0

So, my goal is to count the number of arguments in a list using recursion. However, as I'm only to use one argument in the function call, I don't know how to solve it without a second "count" argument.

So far I have this, where I accumulate the 1's together.

def countElements(a):
    if a==[]:
        return []
    else:
        return [1] + countElements(a[1:])
def main():
    a=[3,2,5,3]
    print(countElements(a))

main()
pastaleg
  • 1,782
  • 2
  • 17
  • 23

1 Answers1

1

Instead of returning an empty list in the base case, return 0, and instead of [1] + countElements(a[1:]), return 1 + countElements(a[1:]). That way, you're just keeping the running count instead of getting a list back.

Randy
  • 14,349
  • 2
  • 36
  • 42