You can compare strings directly. x<y means "does x come before y alphabetically?" So you can replace your second block with:
if len(x) == len(y) and x < y:
return x
Answer from AlwaysBTryin on Stack Overflowpython - Checking if a given string is in alphabetical order - Code Review Stack Exchange
list - Python - arranging words in alphabetical order - Stack Overflow
Why is string "b" bigger than string "azzzzzz" ?
python - Check if 3 string inputs are in alphabetical order - Stack Overflow
Videos
This has the advantage of being O(n) (sorting a string is O(n log n)). A character (or string) in Python is "less than" another character if it comes before it in alphabetical order, so in order to see if a string is in alphabetical order we just need to compare each pair of adjacent characters. Also, note that you take range(len(word) - 1) instead of range(len(word)) because otherwise you will overstep the bounds of the string on the last iteration of the loop.
def isInAlphabeticalOrder(word):
for i in range(len(word) - 1):
if word[i] > word[i + 1]:
return False
return True
This is a simple (and Python idiomatic) way to do this:
def isInAlphabeticalOrder(word):
return word==''.join(sorted(word))
>>> isInAlphabeticalOrder('abc')
True
>>> isInAlphabeticalOrder('acb')
False
I am not 100% sure of this, but your code will probably return unexpected results if you use it with accented characters. accènt will probably return false because è is later in the extended ASCII table than n, but humans will view it as alphabetical because they view è the same as e.
There are libraries that can help you with this. https://github.com/kmike/text-unidecode has a more permissive license. https://pypi.python.org/pypi/Unidecode gives slightly better results and performance, but has a GPL license which is harder to use.
Sorting is idempotent, sorting an already sorted list leaves it unchanged.
So checking if a list is ordered equals checking if it equals itself when sorted:
def is_sorted_alphabetically(string):
return string == ''.join(sorted(string))
If you do not want to have a \$O(NlogN)\$ runtime of sorting or you want to implement this yourself without using the sorted built-in, I suggest you avoid recursion and use the all and pairwise helper functions:
def is_sorted(iterable):
return all(x1 <= x2 for x1, x2 in pairwise(iterable))
This is general and works for any iterable such as string but also lists of numbers or lists of anything of comparable (the type is Iterable[Comparable] -> bool)
Python's string comparisons are lexical by default, so you should be able to call max and get away with it:
In [15]: sentence
Out[15]: ['this', 'is', 'a', 'sentence']
In [16]: max(sentence)
Out[16]: 'this'
Of course, if you want to do this manually:
In [16]: sentence
Out[16]: ['this', 'is', 'a', 'sentence']
In [17]: answer = ''
In [18]: for word in sentence:
....: if word > answer:
....: answer = word
....:
In [19]: print answer
this
Or you can sort your sentence:
In [20]: sentence
Out[20]: ['this', 'is', 'a', 'sentence']
In [21]: sorted(sentence)[-1]
Out[21]: 'this'
Or, sort it reversed:
In [25]: sentence
Out[25]: ['this', 'is', 'a', 'sentence']
In [26]: sorted(sentence, reverse=True)[0]
Out[26]: 'this'
But if you want to fully manual (which is so painful):
def compare(s1, s2):
for i,j in zip(s1, s2):
if ord(i)<ord(j):
return -1
elif ord(i)>ord(j):
return 1
if len(s1)<len(s2):
return -1
elif len(s1)>len(s2):
return 1
else return 0
answer = sentence[0]
for word in sentence[1:]:
if compare(answer, word) == -1:
answer = word
# answer now contains the biggest word in your sentence
If you want this to be agnostic of capitalization, be sure to call str.lower() on your words first:
sentence = [word.lower() for word in sentence] # do this before running any of the above algorithms
Use the sort() method.
strings = ['c', 'b', 'a']
strings.sort()
print strings
Output will be,
['a', 'b', 'c']
In case you want the last, you can use the max() method.
Hello guys, I got this code:
x = "azzzzzzzzzzzzzz" y = "b"
if x < y: print(y, "is bigger than ",x) else: print(x, "is bigger than ",y)
result is y is bigger than x.
And I don't understand how can x be smaller than y. What is being compared? Does it only compare first letter's ascii table position? Nothing else seems to make sense. Thank you.
Python can compare strings with < and >: https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types
The problem is you are only printing for the cases of:
- strings are in alphabetical order
- strings are in reverse alphabetical order
Instead, try this:
if name_1 < name_2 and name_2 < name_3:
print("The names are in alphabetical order.")
else:
print("The names are not in alphabetical order.")
You can compare multiple things at the same time by chaining them. This also avoids your incomplete implementation of else (your elif doesn't match all non-alphabetical cases).
name_1, name_2, name_3 = 'a', 'b', 'c'
alphabetical = name_1 < name_2 < name_3
a_str = '' alphabetical else ' not'
print('The names are%s in alphabetical order' % a_str)
This prints The names are in alphabetical order.