How to initialize a tuple in Python using recursion

Question:

I’m working on course work for school, the problem is as follows,

The elements of tuple can be initialized so that tup[i] == i in a recursive fashion as follows:

  • A tuple of size 0 is already initialized
  • Otherwise:
    • set the last element of the tuple to n-1 (where n is the number of elements in the tuple)
    • initialize the portion of the tuple consisting of the first n-1 elements

Write a function named init that takes one argument, a tuple of the proper length, and returns an tuple initialized as described above.

def init(tupin):
    if len(tupin) == 0:
        return tupin
    else:
        return (0,) + init(tupin[1:])

so far this is all I have been able to get.

Asked By: Matthew Berg

||

Answers:

You skipped the step set the last element of the tuple to n-1. You can do that by appending (len(tupin)-1,).

def init(tupin):
    if len(tupin) == 0:
        return tupin
    else:
        return init(tupin[1:]) + (len(tupin)-1, )
Answered By: Barmar

Maybe like this:

def init(tupin):
    if not isinstance(tupin, tuple):
        raise TypeError("Please, supply a tuple to the function")
    if len(tupin):
        return init(tupin[:-1]) + (len(tupin)-1,)
    else:
        return tupin
Answered By: Alex
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.