Wednesday, September 21, 2016

Non-transitive dice in Python



All dies are fair and six-sided but with differing numbers on each face.
One die is said to be stronger, > than another if that die has a higher probability of rolling a higher number than the other and so winning.
In [29]:
from itertools import product
from collections import namedtuple
In [35]:
Die = namedtuple('Die', 'name, faces')
dice = [Die('A', [3,3,3,3,3,3]),
        Die('B', [4,4,4,4,0,0]),
        Die('C', [5,5,5,1,1,1]),
        Die('D', [2,2,2,2,6,6])]
In [44]:
def cmp_die(die1, die2):
    'compares two die returning <, > or ='
    # Numbers of times one die wins against the other for all combinations
    win1 = sum(d1 > d2 for d1, d2 in product(die1, die2))
    win2 = sum(d2 > d1 for d1, d2 in product(die1, die2))
    return '>' if win1 > win2 else ('<' if win1 < win2 else '=')
In [45]:
dice
Out[45]:
[Die(name='A', faces=[3, 3, 3, 3, 3, 3]),
 Die(name='B', faces=[4, 4, 4, 4, 0, 0]),
 Die(name='C', faces=[5, 5, 5, 1, 1, 1]),
 Die(name='D', faces=[2, 2, 2, 2, 6, 6])]
In [46]:
cmp_die(dice[0].faces, dice[1].faces)
Out[46]:
'<'
In [47]:
shortform = []
for (n1, f1), (n2, f2) in zip(dice, dice[1:] + dice[:1]):
    comparison = cmp_die(f1, f2)
    print('%s: %r %s %s: %r' % (n1, f1, comparison, n2, f2))
    shortform.append('%s %s %s' % (n1, comparison, n2))
print('\nIn short:', ', '.join(shortform))
    
A: [3, 3, 3, 3, 3, 3] < B: [4, 4, 4, 4, 0, 0]
B: [4, 4, 4, 4, 0, 0] < C: [5, 5, 5, 1, 1, 1]
C: [5, 5, 5, 1, 1, 1] < D: [2, 2, 2, 2, 6, 6]
D: [2, 2, 2, 2, 6, 6] < A: [3, 3, 3, 3, 3, 3]

In short: A < B, B < C, C < D, D < A
Notice that it forms a circle of winning die!

Monday, March 14, 2016

Mathematicians Discover Prime Conspiracy: Python check


In the article Mathematicians Discover Prime Conspiracy essentially is described the discovery that the last digit of the next prime number is less likely to equal the last digit of its predecessor.
To check this I decided to download a list of the first million prime numbers from here and check.
In [27]:
from collections import defaultdict

this2previous = defaultdict(int)
previous = None
with open('primes1.txt') as f:
    # Skip text file header
    print(f.readline())
    for line in f:
        line = line.strip()
        if not line:
            continue
        for primelastdigit in (prime[-1] for prime in line.split()):
            if previous is not None:
                this2previous[(primelastdigit, previous)] += 1
            previous = primelastdigit
                 The First 1,000,000 Primes (from primes.utm.edu)

In [28]:
def pretty_print(counts):
    lastdigit = None
    for (this, previous), count in sorted(counts.items()):
        if this in '25' or previous in '25':
            continue
        if lastdigit != this:
            print()
        lastdigit = this
        print('%2s %s after %s frequency: %6i' 
              % (('#' if this == previous else ''), this, previous, count))
In [29]:
pretty_print(this2previous)
 # 1 after 1 frequency:  42853
   1 after 3 frequency:  58255
   1 after 7 frequency:  64230
   1 after 9 frequency:  84596

   3 after 1 frequency:  77475
 # 3 after 3 frequency:  39668
   3 after 7 frequency:  68595
   3 after 9 frequency:  64371

   7 after 1 frequency:  79453
   7 after 3 frequency:  72827
 # 7 after 7 frequency:  39603
   7 after 9 frequency:  58130

   9 after 1 frequency:  50153
   9 after 3 frequency:  79358
   9 after 7 frequency:  77586
 # 9 after 9 frequency:  42843
As you can see, the frequency of the last digit being followed by the same last digit in consecutive prime numbers (for this sample of the first million primes), is markedly lower.

Friday, February 05, 2016

Mind boggling card trick in Python


A Python version of the Mind boggling card trick.


Get a pack of 52 cards, half red - half black. (You might need to find those missing cards from that old pack)
In [61]:
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2) 
reds = [Red] * (n // 2)
pack = blacks + reds

Shuffle the pack!

Give the pack a good shuffle. (Don't drop any).
In [62]:
import random
random.shuffle(pack)

Deal those random cards

  1. Assemble the cards face down.
  2. Turn up the top card, if it is black then add the next card, unseen, to the black-stack. If it is red then instead add that next card, unseen, to the red-stack.
  3. Add the card you turned over to see what colour it was above to the discard stack.
  4. Repeat the above for the whole pack.
In [63]:
black_stack, red_stack, discard = [], [], []
while pack:
    top = pack.pop()
    print(top[0], end=' ')
    if top == Black:
        black_stack.append(pack.pop())
    else:
        red_stack.append(pack.pop())
    discard.append(top)
print()
            
R B R R B R R R B B B B B B B B R R B B B R R R R R 
There is still randomness present. The discard stack shown above seems pretty random.

Swap the same, random, number of cards between the two stacks.

We can't swap more than the number of cards in a stack.
In [64]:
max_swaps = min(len(black_stack), len(red_stack))
Randomly choose the number of cards to swap. (You could use a dice).
In [65]:
swap_count = random.randint(0, max_swaps)
print('Swapping', swap_count)
Swapping 11
Randomly choose that number of cards out of each stack to swap. (Without knowing those cards - they could be red or black cards from the stacks, we don't know)
In [66]:
def random_partition(stack, count):
    "Partition the stack into 'count' randomly selected members and the rest"
    sample = random.sample(stack, count)
    rest = stack[::]
    for card in sample:
        rest.remove(card)
    return rest, sample

black_stack, black_swap = random_partition(black_stack, swap_count)
red_stack, red_swap = random_partition(red_stack, swap_count)
Perform the swap.
In [67]:
black_stack += red_swap
red_stack += black_swap

Order from randomness?

The mathematician asserts that:
  • The number of black cards in the black pile equals the number of red cards in the red pile
In [68]:
if black_stack.count(Black) == red_stack.count(Red):
    print('Yea! The mathematician is right.')
else:
    print('Woops - That mathematician (or my card manipulations) are flakey')
Yea! The mathematician is right.