I am trying to reverse order of given numbers in python.The problem says that the first line of the standard input contains one integer t (t<1001) which is the number of numbers.In each of the next t lines there is one integer n (n<1001).
Now I am trying to solve this using recursion trick:
def f(n,a):
if n > 0:
a = input()
f(n-1,a)
print a
f(input(),0)
But this is not working properly since the last number is output twice.How to fix this ?
My obvious solution for this is:
n=input()
a=[1]*n
for i in range(n):a[i]=input()
a=a[::-1]
for i in range(n):print a[i]
If anybody is aware of any other smart solution for the same please enlighten me too.
Thanks
You probably don’t want to print in the ‘n == 0‘ case.
Try indenting the ‘print‘ inside the ‘if‘.
I imagine your ‘a‘ variable is getting re-used in the ‘n == 0‘ case, causing your problem.
Also, is there a particular reason you don’t just read the input into an list, then reverse that list?[I see you know how to do that from your edit] If this is just to experiment, then more power to you. Lists in python have a reverse() function, though (:FWIW, here’s a slight variation on your solution I tried out:
Also, there’s a fun function in Python called reversed(), which returns an iterator.
And lastly, not exactly related, but since you seem to be learning recursion… A handy way to debug your problem might be to put this as the first line of your f() function:
Maybe then it will be clearer why you have the double-print problem.