Reputation: 1074
I am currently learning recursive functions and i have solved this question partially.
For example,if the input is [4,4,3],the output should be true.The successive element has to be at least as big as the previous one.
Here's my code:
def descending(l):
x=0
if len(l)==0 or len(l)==1:
return True
for value in range(0,len(l)):
if l[value]>=l[value]+1:
x=l[value]+1
descending(l[x:len(l)])
return True
else:
return False
Do let me know why my logic fails for certain cases.
Upvotes: 0
Views: 5403
Reputation: 11
def decreasing(l):
if l==[] or len(l) == 1:
return(True)
else:
return( decreasing(l[1:]) if l[0] > l[1] else False)
Upvotes: 1
Reputation: 41895
For me, the key failure of your code is that descending()
returns a value but when you call it recursively, you ignore its return value!
I'm not sure which of the previous answers is more Pythonic than the other but I don't like their style. I'd first clearly lay out your base cases and then end with the recursion:
def descending(array):
if len(array) <= 1:
return True
if array[0] < array[1]:
return False
return descending(array[1:])
I also have a personal hangup against return-else-return logic:
if x:
return a
else:
return b
vs. simply:
if x:
return a
return b
Upvotes: 1
Reputation: 465
If you want this function to be recursive, it should look like this :)
def descending(l):
if len(l) <= 1 or (len(l) == 2 and l[0] >= l[1]):
return True
else:
if l[0] >= l[1]:
return descending(l[1::])
else:
return False
Upvotes: 2
Reputation: 501
If u want to use recursion, you can do it like this:
def foo(l):
if len(l) <= 1:
return True
f, *l = l
return False if f < l[0] else foo(l)
But I strongly not recommend you use recursion for this kind of problems.
Little remark for syntax: f, *l = l
will set f
to first element of l
and set l
to rest part of l, it same to: f, l = l[0], l[1:]
Upvotes: 2
Reputation: 966
I think your code works, but it could easily be more pythonic.
def descending(l):
if not l or len(l) == 1:
return True
elif l[0]>=l[1]:
return descending(l[1:])
else:
return False
Upvotes: 0