Re: [Tutor] finding factorials
by Kristoffer Erlandsson other posts by this author
Jun 30 2003 9:14AM messages near this date
Re: [Tutor] finding factorials
|
Re: [Tutor] finding factorials
On Mon, Jun 30, 2003 at 01:01:29PM +0530, Payal Rathod wrote:
[...]
> My very basic solution is going totally wrong,
>
> #!/usr/local/bin/python
> def euclid(a,b):
> c = a
> a = b
> b = c % a
> if b != 0:
> euclid(a,b)
> return a
> b = 5
> euclid(10,5)
> print a
>
> It is giving errors. Can someone guide me to a proper solution?
> Thanks a lot and hope this basic question is allowed.
The method you are using now, when you are calling the function itself is
called recursion. I would not recommend using recursion yet in a while,
it can be pretty hard to grasp. Try solving this problem using some kind
of loop instead. A good start for making this loop for this problem would
be something like:
while b != 0:
...
This way you will perform things as long as b is not equal to 0. For
this very problem you will also have to consider the case where b is
larger than a (since the method defined only works for when a is larger
than b).
Also, adding print statements in your function to see what happens at
different stages is a good idea. For example you could print the
values of a and b before and after you change them. This usually is very
helpful when trying to grasp how things work.
The function you have allready made isn't very wrong, I'd say that you
are thinking in the right way, but falling on the mechanics of
recursion.
Hope this helps!
Regards,
--
Kristoffer Erlandsson
E-mail: krier115@[...].se
ICQ#: 378225
_______________________________________________
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
|