Reputation: 25
Hey there fellow programmers, I want to check the equality of list elements in a recursive way. The following code snipped should fulfill this task but I might have misunderstood something. If I test the function are_numbers_equal([2, 2, 2, 2]) I get False and not True. I would be thankful for help! Much love <3
The code:
def are_numbers_equal(self, numbers):
if len(numbers) > 1:
return numbers.pop() == self.are_numbers_equal(numbers)
else:
return numbers.pop()
Upvotes: 0
Views: 943
Reputation: 3174
Calling your function ane
you have
ane([2, 2, 2, 2]) = (2 == ane([2, 2, 2]))
= (2 == (2 == ane([2, 2])))
= (2 == (2 == (2 == ane([2]))))
= (2 == (2 == (2 == 2)))
= (2 == (2 == True))
= (2 == False)
= False
Other than the obvious problem with the recursion logic your solution has multiple flaws:
ValueError
)For a detailed answer on how to check if all elements in a list are equal see https://stackoverflow.com/a/3844832/2246024.
Upvotes: 2