4 # formats: ipynb,py:light
8 # format_version: '1.5'
9 # jupytext_version: 1.11.1
11 # display_name: Python 3 (ipykernel)
16 # # Honeycomb letter puzzle
17 # Solving the puzzle as posted on [FiveThirtyEight](https://fivethirtyeight.com/features/can-you-solve-the-vexing-vexillology/), also solved by [David Robinson](http://varianceexplained.org/r/honeycomb-puzzle/).
22 from dataclasses
import dataclass
26 with
open('enable1.txt') as f
:
27 words
= [line
.strip() for line
in f
]
29 words
= set(w
for w
in words
31 if len(frozenset(w
)) <= 7
34 word_sets
= collections
.defaultdict(set)
36 letters
= frozenset(w
)
37 word_sets
[letters
].add(w
)
40 @dataclass(frozen
=True)
46 return f
'{self.mandatory}|{"".join(sorted(self.letters - set(self.mandatory)))}'
49 def present(target
, honeycomb
):
50 return ( (honeycomb
.mandatory
in target
)
51 and target
.issubset(honeycomb
.letters
)
55 def score(present_set
):
57 for w
in word_sets
[present_set
]:
62 if len(present_set
) == 7:
63 score
+= len(word_sets
[present_set
]) * 7
67 def score_honeycomb(honeycomb
):
68 return sum(sc
for letters
, sc
in scored_sets
.items()
69 # if honeycomb.mandatory in letters
70 # if letters.issubset(honeycomb.letters)
71 if present(letters
, honeycomb
)
75 pangram_sets
= [s
for s
in word_sets
.keys() if len(s
) == 7 if 's' not in s
]
76 print("pangram sets:", len(pangram_sets
))
78 with
open('pangaram_words.txt', 'w') as f
:
79 for s
in pangram_sets
:
80 for w
in word_sets
[s
]:
86 # for ps in pangram_sets:
88 # ps_honeycombs.append(Honeycomb(mandatory=mand, letters=ps))
90 ps_honeycombs
= [Honeycomb(mandatory
=mand
, letters
=ps
)
91 for ps
in pangram_sets
93 print(len(ps_honeycombs
), "honeycombs")
96 partitioned_scored_sets
= {l
: {s
: scored_sets
[s
] for s
in scored_sets
if l
in s
}
97 for l
in string
.ascii_lowercase
}
100 def partitioned_score_honeycomb(honeycomb
):
101 return sum(sc
for letters
, sc
in partitioned_scored_sets
[honeycomb
.mandatory
].items()
102 if letters
.issubset(honeycomb
.letters
)
108 best_honyecomb
= max(ps_honeycombs
, key
=partitioned_score_honeycomb
)
109 print(best_honyecomb
, partitioned_score_honeycomb(best_honyecomb
))
113 # best_honyecomb = max(ps_honeycombs, key=score_honeycomb)
114 # print(best_honyecomb, partitioned_score_honeycomb(best_honyecomb))
117 # cProfile.run('max(ps_honeycombs, key=score_honeycomb)')
121 # cProfile.run('max(ps_honeycombs, key=partitioned_score_honeycomb)')