+ 1

Reverse of the sequence with recursion

Hi! This is my code to solve the assignment. I used dynamic data structure "l[]". But it must bu solved without using any type of it. How can it be done? def reverse(l): if len(l) > 1: print(l[len(l)-1]) del l[len(l)-1] return reverse(l) else: return l[0] def ss(n): if n != 0: l.append(n) return ss(int(input())) elif n == 0 and len(l) == 0: return n elif n == 0 and len(l) != 0: l.append(n) return reverse(l) l = [] print(ss(int(input())))

10th Jan 2018, 2:41 AM
Yuri Revin
Yuri Revin - avatar
4 ответов
+ 1
So, if I get it right, what you want is to print your input in backwards order as long as input isn't 0. Not sure how python works but maybe this could work: def ss(n): if n != 0: ss(int(input())) print(n) else: return Each call will stop at another ss() call and will resume in backwards order when last call returns (when input is 0)
10th Jan 2018, 7:38 AM
BlazingMagpie
BlazingMagpie - avatar
0
BlazingMagpie, thank you for working example. But it need's to print null too like: def print_reversed(seq, pos=0): elem = seq[pos] if elem != 0: print_reversed(seq, pos + 1) print(elem) print_reversed(tuple(map(int, sys.stdin.read().split())))
12th Jan 2018, 10:39 PM
Yuri Revin
Yuri Revin - avatar
0
Thank you, guys! I solved the issue. So I need to output the null too. And here it is. Thanks for your time & help! def reverse(n): if n != 0: reverse(int(input())) print(n) else: print(n) reverse(int(input()))
14th Jan 2018, 9:37 AM
Yuri Revin
Yuri Revin - avatar