Jump to content

Need help with 2 simple things

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Xenofon

Xenofon

    Newbie

  • Members
  • Pip
  • 1 posts
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!

#2
manux

manux

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 234 posts
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
HiGuys

HiGuys

    Newbie

  • Members
  • Pip
  • 2 posts
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
PythonPower

PythonPower

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 230 posts
In Python 3:

n = int(input('> '))

print(' '.join(str(abs(x)) for x in range(-n, n+1, 1)))


#5
WIlfred86

WIlfred86

    Newbie

  • Members
  • Pip
  • 3 posts
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.

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