Best Python code snippet using slash
hangman.py
Source:hangman.py  
...75    get_num_guess()76        Return the number of guesses the user has made77    get_guesses()78        Return the list attribute locations holding the letters the user has guessed79    get_num_errors()80        Return the attribute num_errors 81    add_num_guess()82        Increase attribute num_guess by 183    add_num_errors()84        Increase attribute num_errors by 185    add_guess_letter()86        Append letter to attribute list guesses87    show_word()88        Prints the word object to stdout as a string89    get_word_indices(guess)90        Gets the indices where guess exists in word91    update_display(indices, letter)92        Updates display attribute by replacing '_' with letter at given indices93    check_guess(guess)94        Checks whether the guess made exists in word or is an error95    """96    def __init__(self) -> None:97        """98        Constructs all the necessary attributes for the Word object.99        Parameters100        ----------101        word : str102            The word being guessed103        display : [str]104            Formatted display with '_' as placeholder for letter in word105        guesses : [str]106            The letters the user has already guessed107        num_guess : int108            The number of guesses the user has made109        num_errors : int110            The number of errors the user has made111        """112        self.word = self.__get_random_word()113        self.display = ['_ ' for letter in self.word]114        self.guesses = []115        self.num_guess = 0116        self.num_errors = 0117    def __get_random_word(self) -> str:118        word = wordApi.getRandomWord(maxLength=8)119        return word.word120    def get_word(self) -> str:121        return self.word122    123    def get_display(self) -> list[str]:124        return self.display125    def get_num_guess(self) -> int:126        return self.num_guess127    128    def get_guesses(self) -> list[str]:129        return self.guesses130    def get_num_errors(self) -> int:131        return self.num_errors132    133    def add_num_guess(self) -> None:134        self.num_guess += 1135    136    def add_num_errors(self) -> None:137        self.num_errors += 1138    139    def add_guess_letter(self, letter: str) -> None:140        self.guesses.append(letter)141    def show_word(self) -> None:142        display = ' '.join(self.display)143        print(f'\nThe word is {display}')144    145    def get_word_indices(self, guess: str) -> list[int]:146        locations = []147        for i, letter in enumerate(list(self.word)):148            if letter == guess:149                locations.append(i)150        return locations151    152    def update_display(self, indices: list[int], letter: str) -> None:153        for i in indices:154            self.display[i] = letter155    def check_guess(self, guess: str) -> int:156        if guess not in self.guesses and guess in self.get_word():157            self.add_guess_letter(guess)158            self.add_num_guess()159            indices = self.get_word_indices(guess)160            self.update_display(indices, guess)161            print('\nYou got it! The letter '+guess+' is in the word!\n')162            return 0163        else:164            if guess in self.guesses:165                self.add_num_guess()166                self.add_num_errors()167                print('\nUh oh, you have already guessed the letter '+guess+'!\nA part to the stick figure will be added.\n')168            else:169                self.add_guess_letter(guess)170                self.add_num_guess()171                self.add_num_errors()172                print('\nUh oh, the letter '+guess+' is not in the word!\nA part to the stick figure will be added.')173            return -1174class Game:175    """176    A class used to represent a Hangman Game177    ...178    Attributes179    ----------180    word : Word object181        A formatted string to print out the hangman figure182    picture : Picture object183        Something here184    Methods185    -------186    print_title()187        Prints out the ASCII title to stdout188    check_for_win()189        Checks for win condition of the game190    reset()191        Gets a new Word object and Picture object and resets game192    play_again()193        Gets user input whether to play the game again to reset or not to exit game194    run()195        Runs the game awaiting user input for guess, until win condition or user exit196    """197    def __init__(self) -> None:198        """199        Constructs all the necessary attributes for the Game object.200        Parameters201        ----------202        word : Word object203            Word object204        picture : Picture object205            Picture object206        """207        self.word = Word()208        self.picture = Picture()209    def print_title(self) -> None:210        print(' _    _      _                            _         ')    211        print('| |  | |    | |                          | |        ')     212        print('| |  | | ___| | ___ ___  _ __ ___   ___  | |_ ___   ')213        print('| |/\| |/ _ \ |/ __/ _ \| \'_ ` _ \ / _ \ | __/ _ \ ')214        print('\  /\  /  __/ | (_| (_) | | | | | |  __/ | || (_) | ')215        print(' \/  \/ \___|_|\___\___/|_| |_| |_|\___|  \__\___/  ')216                                                                                                    217        print(' _   _')                                       218        print('| | | |   ')                                        219        print('| |_| | __ _ _ __   __ _ _ __ ___   __ _ _ __     ')220        print('|  _  |/ _` | \'_ \ / _` | \'_ ` _ \ / _` | \'_ \   ') 221        print('| | | | (_| | | | | (_| | | | | | | (_| | | | |   ')222        print('\_| |_/\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|   ')223        print('                    __/ |')                       224        print('                   |___/') 225    def check_for_win(self) -> bool:226        display = ''.join(self.word.get_display())227        if display == self.word.get_word():228            return True229    def check_for_lose(self) -> bool:230        if self.word.get_num_errors() == MAX_ERRORS:231            self.picture.update_image(self.word.get_num_errors())232            self.picture.draw_image()233            return True234    235    def reset(self) -> None:236        self.word = Word()237        self.picture = Picture()238    239    def play_again(self) -> None:240        answer = input('Want to play again? Type \'y\' to play another round, or \'n\' to exit the game.\n>>> ')241        if answer.lower() == 'y':242            self.reset()243        else:244            exit()245    def run(self) -> None:246        running = True247        self.print_title()248        while running:249            self.picture.draw_image() 250            self.word.show_word()251            guess = input('Guess a letter or type exit to leave the game\n>>> ')252            if guess == 'exit':253                print('Thanks for playing! The word was '+self.word.get_word()+'. See you soon!')254                exit()255                256            if self.word.check_guess(guess.lower()) == -1:257                self.picture.update_image(self.word.get_num_errors())258            if self.check_for_win():259                print(f'You have guessed the word {self.word.word} in {self.word.get_num_guess()} guesses!')260                self.play_again()261            elif self.check_for_lose():262                print('You have lost the game! The word was '+self.word.get_word()+'.')263                self.play_again()264if __name__ == '__main__':265    game = Game()...PocketAlgo.py
Source:PocketAlgo.py  
...4import numpy as np5from numpy import loadtxt6import matplotlib.pyplot as plt7# below code for checking random point or accuracy8def get_num_errors():9    error_counter=010    for idx in range(0,2000):11        final_test= W0*1 + W1*input[idx][0]  +W2*input[idx][1] + W3*input[idx][2]12        if  final_test <= 0 and input[idx,3] == 1:  #error case one keep count13            error_counter=error_counter + 114        if  final_test >= 0 and input[idx,3] == -1: 15            error_counter=error_counter + 116    return error_counter17 #3D problem so 3 wt variables + threshold(W0)18W1=519W2=520W3=5 21W0=4  # -threshold woith X0=122step_size=0.01#0.00823np_data_points=024with open('classification.txt', 'r') as in_file:25    np_data_points = loadtxt('classification.txt', delimiter=',')26input =   np.delete(np_data_points, 3, axis=1) # using last column as labels  and delete older labels27iter=028error_size=700029num_misclassify=[0]*error_size30while (True):       31        W0_old=W032        W1_old=W133        W2_old=W234        W3_old=W335        for point in input:36            value= W0*1 + W1*point[0]  +W2*point[1] + W3*point[2]37            if  value < 0 and point[3] == 1:  # CAse 1 w= w+ alpha*X 38                W0=W0 + step_size* 139                W1=W1 + step_size*point[0]40                W2=W2 + step_size*point[1]41                W3=W3 + step_size*point[2]42                num_misclassify[iter]= get_num_errors() # call function to calculate and store number of misclassified pts43                iter=iter+144            elif value >=0 and point[3]==-1: # Case245                W0=W0 - step_size* 146                W1=W1 - step_size*point[0]47                W2=W2 - step_size*point[1]48                W3=W3 - step_size*point[2]49                num_misclassify[iter]= get_num_errors() # call function to calculate and store number of misclassified pts50                iter=iter+151            if iter>=error_size :  # run only 7000 iterations52                break53        if iter>=error_size :  # run only 7000 iterations54             break     # break from both loops55print("Weight vector  W = [" + str(W0) +", " + str(W1) +", " + str(W2) +", "+ str(W3)  +"]")56downSample=10057y=[0]* int (error_size / downSample)58y_idx=059for i in range(0,len(num_misclassify)): # down sampling the errors array fro better display60    if i % downSample ==0: #down sample by 10061        y[y_idx]=num_misclassify[i]62        y_idx= y_idx+163fig = plt.figure()64ax = plt.axes()65x = np.linspace(0, 7000, len(y) )66ax.plot(x, y)67plt.show()68numWrong= num_misclassify[-2]   #get_num_errors()69Accuracy= 100 - (  (numWrong/2000) * 100   )70print("Accuracy =  " + str(Accuracy) + "%")71      ...grammar_error.py
Source:grammar_error.py  
...45        if self._language == LANGUAGE.CHINESE:46            self.lang_tool = language_tool_python.LanguageTool("zh-CN")47        elif self._language == LANGUAGE.ENGLISH:48            self.lang_tool = language_tool_python.LanguageTool("en-US")49    def get_num_errors(50        self, attacked_text: AttackedText, use_cache: bool = False51    ) -> int:52        """ """53        text = attacked_text.text54        if use_cache:55            if text not in self.grammar_error_cache:56                self.grammar_error_cache[text] = len(self.lang_tool.check(text))57            return self.grammar_error_cache[text]58        else:59            return len(self.lang_tool.check(text))60    def _check_constraint(61        self, transformed_text: AttackedText, reference_text: AttackedText62    ) -> bool:63        """ """64        original_num_errors = self.get_num_errors(reference_text, use_cache=True)65        errors_added = self.get_num_errors(transformed_text) - original_num_errors...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!!
