Project Euler #54: Poker hands

  • + 0 comments

    100/- points python 3

    import collections
    
    numbers=['2','3','4','5','6','7','8','9','T','J','Q','K','A']
    #numbers_2=['A','2','3','4','5','6','7','8','9','T','J','Q','K']
    
    def ranker(cards):
        suits=[i[-1] for i in cards]
        if len(set(suits))==1:
            same_suit=True
        else:
            same_suit=False
        
        values=[numbers.index(i[0]) for i in cards]
        # values_2=[numbers_2.index(i[0]) for i in cards]
        values.sort(reverse=True)
        if values==[12,3,2,1,0]:
            if same_suit:
                return (8,3)
            else:
                return (4,3)
        # values_2.sort(reverse=True)
        differences=[values[i]-values[i+1] for i in range(4)]
        groups=[] # I could have grouped by using itertools.groupby but I wanted to write it alorithmically
        differences.append(-1) #pre-processing to obtain last interval too
        start=0
        for i in range(1,len(differences)):
            if differences[i]!=differences[i-1]:
                groups.append((differences[i-1],i-start))
                start=i
        
        if (1,4) in groups :
            consecutive_values=True
        else:
            consecutive_values=False
        
        values_same=[i[0] for i in collections.Counter(values).most_common()] #this is coool
    
        if same_suit and consecutive_values:
            return (8,max(values))
        elif (0,3) in groups:
            # if values[0]!=values[1]:
            #     if values[0]!=values[2]:
            #         ans=(values[1],values[0])
            #     else:
            #         ans=(values[0],values[1])
            # else:
            #     ans=(values[0],int(set(values).difference([values[0]])))
            # return (7,*ans)
            return (7,*values_same)        
        elif (0,1) in groups and (0,2) in groups: 
            return (6,*values_same)
        elif same_suit:
            return (5,*values)
        elif consecutive_values:
            return (4,max(values))
        elif (0,2) in groups:
            return (3,*values_same )
        elif groups.count((0,1))==2:
            return (2,*values_same)
        elif (0,1) in groups:
            return (1,*values_same)
        else:
            return (0,*values)
                    
    def sorter(pl1,pl2): 
        size=min(len(pl1),len(pl2))
        for i in range(size):
            if pl1[i]>pl2[i]:
                return 'Player 1'
            elif pl1[i]<pl2[i]:
                return 'Player 2'
            
    for _ in range(int(input())):
        cards=input().split()
        pl1=cards[:5]
        pl2=cards[5:]
        print(sorter(ranker(pl1),ranker(pl2)))