파이썬 풀이
앞서 Swift와 동일한 알고리듬으로 작성된 코드이다. 파이썬의 경우, 튜플을 비교하면 앞에 있는 원소부터 차례로 비교해준다.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from urllib.request import urlopen | |
""" | |
Straight Flush : 95,000 (Straight + Flush) | |
Four Kind : 80,000 | |
Full House : 55,000 ( Three Kind + One Pair) | |
Flush : 50,000 | |
Straight : 45,000 | |
Three of a Kind: 40,000 | |
Two Pair : 30,000 (One Pair + One Pair) | |
One Pair : 15,000 | |
""" | |
def poker(data): | |
priorities = "23456789TJQKA" | |
numbers = dict() | |
faces = dict() | |
cards = data.split() | |
for card in cards: | |
faces[card[1]] = faces.setdefault(cards[1], 0) + 1 | |
card_number = priorities.index(card[0])+2 | |
numbers[card_number] = numbers.setdefault(card_number, 0) + 1 | |
value, h1, h2 = 0, 0, 0 | |
## Four of a Kind | |
g = [k for k, v in numbers.items() if v == 4] | |
if g: | |
value += 80_000 | |
if h1 is 0: | |
h1 = g[0] | |
## Flush | |
g = [x for x in faces.items() if x[1] == 5] | |
if g: | |
value += 50_000 | |
if h1 is 0: | |
h1 = max(numbers.keys()) | |
## Straight | |
keys = ''.join(sorted((x[0] for x in cards), key=lambda x: priorities.index(x))) | |
if keys in priorities: | |
value += 45_000 | |
if h1 is 0: | |
h1 = max(numbers.keys()) | |
## Three of a Kind | |
g = [k for k, v in numbers.items() if v == 3] | |
if g: | |
value += 40_000 | |
if h1 is 0: | |
h1 = g[0] | |
## Pairs | |
g = [k for k, v in numbers.items() if v == 2] | |
for n in sorted(g, reverse=True): | |
value += 15_000 | |
if h1 is 0: | |
h1 = n | |
elif h2 is 0: | |
h2 = n | |
## High Cards | |
for n in sorted([k for k, v in numbers.items() if v == 1], reverse=True): | |
if h1 is 0: | |
h1 = n | |
elif value > 0 and h2 is 0: | |
h2 = n | |
return (value, h1, h2) | |
def main(): | |
contents = urlopen('http://euler.synap.co.kr/files/poker.txt').read().decode() | |
rounds = contents.splitlines() | |
result = 0 | |
for round in rounds: | |
pos = len(round) // 2 | |
p1, p2 = poker(round[:pos]), poker(round[pos:]) | |
if p1 > p2: | |
result += 1 | |
print(result) | |
main() |