patternpythonModerate
Checking if a given string is in alphabetical order
Viewed 0 times
ordercheckingalphabeticalstringgiven
Problem
I wrote this function to check if a given string is in alphabetic order. How can I improve?
def alphacheck(x):
'''This function checks if a given string is in Alphabetical order'''
# Creating a variable to allow me to efficiently index a string of any length
i = len(x) - 1
# Using a recursive formula and checking for the base case when the string is of less than one character
if len(x) <= 1:
return True
# This the recursive portion of the formula
else:
# This code checks if the last two characters are in alphabetical order
# By utilizing the property that the letters of the alphabet increase in "value" accroding to python
if x[i - 1] <= x[i]:
# I remove the last letter of the string to reduce the probelm size
x = x[:i]
# I then repeat this on the smaller string until it reaches the base case or
# Finds out the string is not in alphabetical order and returns False
return alphacheck(x)
else:
return FalseSolution
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:
If you do not want to have a \$O(NlogN)\$ runtime of sorting or you want to implement this yourself without using the
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
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)Code Snippets
def is_sorted_alphabetically(string):
return string == ''.join(sorted(string))def is_sorted(iterable):
return all(x1 <= x2 for x1, x2 in pairwise(iterable))Context
StackExchange Code Review Q#141725, answer score: 11
Revisions (0)
No revisions yet.