1

I am trying to write two functions that take an integer and return a tuple. I can get very close to what would like to return, but what I am returning has multiple parenthesis within it. for example, I want rec_range(5) to return (0,1,2,3,4) instead of (((((0, 1), 2), 3), 4).

Here are the two functions I am writing

def rec_range(n):
    '''Takes a natural number n and returns a tuple of numbers starting
       with 0 and ending before n.
       Int-->Tuple'''

    if n == 0:
         return 
    if n == 1:
        return 0
    if n >= 1:
        return rec_range(n-1),(n-1)

def squares_tuple(n,m):
    '''Takes a natural numbers n and m and returns a tuple of the squares
       of all the natural numbers starting with n and ending with m-1.
       Int,Int-->Tuple'''

    while n<=m:
        return n * n, squares_tuple(n + 1, m)
David Robinson
  • 77,383
  • 16
  • 167
  • 187
Brett
  • 183
  • 3
  • 9

2 Answers2

3

This is because you're using the return value from your recursive calls as a single element in a new tuple, rather than constructing a tuple from the elements in the return value plus new elements.

Instead, you should probably be adding tuples together:

return rec_range(n-1) + (n-1,)

and

return (n*n,) + squares_tuple(n+1, m)

Note that doing this means that your functions need to always return a tuple (which is probably a good thing, because sometimes returning one data type and sometimes another is a good way to create runtime errors), so you need to adjust some of your other non-recursive returns as well - for instead, instead of return 0 you'd want to use return (0,).

Amber
  • 507,862
  • 82
  • 626
  • 550
2

Two issues: first, you need to return a tuple, rather than an int, for your base case:

if n == 1:
    return (0,)

Second, you need to append n - 1 to the tuple rather than return it as a pair with the tuple:

if n >= 1:
    return rec_range(n-1) + (n-1,)

Your squares_tuple can be solved by a similar approach. Note that I changed the base case to return an empty tuple rather than None. (I also changed while to if, which makes it a bit clearer since it happens only once).

if n<=m:
    return (n * n,) + squares_tuple(n + 1, m)
return ()
David Robinson
  • 77,383
  • 16
  • 167
  • 187