# Wordle strategy

May 24th, 2022
1,198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import math
2.
3. def guess(attempt, secret):
4.     n = len(secret)
5.     assert n == len(attempt), (attempt, secret, n)
6.     result = ['-'] * n
7.     unused = list(secret)
8.     for i in range(n):
9.         if attempt[i] == secret[i]:
10.             result[i] = '+'
11.             unused[i] = None
12.     for i in range(n):
13.         if result[i] == '-' and attempt[i] in unused:
14.             result[i] = '?'
15.             unused[unused.index(attempt[i])] = None
16.     return ''.join(result)
17.
18. def best_move(possible_words):
19.     if len(possible_words) == 2315:
20.         return "raise"
21.     if len(possible_words) == 3483:
22.         return "норка"
23.     if len(possible_words) == 8363:
24.         return "12953"
25.     best_score = 1e100
26.     best_move = None
27.     for move in words:
28.         score = 0.0 # чем меньше, тем лучше
29.         if move in possible_words:
30.             score -= 1.0
31.         groups = {}
32.         for secret in possible_words:
33.             result = guess(move, secret)
34.             groups[result] = groups.get(result, 0) + 1
35.         for group_size in groups.values():
36.             score += group_size * math.log2(group_size)
37.         if score < best_score:
38.             best_score = score
39.             best_move = move
40.     return best_move
41.
42. def is_prime(p):
43.     for x in range(2, round(p ** 0.5) + 1):
44.         if p % x == 0:
45.             return False
46.     return p > 1
47.
48. def primes(n=5):
49.     return [str(p) for p in range(10**(n - 1), 10**n) if is_prime(p)]
50.
51.
52. # https://www.nytimes.com/games/wordle/
53. # https://wordle-igra.ru/
54. # https://wordle.belousov.one/
55. # https://converged.yt/primel/
56. words = open("ru_nounlist.txt", encoding="utf-8").read().split()
57. words = [word for word in words if len(word) == 5]
58. # words = primes()
59. possible_words = words
60. while len(possible_words) > 1:
61.     move = best_move(possible_words)
62.     print(move)
63.     result = input()
64.     possible_words = [word for word in possible_words if result == guess(move, word)]
65.     print("Info:", len(possible_words), possible_words)
66.