• + 3 comments

    This is similar to the "Normal" nim game except for the case where all piles are '1'. We can take advantage of the fact that if all piles are '1' than the xoring of all piles will be '0' if there are even number of piles (Second player wins) and '1' if there are odd number of piles (First player wins). If not all piles are '1' we are back to the norma nim game (xoring of all piles).

    Xor = bitwise xoring of all piles. All1 = All piles are '1'

    Xor   All1  F/S
     0      0    S
     0      1    F   (There are even number of piles and all are '1')
     1      0    F
     1      1    S  (There are odd number of piles and all are '1')
    

    So Xor ^ All1 will give the final result:

    from functools import reduce
    def misereNim(piles):
        all1 = all(map(lambda x: x==1,piles))
        xor = reduce(lambda x,h: x^h, piles)
        return 'First' if bool(xor) ^ all1 else 'Second'
    

    Can be done more efficiently, but less readable:

    [xor,all1] = reduce(lambda res,h: [res[0]^h, res[1] and h==1], piles, [0,True])
    

    `