Re: [Tutor] finding factorials
by Danny Yoo other posts by this author
Jun 30 2003 5:33PM messages near this date
Re: [Tutor] finding factorials
|
Re: [Tutor] finding factorials
> I have given my solution below, but still I am not able to get this
> using functions. Can anyone give more hints? I have given both working
> and non-working solution below. Check the comments.
>
>
>
> #!/usr/local/bin/python
> # Non-Working Solution
> def euclid(a,b):
> while b != 0:
> c = a
> a = b
> b = c % a
> print 'A = ', a
> print 'B = ', b
> return a
>
> x = 100
> y = 5
>
> euclid(x, y) ### <---- bug here
>
Hi Payal,
Same mistake as last time. *grin* The code is simply dropping the value
that you're calculating from doing euclid(). We need to capture that
value:
###
result = euclid(x, y)
print x
print y
print "GCD is", result
###
Otherwise, your program appears to work ok.
The thing that you need to feel more familiar with is the idea that
functions return things back.
Here's another example of a set of functions:
###
def square(x):
return x * x
def sqrt(x):
return x ** (0.5)
def hypotenuse(a, b):
return sqrt(square(a) + square(b))
###
The last example is important: it shows that once we define a good
function, we can use it as if it were part of the Python language itself.
We could have written hypotenuse() without using square() or sqrt():
###
def hypotenuse(a, b):
return ((a * a) + (b * b))**(0.5)
###
And, in this example, this even appears slightly shorter than the more
verbose definition. But I'd argue that the first version is a little
easier on the eyes. *grin*
Hope this helps!
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Payal Rathod
lonetwin
Kristoffer Erlandsson
Payal Rathod
Gregor Lingl
Danny Yoo
Payal Rathod
Danny Yoo
Gregor Lingl
Danny Yoo
|