1

I want to build a function that takes two 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. I am able to decide if the function should return if m is smaller than n, but it shouldn't crash or return some sort of error message. So squares_tuple(3,7) returns (9,16,25,36) and rec_range(10,11) returns (100,). Also, I do not want to use range(), map(), loops, or lists. Here is what I have so far:

def squares_tuple(n,m):
"""takes two nat nums n and m and returns a tuple of the squares of all the
natural numbers starting with n and ending with m-1

nat, nat -> tuple of natural numbers"""
   if m >= 0:
       return 0
   else:
       return squares_tuple(n - 1, ) + (n**m, )

Kind of stuck at this point...

1
  • 1
    Don't you want that to be if m <= 0:? Commented Mar 25, 2015 at 20:31

2 Answers 2

4
def squares_tuple(n, m):
    return (n * n, ) + squares_tuple(n + 1, m) if n < m else ()

Example:

>>> squares_tuple(0, 6)
(0, 1, 4, 9, 16, 25)
>>> squares_tuple(3, 7)
(9, 16, 25, 36)
Sign up to request clarification or add additional context in comments.

2 Comments

@AdamSmith You cannot add a list to a tuple so you cannot cast your return type to a tuple.
@Shashank bah, you're right. I'm terrible with recursing functions. Deleted my comment.
1

Does this have to be a recursive function? If not then the best solution is:

def squares_tuple(start, stop):
    return tuple([num**2 for num in range(start, stop)])

3 Comments

You don't actually need to create a temporary list: return tuple(num**2 for num in range(start, stop)). since python 2.4
@BillLynch I haven't profiled, but in a few of those kinds of "building from a completed list" functions using the list comp is actually faster. see the comments on this answer
@AdamSmith Look at my test here: repl.it/f2h Adding the tuples is doable in a lower amount of time. Note that I created both the lists and the tuples in the setup phase so I'm only testing the add operator time. (Creating tuples is also faster than creating lists)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.