T.Black
T.Black

Reputation: 25

Recursion check if list elements are equal

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

Answers (1)

Simon Fromme
Simon Fromme

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:

  • it modifies the input list (list is empty after processing)
  • it surely fails for a single-element-list
  • it doesn't account for the case where the list ist empty (e.g. by raising a ValueError)
  • it is really inefficient (the list is entirely traversed in each recursion step)

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

Related Questions