[Tutor] Beginner - explaining 'Flip a coin' bug

spir denis.spir at gmail.com
Wed Feb 12 22:31:51 CET 2014


On 02/12/2014 10:14 PM, Steven D'Aprano wrote:
> On Wed, Feb 12, 2014 at 03:25:22PM +0000, Marc Eymard wrote:
>
>> I want to emulate a coin flip and count how many heads and tails when
>> flipping it a hundred times.
>
>
> In my last reply, I said I'd next give you some pointers to
> improve the code. If you'd rather work on it yourself first, stop
> reading now!
>
> In your working code, you have (in part):
>
>
> count_heads = 0
> count_tails = 0
> count_flips = 0
> while count_flips != 100:
>      coin_side = random.randint(1,2)
>      count_flips += 1
>      if coin_side == 1:
>          count_heads += 1
>          #count_flips += 1
>      else: count_tails += 1
>      #count_flips += 1
>
>
> The first thing to notice is that by the logic of the task, each flip
> must be either a Head or a Tail, so the number of Heads and the number
> of Tails should always add up to the number of flips. So you don't need
> to record all three variables, you only need two of them.
>
> The second thing is that since the number of flips is incremented by one
> every single time through the loop, regardsless of what happens, you
> don't need to manually increment that. You can get Python to do the
> counting for you, using a for-loop:
>
> for count_flips in range(1, 101):
>      coin_side = random.randint(1,2)
>      if coin_side == 1:
>          count_heads += 1
>
>
> At the end of the loop, you will have count_flips equal to 100 (can you
> see why?) and the number of Tails will be count_flips - count_heads.

Actually, there are 2 distinct points:
* That one doesn't need to count flips: right.
* That one needs only to count one eveny kind is accidental, just because there 
are here only 2 event kinds, so that number of tails+heads=flips. In the general 
case, Marc's solution to count each even kind is just right. [To compare, there 
are people using bools to represent 2 distinct cases (eg black & white in a 
chass game), and it's conceptually wrong: white is not not(black).]

d


More information about the Tutor mailing list