Skip to content

Commit d00628b

Browse files
committed
running for president
1 parent 421d156 commit d00628b

File tree

1 file changed

+68
-0
lines changed
  • 2-hard/running-for-president

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
from collections import namedtuple
2+
import sys
3+
4+
Issue = namedtuple("Issue", "name cost")
5+
State = namedtuple("State", "name votes totalRelevance issueRelevance")
6+
7+
def get_cost(issues):
8+
return sum(map(lambda x: x.cost, issues))
9+
10+
def can_win_state(issues, state):
11+
relevance = sum([state.issueRelevance[issue] for issue in issues])
12+
return relevance * 2 > state.totalRelevance
13+
14+
def can_win(states, issues):
15+
return sum([state.votes for state in states if can_win_state(issues, state)]) >= 270
16+
17+
def get_minimal_issues(allIssues, states, taken, best):
18+
if can_win(states, taken):
19+
return taken
20+
21+
for issue in allIssues:
22+
if issue in taken:
23+
continue
24+
25+
next_taken = list(taken)
26+
next_taken.append(issue)
27+
28+
if best is not None and get_cost(best) <= get_cost(next_taken):
29+
continue
30+
31+
min = get_minimal_issues(allIssues, states, next_taken, best)
32+
if min is not None:
33+
best = min
34+
35+
return best
36+
37+
def main():
38+
lines = [i.strip().split(": ") for i in open(sys.argv[1], 'r') if len(i.strip()) > 0]
39+
40+
issueCount = int(lines.pop(0)[1])
41+
42+
issues = {}
43+
for _ in range(issueCount):
44+
line = lines.pop(0)
45+
name = line[0]
46+
issues[name] = Issue(name=name, cost=int(line[1]))
47+
48+
states = []
49+
50+
while len(lines) > 0:
51+
name = lines.pop(0)[0]
52+
votes = int(lines.pop(0)[1])
53+
issueRelevance = {}
54+
totalRelevance = 0
55+
56+
for _ in range(issueCount):
57+
s = lines.pop(0)
58+
relevance = int(s[1])
59+
totalRelevance += relevance
60+
issueRelevance[issues[s[0]]] = relevance
61+
62+
states.append(State(name=name, votes=votes, totalRelevance=totalRelevance, issueRelevance=issueRelevance))
63+
64+
for x in get_minimal_issues(sorted(issues.values(), key=lambda x: x.cost), states, [], None):
65+
print(x.name)
66+
67+
if __name__ == "__main__":
68+
main()

0 commit comments

Comments
 (0)