Question

Python: Lee has discovered what he thinks is a clever recursive strategy for printing the elements...

Python:

Lee has discovered what he thinks is a clever recursive strategy for printing the elements in a sequence (string, tuple, or list). He reasons that he can get at the first element in a sequence using the 0 index, and he can obtain a sequence of the rest of the elements by slicing from index 1. This strategy is realized in a function that expects just the sequence as an argument. If the sequence is not empty, the first element in the sequence is printed and then a recursive call is executed. On each recursive call, the sequence argument is sliced using the range 1:. Here is Lee’s function definition:

def printAll(seq):
    if seq:
        print(seq[0])
        printAll(seq[1:])

Write a program that tests this function and add code to trace the argument on each call. Does this function work as expected? If so, are there any hidden costs in running it?

Grading

When you have completed your program, click the Submit button to record your score.

Homework Answers

Answer #1

def printAll(seq):

print ('printAll(%s)' % seq) #for tracing arguments

if seq:

print(seq[0])

printAll(seq[1:])

n=int(input("Enter the no of sequence:"))

seq = []

for i in range(n):

seq.append(int(input())) #geting input of sequence from user

printAll(seq) #calling the function

Screen Shot

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions