Best Python code snippet using SeleniumBase
wordle.py
Source:wordle.py
1from absl import flags2from absl import app3from collections import defaultdict, namedtuple4import copy5import multiprocessing as mp6YELLOW = 'y'7GRAY = 'b'8GREEN = 'g'9class Wordle:10 """Representation of wordle puzzle state and solution functionality."""11 # all possible solutions12 solutions = []13 # all possible guesses14 guesses = []15 def __init__(self, solutions: list[str] = None, guesses: list[str] = None, greens: list[str] = None, 16 greens_not: dict[int, list[str]] = None, yellows: set[str] = None, grays: set[str] = None, hard_mode: bool = False):17 # list of 5 positions with either the correct letter or empty str18 if greens is None:19 self.greens = ['', '', '', '', '']20 else:21 self.greens = greens22 # map from position indices to letters we know are not there23 if greens_not is None:24 self.greens_not = defaultdict(list)25 else:26 self.greens_not = greens_not27 # letters that are confirmed to be in word28 if yellows is None:29 self.yellows = set()30 else: 31 self.yellows = yellows32 # letters that are confirmed not to be in word33 if grays is None:34 self.grays = set()35 else:36 self.grays = grays37 if solutions is not None:38 self.solutions = solutions39 if guesses is not None:40 self.guesses = guesses41 42 self.hard_mode = hard_mode43 44 def add_green(self, pos: int, c: str) -> None:45 # store info that letter c is at index pos46 self.greens[pos] = c47 48 def add_yellow(self, pos: int, c: str) -> None:49 # store info that letter c is in word50 self.yellows.add(c)51 # store info that letter c is not in position pos52 self.greens_not[pos].append(c)53 def add_gray(self, c: str) -> None:54 # store information that letter c is not in word55 self.grays.add(c)56 def add_grays(self, grays: list[str]) -> None:57 for gray in grays:58 self.grays.add(gray)59 def init_solutions(self, solutions: list[str]) -> None:60 self.solutions = solutions61 62 def init_guesses(self, guesses: list[str]) -> None:63 self.guesses = guesses64 65 def get_filtered_solutions(self) -> list[str]:66 words = []67 for solution in self.solutions:68 if self.greens_check(solution) and self.yellows_check(solution) and self.grays_check(solution) and self.greens_not_check(solution):69 words.append(solution)70 return words71 72 def get_guesses(self) -> list[str]:73 if not self.hard_mode:74 return self.guesses75 guesses: list[str] = []76 for guess in self.guesses:77 if self.greens_check(guess) and self.yellows_check(guess) and self.grays_check(guess) and self.greens_not_check(guess):78 guesses.append(guess)79 return guesses80 81 def greens_check(self, word: str) -> bool:82 for i, c in enumerate(self.greens):83 if c != '' and c != word[i]:84 return False85 return True86 def yellows_check(self, word: str) -> bool:87 for c in self.yellows:88 if c not in word:89 return False90 return True91 def grays_check(self, word: str) -> bool:92 for c in word:93 if c in self.grays and c not in self.yellows:94 return False95 return True96 def greens_not_check(self, word: str) -> bool:97 for i, c in enumerate(word):98 if c in self.greens_not[i]:99 return False100 return True101 102 def get_optimal_guess_process(self, process_id: int, solutions: list[str], filtered_solutions: list[str], return_dict: dict) -> None:103 """104 Process to run as a part of multiprocess optimal word search.105 """106 # dict from each guess to how many solutions it would leave remaining on average if guessed107 guess_to_rem = defaultdict(int)108 for i, sol in enumerate(solutions):109 for guess in self.get_guesses():110 greens, greens_not, yellows, grays = self.greens.copy(), copy.deepcopy(self.greens_not), self.yellows.copy(), self.grays.copy()111 sol_dict = dict()112 for c in sol:113 sol_dict[c] = True114 for j, c in enumerate(guess):115 # test for greens116 if c == sol[j]:117 greens[j] = c118 else:119 if c in sol_dict:120 yellows.add(c)121 greens_not[j].append(c)122 else:123 grays.add(c)124 125 test_wordle = Wordle(solutions=filtered_solutions, guesses=self.guesses, greens=greens, greens_not=greens_not, yellows=yellows, grays=grays)126 # number of solutions that would remain if this guess were guessed and sol were the solution127 num_sol_rem = len(test_wordle.get_filtered_solutions())128 delta, weight = num_sol_rem - guess_to_rem[guess], i+1129 # apply running average to guess dict130 guess_to_rem[guess] += delta/weight131 return_dict[process_id] = guess_to_rem132 def get_optimal_guess_multiprocess(self, cores: int = 10) -> str:133 """134 Return the guess that eliminates the most solutions.135 Inputs:136 cores: the number of cores to use137 """138 filtered_solutions = self.get_filtered_solutions()139 if len(filtered_solutions) < 3:140 return filtered_solutions[0]141 142 group_size = len(filtered_solutions)//cores143 if group_size < 1:144 group_size = 1145 solution_sets = [filtered_solutions[i:i+group_size] for i in range(0, len(filtered_solutions), group_size)]146 set_weights = [len(sol_set)/len(filtered_solutions) for sol_set in solution_sets]147 processes: list[mp.Process] = []148 guess_to_rem = defaultdict(int)149 with mp.Manager() as manager:150 return_dict = manager.dict()151 for process_id, solution_set in enumerate(solution_sets):152 process = mp.Process(target=self.get_optimal_guess_process, args=(process_id, solution_set, filtered_solutions, return_dict))153 processes.append(process)154 process.start()155 156 for process in processes:157 process.join()158 for group_id, guess_to_rem_frag in return_dict.items():159 for guess, rem in guess_to_rem_frag.items():160 guess_to_rem[guess] += rem * set_weights[group_id]161 162 # merge dictionary from each 163 # retrieve guess with minimum rem value164 min_rem = len(self.solutions)165 min_guess = self.guesses[0]166 for guess, rem in guess_to_rem.items():167 if rem < min_rem:168 min_guess, min_rem = guess, rem169 return min_guess170 def get_optimal_guess(self) -> str:171 """172 Return the guess that eliminates the most solutions.173 """174 filtered_solutions = self.get_filtered_solutions()175 if len(filtered_solutions) < 3:176 return filtered_solutions[0]177 # dict from each guess to how many solutions it would leave remaining on average if guessed178 guess_to_rem = defaultdict(int)179 180 for i, sol in enumerate(filtered_solutions):181 for guess in self.get_guesses:182 greens, greens_not, yellows, grays = self.greens.copy(), copy.deepcopy(self.greens_not), self.yellows.copy(), self.grays.copy()183 sol_dict = dict()184 for c in sol:185 sol_dict[c] = True186 for j, c in enumerate(guess):187 # test for greens188 if c == sol[j]:189 greens[j] = c190 else:191 if c in sol_dict:192 yellows.add(c)193 greens_not[j].append(c)194 else:195 grays.add(c)196 197 test_wordle = Wordle(solutions=filtered_solutions, guesses=self.guesses, greens=greens, greens_not=greens_not, yellows=yellows, grays=grays)198 # number of solutions that would remain if this guess were guessed and sol were the solution199 num_sol_rem = len(test_wordle.get_filtered_solutions())200 delta, weight = num_sol_rem - guess_to_rem[guess], i+1201 # apply running average to guess dict202 guess_to_rem[guess] += delta/weight203 # retrieve guess with minimum rem value204 min_rem = len(self.solutions)205 min_guess = self.guesses[0]206 for guess, rem in guess_to_rem.items():207 if rem < min_rem:208 min_guess, min_rem = guess, rem209 return min_guess210def get_solutions(filename: str) -> list[str]:211 solutions = []212 with open(filename, 'r') as f:213 for line in f:214 word = line.replace('\n', '').strip().lower()215 solutions.append(word)216 return solutions217def get_guesses(filename: str) -> list[str]:218 guesses = []219 with open(filename, 'r') as f:220 for line in f:221 word = line.replace('\n', '').strip().lower()222 guesses.append(word)223 return guesses224def check_guess_error(guesses: list[str], guess: str) -> tuple[bool, str]:225 '''Returns True if there is error in guess.'''226 if len(guess) != 5:227 return True, "Guess needs to be of length 5."228 if guess not in guesses:229 return True, "This guess is not a valid word"230 return False, ''231def check_result_error(result: str) -> tuple[bool, str]:232 '''Returns True if there is error in result format.'''233 if len(result) != 5:234 return True, "Result needs to be of length 5."235 for c in result:236 if c not in ['y', 'b', 'g']:237 return True, "Only y, b, and g are valid inputs."238 return False, ''239def update_wordle(wordle: Wordle, word: str, result: str) -> None:240 # letter to color dict241 for i, letter in enumerate(word):242 color = result[i]243 if color == GREEN:244 wordle.add_green(i, letter)245 elif color == YELLOW:246 wordle.add_yellow(i, letter)247 else:248 wordle.add_gray(letter)249FLAGS = flags.FLAGS250flags.DEFINE_boolean('hardmode', False, 'Whether to run using hard mode.')251def main(_):252 solutions, guesses = get_solutions('wordlist_solutions.txt'), get_guesses('wordlist_guesses.txt')253 wordle = Wordle(solutions=solutions, guesses=guesses, hard_mode=FLAGS.hardmode)254 err = True255 while err:256 # Optimal first guesses: roate, raise257 first_guess = input('Input your first guess: ')258 err, explanation = check_guess_error(guesses, first_guess)259 if err:260 print(explanation)261 262 err = True263 while err:264 result = input('Input the result pattern (e.g. ybgbb): ')265 err, explanation = check_result_error(result)266 if err:267 print(explanation)268 update_wordle(wordle, first_guess, result)269 270 while len(wordle.get_filtered_solutions()) > 1:271 # guess = wordle.get_optimal_guess()272 guess = wordle.get_optimal_guess_multiprocess()273 print(f"Your next guess should be {guess}")274 err = True275 while err:276 result = input('Input the result pattern (e.g. ybgbb): ')277 err, explanation = check_result_error(result)278 if err:279 print(explanation)280 update_wordle(wordle, guess, result)281 print(f"The answer is {wordle.get_filtered_solutions()[0]}")282 283if __name__ == "__main__":...
test.py
Source:test.py
1from wordle import print_guess_after_user_prompt, check_if_in, determine_next_guess, find_guess_results, parse_final_list, won_wordle2def test_wordle(answer, first_guess="crane"):3 i = 04 guess_history = []5 letter_strings = []6 next_guess = first_guess7 while (i < 6):8 current_guess_list, guess = find_guess_results(answer, next_guess)9 guess_history.append(guess)10 print_guess_after_user_prompt(current_guess_list)11 # check if you won12 if (won_wordle(current_guess_list) is True):13 print("you won the wordle in", i, "guesses! great job")14 return15 next_guesses_list = check_if_in(current_guess_list, guess)16 next_guess_list, length = determine_next_guess(17 next_guesses_list, guess_history)18 parse_final_list(current_guess_list,19 next_guesses_list, letter_strings)20 try:21 next_guess = next_guess_list[0]22 except IndexError:23 print("there are no more words to check")24 print("words remaining:", length)25 i = i + 126def main():27 test_wordle("dodge")...
test_wordle.py
Source:test_wordle.py
1#!/usr/bin/env python32# Run from project root directory with3# python3 -m tests.test_wordle4# Note - test_wordle, not test_worlde.py (no file extension)5import unittest6import mock7from wordle import Wordle8# Test with practice word 'CHAIR'9class TestWordle_01(unittest.TestCase):10 def setUp(self):11 w = Wordle()12 w.correct = ['', 'H', '', 'I', '']13 w.close = ['A', 'R']14 w.eliminated = ['B', 'C', 'D', 'S', 'T']15 def tearDown(self):16 pass17 # Check possible solutions18 def test_check_words(self):19 self.assertFalse(w.check_word(self, 'flair'))20if __name__ == '__main__':...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!