Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to initialize a tuple in Python using recursion

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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, )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading