Is inifinite loop not a good practice?
Felipe Almeida Lessa
felipe.lessa at gmail.com
Mon Feb 20 19:32:07 EST 2006
Em Seg, 2006-02-20 às 17:01 -0500, Roy Smith escreveu:
> In article <mailman.2182.1140471719.27775.python-list at python.org>,
> "Terry Reedy" <tjreedy at udel.edu> wrote:
> > def fact(n):
> > res = 1
> > while n != 0:
> > res *= n
> > n -= 1
> > return res
> >
> > fact(-1)
>
> Could be worse. You could have written:
>
> def fact(n):
> if n == 0:
> return 1
> else:
> return n * fact (n-1)
>
> then you would have not only gotten zonked on CPU charges, but on memory
> charges as well :-)
This is not worse. Sometime in the future the function will raise a
RuntimeError with "maximum recursion depth exceeded" and free all system
resources, but the other one (without recursive calls) will only grow
and grow and grow...
--
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."
-- Sun Tzu, em "A arte da guerra"
More information about the Python-list
mailing list