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...

holaprofesor
  • 271
  • 4
  • 15

2 Answers2

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)
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
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)])
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • You don't actually need to create a temporary list: `return tuple(num**2 for num in range(start, stop))`. [_since python 2.4_](https://www.python.org/dev/peps/pep-0289/) – Bill Lynch Mar 25 '15 at 20:35
  • 1
    @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](http://stackoverflow.com/a/9060697/3058609) – Adam Smith Mar 25 '15 at 20:37
  • @AdamSmith Look at my test here: http://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) – Shashank Mar 25 '15 at 20:54