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

Steven D'Aprano steve at pearwood.info
Thu Feb 13 00:02:05 CET 2014


On Wed, Feb 12, 2014 at 10:31:51PM +0100, spir wrote:
> On 02/12/2014 10:14 PM, Steven D'Aprano wrote:

> >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.
[...]

> * 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.

That is not accidental. That is fundamental to the idea of tossing a 
coin to get Heads or Tails. Even if you generalise to more than two 
different events, the sum of each event equals the total number of 
events. Unless you are forgetting to count some events, or counting 
other events twice, how can it be otherwise?


> In 
> the general case, Marc's solution to count each even kind is just right. 

In the *general case* of counting events that occur in N different 
kinds, the total number of events is equal to the sum of each count. So 
if there are six different events, plus the total:

heads
tails
hearts
spades
diamonds
clubs
total

you don't need to record all seven counts (although of course you can if 
you wish) but just six of them, and work out the seventh:

total = sum of heads, tails, hearts, spades, diamonds and clubs

or

heads = total - sum of tails, hearts, spades, diamonds and clubs
    
for example. In the language of statistics, we say that there are six 
degrees of freedom here (the six kinds of events) but seven variables. 
Any one of those variables is completely determined by the other six.


> [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).]

Of course it is. If x ∈ {White, Black}, then if x is not White, then it 
must be Black. There are no other options. There is a one:one 
correspondence between any two-element set and {White, Black}:


white, black = ChessColour("white"), ChessColour("black")
white, black = "white", "black"
white, black = 0, 255
white, black = 255, 0
white, black = -1, 1
white, black = True, False

whichever solution makes your code simpler, more efficient, more easily 
understood, etc.



-- 
Steven


More information about the Tutor mailing list