Home > Software design >  How to initialize a tuple in Python using recursion
How to initialize a tuple in Python using recursion

Time:09-10

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.

CodePudding user response:

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, )

CodePudding user response:

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
  • Related