Iteration for Factorials
Steven Bethard
steven.bethard at gmail.com
Mon Oct 22 14:51:37 EDT 2007
Michael J. Fromberger wrote:
> # Not legal Python code.
> def fact3(n, acc = 1):
> TOP:
> if n > 0
> n = n - 1
> acc = acc * n
> goto TOP
> else:
> return acc
Yes, to write this in legal Python code, you have to write::
from goto import goto, label # http://entrian.com/goto/
def fact3(n, acc = 1):
label .TOP
if n > 0
n = n - 1
acc = acc * n
goto .TOP
else:
return acc
;-)
STeVe
>
> Naturally, of course, Python does not provide a "goto" statement. But
> it does have one that's similar:
>
> while TEST: BODY
>
> is equivalent in meaning to the pseudo-code:
>
> X: if TEST:
> BODY
> goto X
>
> Can you now see how you would re-write "fact3" into legal Python code,
> using this equivalence? Once you have done so, you will also be able to
> get rid of the extra accumulating parameter, and then you will have what
> you wanted.
>
> I hope this helps.
>
> Cheers,
> -M
>
More information about the Python-list
mailing list