Hi, I just started learning programming and I was told that Python was good for beginners, and after solving just a few problems I'm already stuck...
I'm suppose to make a function that counts down from the number entered and then up again. Using recursion (if). I can make it go either up or down but not both in one function.
For example if i enter 4 it should do this:
4 3 2 1 0 1 2 3 4
The next problem is the same but using iteration (while) instead of recursion.
I know this must be so easy but the answer eludes me. Thanks!
Need help with 2 simple things
Started by Xenofon, Sep 19 2008 07:01 AM
4 replies to this topic
#1
Posted 19 September 2008 - 07:01 AM
|
|
|
#2
Posted 31 October 2008 - 08:19 AM
you can give another argument in you recursive function that will specify if the counter should go up or down:
Quote
def upAndDown(n, nmax , goingDown): print n if goingDown: if n>0: upAndDown(n-1,nmax,True) else: #etc...
#3
Posted 08 March 2009 - 09:45 AM
This code is short and simple, tested, and works:
n = raw_input("Please enter a number: ");
t = int(n);
r = int(n);
print str(r);
while(r > 0):
r=r-1;
print str(r);
while(t != r):
r=r+1
print str(r);
#4
Posted 10 March 2009 - 10:08 AM
In Python 3:
n = int(input('> '))
print(' '.join(str(abs(x)) for x in range(-n, n+1, 1)))
#5
Posted 10 March 2009 - 12:51 PM
Hi Xenofon (nice name btw),
I made you something as well, but I am cheating a bit :P. I converted the input to an absolute value, so when reached zero, the output is really -1, -2, and so on, but will be converted to 1, 2, etc.
Best regards,
Wilfred
I made you something as well, but I am cheating a bit :P. I converted the input to an absolute value, so when reached zero, the output is really -1, -2, and so on, but will be converted to 1, 2, etc.
import math def AbsoluteValue(x): p = int(math.sqrt(x**2)) return p def UpAndDown(n, Limit) #Limit cannot be lower than n s = AbsoluteValue(n) if s<=Limit: print s UpAndDown(n-1, Limit)
Best regards,
Wilfred


Sign In
Create Account

Back to top









