-1
votes

Since im fairly new to python and programming i have a question of a very basic nature. I want to make a iteration function and a recursive function that does this:

bounce(4)

4 3 2 1 0 1 2 3 4

I know it's propably very simple but any help would be appreciated.

My current code looks like this:

def bounce1(n):
    if n==0:
        print "0",
    else:
        print n,
        bounce1(n-1)

def bounce2(n):
    if n>=1:
        bounce2(n-1)
        print n

def bounce(n):
    bounce1(n)
    bounce2(n)
2
Recursion? Are you sure about this? - Malik Brahimi
The range function will probably be useful to you. Did you know? You can give negative numbers to range's third parameter. - Kevin
What have you tried so far? StackOverflow is not for building programs for you, but for helping you with specific programming questions. Please post what code you have tried, and if you've tried nothing, attempt the problem yourself first. - David Reeve
@Kevin There's not need for the 3rd parameter of range: f=lambda x:map(abs,range(-x,x+1)) [NEW LINE] for x in f(4):print x, - mbomb007
@Raindeerstream Your code works already. The indentation was just incorrect. - mbomb007

2 Answers

2
votes

Iterative implementation:

>>> def bounce(num):
...     limit, delta = num + 1, -1
...     while(num != limit):
...         print num
...         num += delta
...         if num == 0:
...             delta = 1

Recursive implementation:

>>> def bounce(num):
...     print num
...     if num: 
...         bounce(num - 1)
...         print num
...         
... 

Output in both the cases:

>>> bounce(4)
4
3
2
1
0
1
2
3
4
1
votes

If you can use range, I would do it like this in Python 2.7:

f = lambda x : map(abs, range(-x,x+1))
for x in f(4):
    print x,