开发者

Reverse order of given numbers in python

I am trying to reverse order of giv开发者_开发百科en 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:

def f(n):
    if n == 0:
        return
    a = input()
    f(n-1)
    print a

f(input())

Also, there's a fun function in Python called reversed(), which returns an iterator.

x = [1,2,3]
for i in reversed(x):
    print i    # prints 3, 2, 1

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:

print '>' * n, n, a

Maybe then it will be clearer why you have the double-print problem.


Here was my solution:

def f(n,a=None):
    if n > 0:
        f(n-1, input())
    if a is not None:
        print a

f(input())

It bugs me a little bit that I had to use the check on a, but then I realized this question is a bit artificial anyway. You don't need to know the number of items in the list in order to reverse it. Of course the None is in case 0 appears in the inputs.

Demo:

$ <<< '5
7
4
1
0
8' python Desktop/foo.py 
8
0
1
4
7
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜