2

I'm trying to write a function that checks wether or not the characters in a string are sorted using recursion. This is what I came up with:

def is_sorted(x,i):
    if i >= len(x):
        return True
    elif x[i] <= x[i-1]:
        return False
    else:
        is_sorted(x,i+1)

I used these to test my function:

x = "abcadef"
y = "aabcdef"
z = "abcdef"
print is_sorted(x, 1)
print is_sorted(y, 1)
print is_sorted(z, 1)

I expected to get False, False, True, but instead I got None, False, None. Why? :(

EerlijkeDame
  • 477
  • 3
  • 8
  • 18

2 Answers2

11

You are not returning anything in the last else clause. Hence the result.

def is_sorted(x,i):
    if i >= len(x):
        return True
    elif x[i] <= x[i-1]:
        return False
    else:
        return is_sorted(x,i+1)

Demo:

>>> def is_sorted(x,i):
...     if i >= len(x):
...         return True
...     elif x[i] <= x[i-1]:
...         return False
...     else:
...         return is_sorted(x,i+1)
... 
>>> x = "abcadef"
>>> y = "aabcdef"
>>> z = "abcdef"
>>> print is_sorted(x, 1)
False
>>> print is_sorted(y, 1)
False
>>> print is_sorted(z, 1)
True
>>> 
karthikr
  • 97,368
  • 26
  • 197
  • 188
3

You need to return the function to pass it up the recursive chain

def is_sorted(x,i):
    if i >= len(x):
        return True
    elif x[i] <= x[i-1]:
        return False
    else:
        return is_sorted(x,i+1) # <---- Here
karthikr
  • 97,368
  • 26
  • 197
  • 188
Farmer Joe
  • 6,020
  • 1
  • 30
  • 40