Bounce code

python

#1

Hi!

I was wondering if someone could help me with a code that takes a number, counts it down with x steps and then up again with the same steps.

As an example:

bounce(10)
10 7 4 1 -2 1 4 7 10
In this, every third integer is written, down and then up. It should be in recursive form, but I wouldn't mind to see it in interative form as well

My attempt:

def bounce(n):
if n<=10:
n=n-3
print (n)
elif n>=0:
n=n+3
print (n)
else:
return ""

This is totally wrong!
Thanks!


#2

I was thinking something like this:

def bounce(n):
    increment = n
    final = []
    if not isinstance(n, int):
        return None
    elif n > 10 or n < 0:
        return None
    final.append(n)
    for i in range(1, 100):
         if increment > 0:
             increment -= 3 * i
             final.append(increment)
         elif increment < 0:
             for i in range(1, 100):
                 if increment >= n:
                      final.append(n)
                          break
                 increment += 3
                 final.append(increment)
        if final[len(final) - 1] = n:
            break
    return final
print bounce(9)

I can't seem to get the breaks to work... it's about complete though.


#3

Thanks a lot buddy, I'll take a look at it :slightly_smiling:


#4

Looks way overkill, shouldn't that just be two ranges with step -3 and +3, some arithmetics to figure out the end-points, convert to string, print? That's a one-liner


solution + examples

Thu Feb 18 22:40:58 [~]
nate@acine >> cat bounce.py 
def bounce(n, step=3):
    print(' '.join(map(str, range(n, -step-1, -step))) + ' ' +
          ' '.join(map(str, range(n%step, n+(1 if n>=0 else -1), step))))
Thu Feb 18 22:41:01 [~]
nate@acine >> python -i bounce.py 
>>> bounce(10)
10 7 4 1 -2 1 4 7 10
>>> bounce(10, 4)
10 6 2 -2 2 6 10
>>> bounce(20, -7)
 
>>> bounce(-20,-7)
-20 -13 -6 1 -6 -13 -20
>>> bounce(20, 7)
20 13 6 -1 6 13 20
>>>

Neat problem.


#5

I wrote something like this (the code increases with 1):

def bounce(n):
while n>=0:
print (n)
n=n-1
while n<=0:
print(n)
n=n+2

The problem is that it doesn't count up . Instead, I get:
bounce(5)

5
4
3
2
1
0
-1


#6

Okay guys, I figured it out. The code should look like this:

def bounce(n):

while n>=1:
    print (n)
    n=n-3

while n<=10:
    print(n)
    n=n+3

bounce(10) gives:
10
7
4
1
-2
1
4
7
10

One can of course change the 10 to something else as an upper limit when it bounces up again.
Thanks for the help you gave me. I tried to solve this without built in functions :slightly_smiling: