Best Python code snippet using hypothesis
Main.py
Source:Main.py  
1from GraphGame import *2from Value import *3def one_aleatory_test(nb_vertex,min_weight = 1, max_weight = 100):4    """5    Genere aleatoirement un jeu a deux joueurs pour lequel chaque joueur a un objectif (ces deux objectis etant differents)6    :param nb_vertex: nombre de sommets du graphe du jeu7    :param min_weight: poids minimal sur les aretes du graphe8    :param max_weight: poids maximal sur les aretes du graphe9    :return: un jeu10    """11    possible_goal = range(0, nb_vertex)12    random.shuffle(possible_goal)13    goal_1 = possible_goal.pop()14    goal_2 = possible_goal.pop()15    possible_init = range(0, nb_vertex)16    random.shuffle(possible_init)17    init = possible_init.pop()18    game = ReachabilityGame.generate_game(2, nb_vertex, init, [{goal_1}, {goal_2}], min_weight, max_weight)19    return game20def compute_a_star(game, allowed_time = float("infinity")):21    res = game.best_first_search(ReachabilityGame.a_star_positive, None, allowed_time)22    return res23def compute_random_method(game, nbr_path=100):24    set_res = game.test_random_path(nbr_path, game.compute_max_length())25    best_res = game.filter_best_result(set_res)26    return best_res27def compute_init_best_first_search(game, allowed_time = float("infinity")):28    init = game.best_first_search_with_init_path_both_two(ReachabilityGame.a_star_positive, allowed_time)29    return init30def compute_breadth_first_search_first(game):31    first = game.breadth_first_search()32    return first33def compute_breadth_first_search(game, allowed_time = float("infinity")):34    breadth = game.breadth_first_search(False, allowed_time)35    breadth_result = game.filter_best_result(breadth)36    return breadth_result37BEST = 038SAME = 139EQUIVALENT = 240BOTH_FAIL = 341WORST = 442def compare_one_method_to_other_method(game, path1, path2):43    """44    Compare si pour un certain jeu donne un resultat: path1 et un autre resultat. Determine sur path1 est meilleur, pire,45    egal, equivalent a path2.46    :param game: un jeu d atteignabilite47    :param path1: un resultat48    :param path2: un autre resultat49    :return: la comparaison entre les deux resultats50    """51    if path1 is None and path2 is None:52        return BOTH_FAIL53    else:54        if path1 is None:55            return WORST56        else:57            if path2 is None:58                return BEST59            else:60                (_cost1,reached_player1) = game.get_info_path(path1)61                (_cost2,reached_player2) = game.get_info_path(path2)62                cost1 = game.cost_for_all_players(path1, True)63                cost2 = game.cost_for_all_players(path2, True)64                if len(reached_player1) > len(reached_player2) :65                    return BEST66                else:67                    if len(reached_player1) < len(reached_player2):68                        return WORST69                    else:70                        sum_1 = 071                        for p in cost1.keys():72                            sum_1 += cost1[p]73                        sum_2 = 074                        for j in cost2.keys():75                            sum_2 += cost2[j]76                        if sum_1 < sum_2:77                            return BEST78                        else:79                            if sum_1 > sum_2:80                                return WORST81                            else:82                                if ReachabilityGame.same_paths(path1,path2):83                                    return SAME84                                else:85                                    return EQUIVALENT86def compute_stat(file_name, allowed_time = float("infinity")):87    """88    Test l' algorithme best-first search auquel on associe la fonction d evaluation de type A* sur des graphes a n noeuds89    ou 5 <= n  <= 20, 100 tests pour chaque n differents90    :param file_name: nom du fichier dans lequel stocker les resultats91    :param allowed_time: temps permis pour l execution d une methode92    """93    stat = open(file_name, "a")94    for nb_v in range(5, 21):95        stat.write("******************* \n")96        stat.write(" test avec "+str(nb_v)+" sommets \n")97        stat.write(" temps permis pour chaque recherche "+str(allowed_time)+"\n")98        compt_find = 099        compt_not_find = 0100        debut = time.time()101        for i in range(0, 100):102            game = one_aleatory_test(nb_v)103            res = compute_a_star(game, allowed_time)104            if res is not None:105                compt_find += 1106            else:107                compt_not_find +=1108        fin = time.time()109        print "fini pour ", nb_v, " sommets en ", fin - debut, " secondes"110        stat.write(" nb EN trouves "+str(compt_find)+"\n")111        stat.write(" nbr EN manques "+str(compt_not_find)+"\n")112        stat.write("temps ecoule "+str(fin - debut)+"\n")113    stat.close()114def compute_stat_all_method(file_name, allowed_time = float("infinity")):115    """116    Execute les differents resultats sur 100 jeux donc le graphe est compose de 5 noeuds et genere aleatoirement et117    ecrit les resultats dans un fichier.118    :param file_name: nom du fichier dans lequel inscrire les resultats119    :param allowed_time: temps permis pour l execution d une methode120    """121    stat = open(file_name, "a")122    for nb_v in range(5, 6):123        stat.write("******************* \n")124        stat.write(" test avec " + str(nb_v) + " sommets \n")125        stat.write(" temps permis pour chaque recherche " + str(allowed_time) + "\n")126        compt_find_a_star = 0127        compt_find_random = 0128        compt_find_init = 0129        compt_find_breadth_first = 0130        compt_find_breadth = 0131        real_debut = time.time()132        fin_a_star = 0133        fin_random = 0134        fin_init = 0135        fin_breadth_first = 0136        fin_breadth = 0137        best_vs_random = 0138        best_vs_init = 0139        best_vs_breadth_first = 0140        best_vs_breadth = 0141        worst_vs_random = 0142        worst_vs_init = 0143        worst_vs_breadth_fisrt = 0144        worst_vs_breadth = 0145        both_fail_vs_random = 0146        both_fail_vs_init = 0147        both_fail_vs_breadth_first = 0148        both_fail_vs_breadth = 0149        equivalent_vs_random = 0150        equivalent_vs_init = 0151        equivalent_vs_breadth_first = 0152        equivalent_vs_breadth = 0153        same_vs_random = 0154        same_vs_init = 0155        same_vs_breadth_first = 0156        same_vs_breadth = 0157        for i in range(0, 20):158            print "------"159            print "Jeu numero: ", i + 1160            game = one_aleatory_test(nb_v)161            debut = time.time()162            a_star = compute_a_star(game, allowed_time)163            fin = time.time()164            fin_a_star = fin_a_star + (fin - debut)165            print " a_star"166            debut = fin167            random = compute_random_method(game, 100)168            fin = time.time()169            fin_random = fin_random + (fin - debut)170            print "random"171            debut = fin172            init = compute_init_best_first_search(game, allowed_time)173            fin = time.time()174            fin_init  = fin_init + (fin - debut)175            print "init"176            debut = fin177            breadth_first = compute_breadth_first_search_first(game)178            fin = time.time()179            fin_breadth_first = fin_breadth_first + (fin - debut)180            print "breadth"181            #debut = fin182            #breadth = compute_breadth_first_search(game, allowed_time)183            #fin = time.time()184            #fin_breadth = fin_breadth + (debut - fin)185            if a_star is not None:186                compt_find_a_star += 1187            if random is not None:188                compt_find_random += 1189            if init is not None:190                compt_find_init += 1191            if breadth_first is not None:192                compt_find_breadth_first += 1193            #if breadth is not None:194            #    compt_find_breadth += 1195            #on compare les resultats obtenus avec celui de A*196            vs_random = compare_one_method_to_other_method(game, a_star, random)197            if vs_random == BEST:198                best_vs_random += 1199            if vs_random == WORST:200                worst_vs_random += 1201            if vs_random == BOTH_FAIL:202                both_fail_vs_random += 1203            if vs_random == SAME:204                same_vs_random += 1205            if vs_random == EQUIVALENT:206                equivalent_vs_random += 1207            vs_init = compare_one_method_to_other_method(game, a_star, init)208            if vs_init == BEST:209                best_vs_init += 1210            if vs_init == WORST:211                worst_vs_init += 1212            if vs_init == BOTH_FAIL:213                both_fail_vs_init += 1214            if vs_init == SAME:215                same_vs_init += 1216            if vs_init == EQUIVALENT:217                equivalent_vs_init += 1218            vs_breadth_first = compare_one_method_to_other_method(game, a_star, breadth_first)219            if vs_breadth_first == BEST:220                best_vs_breadth_first += 1221            if vs_breadth_first == WORST:222                worst_vs_breadth_fisrt += 1223            if vs_breadth_first == BOTH_FAIL:224                both_fail_vs_breadth_first += 1225            if vs_breadth_first == SAME:226                same_vs_breadth_first += 1227            if vs_breadth_first == EQUIVALENT:228                equivalent_vs_breadth_first += 1229            #vs_breadth = compare_one_method_to_other_method(game, a_star, breadth)230            #if vs_breadth == BEST:231            #    best_vs_breadth += 1232            #if vs_breadth == WORST:233            #    worst_vs_breadth +=1234            #if vs_breadth == BOTH_FAIL:235            #    both_fail_vs_breadth += 1236            #if vs_breadth_first == SAME:237            #    same_vs_breadth += 1238            #if vs_breadth == EQUIVALENT:239            #    equivalent_vs_breadth += 1240        real_fin  = time.time()241        print "fini en ", real_fin - real_debut, " secondes"242        stat.write("A_STAR : \n")243        stat.write("Nb EN trouves " + str(compt_find_a_star) + "\n")244        stat.write("temps ecoule " + str(fin_a_star) + "\n")245        stat.write("----------------------- \n")246        stat.write("RANDOM : \n")247        stat.write("Nb EN trouves " + str(compt_find_random) + "\n")248        stat.write("temps ecoule " + str(fin_random) + "\n")249        stat.write("----------------------- \n")250        stat.write("INIT BEST : \n")251        stat.write("Nb EN trouves " + str(compt_find_init) + "\n")252        stat.write("temps ecoule " + str(fin_init) + "\n")253        stat.write("----------------------- \n")254        stat.write("BREADTH FIRST : \n")255        stat.write("Nb EN trouves " + str(compt_find_breadth_first) + "\n")256        stat.write("temps ecoule " + str(fin_breadth_first) + "\n")257        stat.write("----------------------- \n")258        #stat.write("BREADTH MULTI : \n")259        #stat.write("Nb EN trouves " + str(compt_find_breadth) + "\n")260        #stat.write("temps ecoule " + str(fin_breadth) + "\n")261        #stat.write("----------------------- \n")262        stat.write("STAT SUR A_STAR : \n")263        stat.write("A_star vs random: meilleur " + str(best_vs_random)+" pire "+ str(worst_vs_random) +" pareil :" + str(same_vs_random) + " equivalent :"+ str(equivalent_vs_random) + " manque tous les deux :"+ str(both_fail_vs_random)+ "\n")264        stat.write("A_star vs init : meilleur " + str(best_vs_init)+" pire "+ str(worst_vs_init) +" pareil " + str(same_vs_init) + " equivalent "+ str(equivalent_vs_init) + " manque tous les deux "+ str(both_fail_vs_init)+ "\n")265        stat.write("A_star vs breadth first: meilleur " + str(best_vs_breadth_first)+ " pire " + str(worst_vs_breadth_fisrt) +" pareil " + str(same_vs_breadth_first) + " equivalent "+ str(equivalent_vs_breadth_first) + " manque tous les deux "+ str(both_fail_vs_breadth_first)+ "\n")266        #stat.write("A_star vs breadth multi: meilleur " + str(best_vs_breadth) +" pareil " + str(same_vs_breadth) + " equivalent "+ str(equivalent_vs_breadth) + "manque tous les deux"+ str(both_fail_vs_breadth)+ "\n")267        stat.write("----------------------- \n")268        stat.close()269def real_EN_test(nb_v, allowed_time = float("infinity")):270    stat = open("real_EN.txt", "a")271    stat.write("*****************\n")272    stat.write("Nouveau test \n")273    compt_find = 0274    compt_not_find = 0275    real_EN = 0276    debut = time.time()277    for i in range(0, 100):278        game = one_aleatory_test(nb_v)279        res = compute_a_star(game, allowed_time)280        (nash,coal) = game.is_a_Nash_equilibrium(res)281        if res is not None:282            compt_find += 1283            if nash:284                real_EN += 1285        else:286            compt_not_find += 1287    fin = time.time()288    print "fini pour ", nb_v, " sommets en ", fin - debut, " secondes"289    stat.write(" nb EN trouves " + str(compt_find) + "\n")290    stat.write(" nbr EN manques " + str(compt_not_find) + "\n")291    stat.write(" EN reel " + str(real_EN) + "\n")292    stat.write("temps ecoule " + str(fin - debut) + "\n")293    stat.close()294def restart_test(times):295    for i in range(0, times):296        real_EN_test(5)297if __name__ == '__main__':298    #compute_stat(30)299    #restart_test(10)...breadth.py
Source:breadth.py  
1import MySQLdb 2import os, sys, json 3import bot_detect as bot 4import numpy as np5import itertools6from dateutil import parser7import draw_tools.cdf_plot as cdf_plot8from draw_tools.line_plot import LinePlot9from draw_tools.cdf_plot import CDFPlot10def get_breadth_time_series(keys, users):11    dir_name = "RetweetNew/"12    files = os.listdir(dir_name)13    unique_d = {}14    count = 015    breadth_size = {}16    breadth_time = {}17    breadth_user = {}18    files = keys.split('_')19    user_index = {}20    for postid in files:21        #if not get_veracity(postid,  veracity):22        #    continue23        unique_d[postid] = {}24        breadth_time[postid] = []25        user_index[postid] = []26        with open(dir_name + postid, 'r') as f:27            tweets = json.load(f)28 29        sort = {}30        for key in tweets.keys():31            tweet = tweets[key]32            sort[key] = parser.parse(tweet['time'])33        #sort by time34        new_list = sorted(sort.items(), key=lambda x: x[1])35        start_time = new_list[0][1]36        sorted_ids = [item[0] for item in new_list]37        breadth_size[postid] = {}38        unique_users = {}39        max_breadth = 040        for i, tid in enumerate(sorted_ids):41            tweet = tweets[tid]42            unique_users[tweet['user']] = 143            #order by breadth can decrease time 44            #time to get to the breadth in a rumor. not care about which breadth is in 45            b_size = breadth_size[postid].get(tweet['depth'], 0) + 146            breadth_size[postid][tweet['depth']] = b_size47            print(tweet['user'], tweet['depth'])48            if max_breadth < b_size:49                max_breadth = b_size50            #    breadth_time[max_breadth] = breadth_time.get(max_breadth, {})51            #    elapsed_time = (new_list[i][1] - start_time).total_seconds() / 60 #min52            #    breadth_time[max_breadth][postid] = elapsed_time53            #    breadth_user[max_breadth] = breadth_user.get(max_breadth, {})54            #    breadth_user[max_breadth][postid] = len(unique_users)55            if tweet['user'] in users:56                user_index[postid].append(i)57            breadth_time[postid].append(max_breadth)58            #time to get to the breadth in a breadth.59        count += 160        #if count > 10 :61        #    break62    return breadth_time, user_index63#observe the change of breadth size with emergence of echo chamber users 64def breadth_change():65    66    with open('Data/echo_chamber2.json', 'r') as f:67        echo_chambers = json.load(f)68    count = 069    for keys in echo_chambers.keys():70        users = echo_chambers[keys]71        breadth_series, user_index = get_breadth_time_series(keys, users)    72        for key in breadth_series.keys():73            breadth = breadth_series[key]74            user = user_index[key]75            line = LinePlot()76            #line.set_ylog()77            line.set_label('Users', 'Breadth')78            line.set_plot_data(breadth, np.arange(1, len(breadth) + 1, 1))79            line.set_axvline(user)80            #line.set_legends(['True', 'False', 'Mixed'])81            #line.set_xticks(x_ticks)82            line.save_image('Image/Breadth/breadth_change_line_%s_%s.png'%(keys, key))83        count += 1 84        if count > 0:85            break86if __name__ == "__main__":87    #breadth_cdf()88    #breadth_num()...packing.py
Source:packing.py  
1##################################2### Title: Packing        ########3### Author: GuoChen Hou   ########4##################################5# Given a rectangle tray and an unlimited supply of slabs. Calculate the maximum number of slabs that can fit into the rectangular 6# tray, in a single orientation only.7def compute_max_slabs(tray_length, tray_breadth, slab_length, slab_breadth):8	length_slabs = int(tray_length / slab_length)9	breadth_slabs = int(tray_breadth / slab_breadth)10	11	remain_length = tray_length - (length_slabs * slab_length)12	remain_breadth_slab = 013	remain_breadth = tray_breadth - (breadth_slabs * slab_breadth)14	remain_length_slab = 015	if remain_length >= slab_breadth:16		if tray_breadth >= slab_length:17			remain_breadth_slab = int(remain_length / slab_breadth)18	if remain_breadth >= slab_length:19		if tray_length >= slab_length:20			remain_length_slab = int(remain_breadth / slab_length)21	return length_slabs * breadth_slabs +remain_breadth_slab + remain_length_slab22t_length, t_breadth = raw_input('Enter dimensions of tray: ').split()23s_length, s_breadth = raw_input('Enter dimensions of tray: ').split()24if t_breadth > t_length:25	temp = t_length26	t_length = t_breadth27	t_breadth = temp28if s_breadth > s_length:29	temp = s_length30	s_length = s_breadth31	s_breadth = temp32tray_length = int(t_length)33tray_breadth = int(t_breadth)34slab_length = int(s_length)35slab_breadth = int(s_breadth)36length_base_slab_number = compute_max_slabs(tray_length, tray_breadth, slab_length, slab_breadth)37breadth_base_slab_number = compute_max_slabs(tray_length, tray_breadth, slab_breadth, slab_length)38print length_base_slab_number39print breadth_base_slab_number40if length_base_slab_number > breadth_base_slab_number:41	print 'Maximum number of slabs =', length_base_slab_number42else:...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!!
