Best Python code snippet using autotest_python
world_truth_count.py
Source:world_truth_count.py
1import sys2import os3import minimal_proplogic as apl4import random5import numpy as np6import sys7import os8import time9import unittest10def generate_random_world(i):11 if type(i) == int:12 return [random.choice(["0","1"]) for j in range(i)]13 if type(i) == list:14 return {j:random.choice([True, False])for j in i}15def w2a(world):16 #world to array of bools17 return [True if x == "1" else False for x in world]18def a2w(world):19 #array of bools to str20 return "".join(["1" if x == True else "0" for x in world])21def arr_to_world(world):22 #Takes array of characters (optionally negated with "~")23 #returns bit vector of 0/1s in corresponding order24 ret_str = ""25 for symbol in world:26 if "~" in symbol:27 ret_str += "0"28 else:29 ret_str += "1"30 return ret_str31def get_relevant_variables(premise, idx=True):32 #return alphabetical pos of each var that is in the premise.33 cmap = "abcdefghijklmnopqrstuvwxyz"34 arr = []35 for i in range(len(cmap)):36 if cmap[i] in premise:37 if idx == True:38 arr.append(i)39 else: #return char itself40 arr.append(cmap[i])41 return arr#[i if (cmap[i] in premise) for i in range(len(cmap))]42def world_in_seen(world, relevant_variables, seen):43 #world: bool array size 26 corresponding to world bits44 #relevant_variables: int array, each int is var included in premise45 #seen: array of int arrays. each int array length of relevant_variables.46 #compares bit arrays, hopefully this is the fastest possible47 #print(world, relevant_variables, seen, True if [world[i] for i in relevant_variables] in seen else False)48 return True if [world[i] for i in relevant_variables] in seen else False49def assign_world(world, vars):50 ret_world = ["0"] * 2651 for i in range(0, len(world)):52 ret_world[vars[i]] = world[i]53 return "".join(ret_world)54def combine_vars(v1, v2):55 v = v156 for var in v2:57 if var not in v:58 v.append(var)59 return v60def in_both(v1, v2):61 v = []62 for var in v2:63 if var in v1:64 v.append(var)65 return v66def convert_sentence_pair_to_az(s1, s2):67 comb = s1 + "\t" + s268 comb_replaced, map = convert_sentence_to_az(comb)69 s1_new, s2_new = comb_replaced.split("\t")70 return s1_new, s2_new, map71def convert_sentence_to_az(sentence):72 if not "Symbol_" in sentence:73 return sentence, [] #already in az format74 else:75 split_sentence = sentence.split(" ")76 ind = 077 symb_to_az_list = [] #should be symb1 symb2 symb3 -> abc78 while ind < len(split_sentence):79 if "Symbol_" in split_sentence[ind]:80 current_symbol = split_sentence[ind]81 symb_to_az_list.append(current_symbol)82 char_mapped = chr(97 + len(symb_to_az_list) - 1)83 split_sentence = list(map(lambda x: x if x != current_symbol else char_mapped, split_sentence))84 elif len(split_sentence[ind]) > 1 and split_sentence[ind][0] in "()&|~>":85 split_sentence[ind] = split_sentence[ind][0]86 ind += 187 return "".join(split_sentence), symb_to_az_list88class TestConvertSentence(unittest.TestCase):89 def test_pass_forward(self):90 self.assertEqual(convert_sentence_to_az("((a&b)|c)")[0], "((a&b)|c)")91 self.assertEqual(convert_sentence_to_az("((a&b)|c)")[1], [])92 def test_convert(self):93 self.assertEqual(convert_sentence_to_az("( ( Symbol_1 & Symbol_2 ) | Symbol_3 )")[0], "((a&b)|c)")94 self.assertEqual(convert_sentence_to_az("( ( Symbol_1 & Symbol_2 ) | Symbol_1 )")[0], "((a&b)|a)")95def dict_to_world(az_map, symbol_map):96 cmap = "abcdefghijklmnopqrstuvwxyz"97 ret_world = ["0"] * 2698 for symbol in symbol_map.keys():99 if symbol_map[symbol] == True:100 bit = "1"101 else:102 bit = "0"103 ret_world[az_map.index(symbol)] = bit104 return ret_world105def sentence_satisfiable_in_world(sentence, world):106 az_sentence, az_mapping_list = convert_sentence_to_az(sentence)107 relevant_variables = get_relevant_variables(az_sentence)108 if type(world) == list:109 world = assign_world(world, relevant_variables)110 elif type(world) == dict:111 world = dict_to_world(az_mapping_list, world)112 truthval = apl.parse(az_sentence, world)113 return truthval114def satisfying_assignment_exists(sentence, symbols):115 """116 Determine whether an assignment of symbols exists that satisifes the sentence117 input:118 sentence: space_split string of symbols, parens, and operators119 symbols: list of unique non-operator symbols in `sentence`120 output:121 truthval: True if assignment of symbols exists that satisfies sentence, False otherwise122 assignment: dict of {string : bool} values dictating the symbol:truth value variable assignment that satisfies sentence123 """124 num_symbols = len(symbols)125 str_num_symbols = str(num_symbols)126 for i in range(2 ** num_symbols):127 world = ('{0:0' + str_num_symbols + 'b}').format(i)128 variable_assignment = apl.getdict_list(world, symbols)129 truthval = apl.eval_assignment_in_world(sentence, variable_assignment)130 if truthval == True:131 return True, variable_assignment132 return False, {}133def all_satisfying_assignments(sentence, symbols):134 """135 Determine whether an assignment of symbols exists that satisifes the sentence136 input:137 sentence: space_split string of symbols, parens, and operators138 symbols: list of unique non-operator symbols in `sentence`139 output:140 assignments: list of dict of {string : bool}. each dict is values dictating the symbol:truth value variable assignment that satisfies sentence141 if no assignments satisfy, then return empty list142 """143 satisfying_assignments = []144 num_symbols = len(symbols)145 str_num_symbols = str(num_symbols)146 for i in range(2 ** num_symbols):147 world = ('{0:0' + str_num_symbols + 'b}').format(i)148 variable_assignment = apl.getdict_list(world, symbols)149 truthval = apl.eval_assignment_in_world(sentence, variable_assignment)150 if truthval == True:151 satisfying_assignments.append(variable_assignment)152 return satisfying_assignments153class TestFindSatisfyingArgument(unittest.TestCase):154 def test_true(self):155 self.assertTrue(satisfying_assignment_exists("( ( Symbol_1 & Symbol_2 ) | Symbol_3 )")[0])156 self.assertEqual(satisfying_assignment_exists("( Symbol_1 & Symbol_2 )")[1], {"Symbol_1": True, "Symbol_2": True})157 def test_false(self):158 self.assertFalse(satisfying_assignment_exists("( Symbol_1 & ~ ( Symbol_1 ) )")[0])159 def test_az(self):160 self.assertTrue(satisfying_assignment_exists("(a&b)"))161 self.assertFalse(satisfying_assignment_exists("(a&~(a))"))162def eval(split, verbose = False):163 prem_vars = get_relevant_variables(split[0])164 hyp_vars = get_relevant_variables(split[1])165 inb = in_both(prem_vars, hyp_vars)166 relevant_variables = combine_vars(prem_vars, hyp_vars)167 l_t = len(relevant_variables)168 s_lt = str(l_t)169 seen = [] #map of int (representing line # for train/test items) to seen worlds170 premise = split[0]171 hypothesis = split[1]172 prem_true = 0173 prem_false = 0174 hyp_true = 0175 hyp_false = 0176 both_true = 0177 #seen_ml = False #have we seen the most likely world yet?178 for i in range(2 ** l_t):179 world = ('{0:0' + s_lt + 'b}').format(i)180 world = assign_world(world, relevant_variables)181 truthval = apl.parse(premise, world)182 hyp_is_true = apl.parse(hypothesis, world)183 if hyp_is_true == True:184 hyp_true += 1185 else:186 hyp_false += 1187 if truthval == True:188 prem_true += 1189 else:190 prem_false += 1191 if hyp_is_true == True and truthval == True:192 both_true += 1193 p_p = prem_true * 1.0 / (prem_true + prem_false)194 p_h = hyp_true * 1.0 / (hyp_true + hyp_false)195 p_b = both_true * 1.0 / (hyp_true + hyp_false)196 try:197 p_cond = p_b / p_p198 except ZeroDivisionError:199 p_cond = 0200 if verbose == True:201 print("Premise true for:\t{}".format(prem_true))202 print("Premise false:\t{}".format(prem_false))203 print("Hypothesis true for:\t{}".format(hyp_true))204 print("Hypothesis false:\t{}".format(hyp_false))205 print("Both true:\t{}".format(both_true))206 return p_p, p_h, p_b, p_cond207def eval2(split, verbose = False):208 premise = split[0]209 hypothesis = split[1]210 '''if type(premise) == list:211 premise = " ".join(premise)212 hypothesis = " ".join(hypothesis)'''213 if "Symbol_" in premise:214 premise, hypothesis,map = convert_sentence_pair_to_az(premise,hypothesis)215 prem_vars = get_relevant_variables(premise)216 hyp_vars = get_relevant_variables(hypothesis)217 inb = in_both(prem_vars, hyp_vars)218 relevant_variables = combine_vars(prem_vars, hyp_vars)219 l_t = len(relevant_variables)220 s_lt = str(l_t)221 seen = [] #map of int (representing line # for train/test items) to seen worlds222 prem_true = 0223 prem_false = 0224 hyp_true = 0225 hyp_false = 0226 both_true = 0227 entailed = True228 equiv = True229 #seen_ml = False #have we seen the most likely world yet?230 for i in range(2 ** l_t):231 world = ('{0:0' + s_lt + 'b}').format(i)232 world = assign_world(world, relevant_variables)233 truthval = apl.parse(premise, world)234 hyp_is_true = apl.parse(hypothesis, world)235 if hyp_is_true == True:236 hyp_true += 1237 else:238 hyp_false += 1239 if truthval == True:240 if hyp_is_true == False:241 entailed = False242 prem_true += 1243 else:244 prem_false += 1245 if hyp_is_true == True and truthval == True:246 both_true += 1247 elif hyp_is_true != truthval:248 equiv = False249 p_p = prem_true * 1.0 / (prem_true + prem_false)250 p_h = hyp_true * 1.0 / (hyp_true + hyp_false)251 p_b = both_true * 1.0 / (hyp_true + hyp_false)252 try:253 p_cond = p_b / p_p254 except ZeroDivisionError:255 p_cond = 0256 if verbose == True:257 print("Premise true for:\t{}".format(prem_true))258 print("Premise false:\t{}".format(prem_false))259 print("Hypothesis true for:\t{}".format(hyp_true))260 print("Hypothesis false:\t{}".format(hyp_false))261 print("Both true:\t{}".format(both_true))262 return p_p, p_h, p_b, p_cond, entailed, equiv263if __name__ == "__main__":...
lowestCommonAnces.py
Source:lowestCommonAnces.py
1#!/usr/bin/python2"""3The lowest common ancestor is defined between two nodes v and w as the lowest node in T4that has both v and w as descendants (where we allow a node to be a descendant of itself).5Find the lowest common ancestor.6#2367REDDO: figure out the algo quick8"""9from btNode import BTNode10def lca(n, p, q):11 if n == None or n == p or n == q: return n12 lhs = lca(n.left, p, q)13 rhs = lca(n.right, p, q)14 if lhs and rhs: return n15 return lhs if lhs else rhs16def lca_non_valid_node(node, t1, t2):17 both_true = [False]*218 res = lca_nvn(node, t1, t2, both_true)19 if both_true[0] and both_true[1]:20 return res.val21 else:22 return -123def lca_nvn(node, t1, t2, both_true):24 if not node:25 return None26 ret_n = None27 if node == t1 or node == t2:28 if node == t1:29 both_true[0] = True30 else:31 both_true[1] = True32 ret_n = node33 lhs = lca_nvn(node.left, t1, t2, both_true)34 rhs = lca_nvn(node.right, t1, t2, both_true)35 if lhs and rhs:36 return node37 if not ret_n:38 ret_n = lhs if lhs else rhs39 return ret_n40def test1():41 n3 = BTNode(3)42 n5 = BTNode(5)43 n6 = BTNode(6)44 n2 = BTNode(2)45 n7 = BTNode(7)46 n4 = BTNode(4)47 n1 = BTNode(1)48 n0 = BTNode(0)49 n8 = BTNode(8)50 n3.left = n551 n5.left = n652 n3.right = n153 n5.right = n254 n2.left = n755 n2.right = n456 n1.left = n057 n1.right = n858 n_nonvalid = BTNode(13)59 print(lca(n3, n6, n2).val)60 print(lca_non_valid_node(n3, n6, n_nonvalid))61 print(lca_non_valid_node(n3, n6, n2))62 print(lca_non_valid_node(n3, n4, n2))63if __name__ == '__main__':...
correlation.py
Source:correlation.py
1# Add the functions in this file2import json3import math4def load_journal(file1):5 with open(file1) as j:6 data = json.load(j)7 return data 8def compute_phi(file1, event):9 data_dict = load_journal(file1)10 both_true=011 both_false=012 x_true=013 y_true=014 for i in range(len(data_dict)):15 if event in data_dict[i]["events"] and data_dict[i]["squirrel"]:16 both_true+=117 elif event in data_dict[i]["events"]:18 x_true+=119 elif data_dict[i]["squirrel"]:20 y_true+=121 else:22 both_false+=1 23 only_x = both_true + x_true24 only_y = both_true + y_true25 not_x = both_false + y_true26 not_y = both_false + x_true 27 corr = (both_true*both_false - x_true*y_true)/math.sqrt(only_x*only_y*not_x*not_y)28 return corr29def compute_correlations(file1):30 journal_file = load_journal(file1)31 events ={}32 event_lol=[]33 for i in range(len(journal_file)):34 event_x = journal_file[i]["events"]35 for j in event_x:36 if j not in event_lol:37 event_lol.append(j)38 for k in event_lol:39 events[k] = compute_phi(file1, k)40 return events41def diagnose(file1):42 journal_file = load_journal(file1)43 events = compute_correlations(file1)44 max_key = max(events, key=events.get)45 min_key = min(events, key=events.get)46 ...
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!!