Reputation: 49
I am trying to implement a function in python that given two strings it checks if the first string is smaller than the second string in the lexicographic order. This is what I managed to write, I do not claim that it is elegant code
import string
#first make a dictionary that gives the value of a letter, eg "C":3
d = dict.fromkeys(string.ascii_uppercase, 0)
i=1
for c in d.keys():
d[c] = i
i+=1
def lexico(str1,str2):#returns true if str1<=str2 in lexicographic order
print(str1,str2) #printing for debugging purpose
if str1 == '' and str2 == '':
return True
elif str1 != '' and str2 == '':
return False
elif str1 == '' and str2 != '':
return True
elif d[str1[0]] > d[str2[0]]:
return False
elif d[str1[0]] < d[str2[0]]:
return True
elif str1 == str2:
return True
else:
print(str1,str2) #printing for debugging purpose
lexico(str1[1:],str2[1:])
str1 = 'ANGELA'
str2 = 'AMY'
print(lexico(str1,str2))
I have really no idea what goes wrong here, but the output is as follows
ANGELA AMY
ANGELA AMY
NGELA MY
None
The function does not return anything, and I dont know why.
Upvotes: 0
Views: 885
Reputation: 3494
You are missing a return on this line: lexico(str1[1:],str2[1:])
. It should be return lexico(str1[1:],str2[1:])
.
Upvotes: 2