[Tutor] Re: Fixed freezing problem, have new one
Derrick 'dman' Hudson
dman@dman.ddts.net
Sat Jan 11 20:05:02 2003
--lrZ03NoBR/3+SXJZ
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
On Sun, Jan 12, 2003 at 12:48:49AM +0000, Guess Who? Me wrote:
First I notice you are starting to pick up on one error :
| number=3Dnumber+1
^^
| return total,dice(number-2,sides)
^^
Since you (incorrectly) incremented by one first, you have to
decrement by two to compensate. The correction is to simply decrement
by one in the first place.
Second, note the overall structure of the loop :
while [condition] :
[something]
return [value]
It isn't really a loop, even though it is spelled like one. That code
can equivalently be written as
if [condition] :=20
[something]
return [value]
or
if not [condition] : return None
[something]
return [value]
| return total,dice(number-2,sides)
^
Next look at the type of data you are returning. It is a tuple
consisting of the random number chosen and the results of the dice()
function. Looking at the dice() function, it returns a tuple. So
what you end up with is a tuple containing a number and a tuple (which
contains a number and a tuple ...). Hence the output looking like :
(1, (4, (1, (0, (1, (0, None))))))
^^ ^^ ^^ ^^ ^^ ^^ ^^^^
|| || || || || || |
|| || || || || || - the last run gave no result, hence the
|| || || || || || implicitly returned None
|| || || || || |- a number
|| || || || || - a tuple
|| || || || |- a number
|| || || || - a tuple
(etc.)
Recursion is fine. It is a different way of expressing the same
concept a loop expresses. Sometimes a loop is a shorter and easier
way to write it, sometimes recursion is, sometimes it is just good to
practice :-).
If you want to do this with recursion instead of a loop, try this :
def dice(number,sides): #number being the number of times you roll
if number <=3D 0 :
# if we don't roll, we get nothing
return None
# roll and see what we get
value =3D random.randint(0,sides)
if number =3D=3D 1 :
# if we roll once we get only 1 number
return value
else :
# we add up the rest of our rolls.
total =3D value + dice( number-1, sides )
# ^^ only decrement by one
return total # return just a single number
See if you understand the difference here.
HTH,
-D
--=20
Religion that God our Father accepts as pure and faultless is this: to
look after orphans and widows in their distress and to keep oneself from
being polluted by the world.
James 1:27
=20
http://dman.ddts.net/~dman/
--lrZ03NoBR/3+SXJZ
Content-Type: application/pgp-signature
Content-Disposition: inline
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iEYEARECAAYFAj4gvx4ACgkQO8l8XBKTpRSeNwCeOgciGIpDK1fBNBiPAb606eDE
9yQAniJytig1cT4vCi01xFZV3HYcp1v/
=Fkmj
-----END PGP SIGNATURE-----
--lrZ03NoBR/3+SXJZ--