def OR(goal, why, how, top): ask = 1 res = [] dict1 = how[top][1][1] for rule in kbase.match_then(goal, dict1): for then in rule['then']: then, cft = certainty(then) dict2 = {} matched, changes = match(goal, then, dict1, dict2) if matched: ask = 0 why2 = [(goal, dict1, rule['rule'])] + why how2 = how + [(goal, (rule['rule'], dict2))] for (proof, cfi) in AND(rule['if'], why2, how2, len(how)): res.append((proof, cft * cfi)) for (var, env) in changes: env[var] = '?' if ask: cf = ask_user(kbase, goal, dict1, known, why) if cf: res = [(how + [(goal, 'told')], cf)] return res
def bindings(ifs, facts, dict, why): if ifs == []: return [(copy_dict(dict), [])] # all conjuncts matched res = [] head, tail = ifs[0], ifs[1:] if head[0] == 'ask': ground = substitute(head[1:], dict) if ask_user(ground, facts, why): for (dict2, proof2) in bindings(tail, facts, dict, why): res.append((dict2, [(ground, 'told')] + proof2)) elif head[0] == 'not': ground = substitute(head[1:], dict) if not asserted(ground, facts) or asserted(['not']+ground, facts): for (dict2, proof2) in bindings(tail, facts, dict, why): res.append((dict2, [(ground, 'not')] + proof2)) else: for (fact, proof) in facts: matched, changes = match(head, fact, dict, {}) if matched: for (dict2, proof2) in bindings(tail, facts, dict, why): res.append((dict2, [(fact, proof)] + proof2)) for (var, env) in changes: env[var] = '?' return res
def addBuildings(user_id): result = {"features": []} with open('%s_tweets_building.json' % user_id, 'w') as jsonout: with open('%s_tweets.json' % user_id, 'r') as jsonin: content = json.load(jsonin) with open('buildings.json', 'r') as f: tweet = json.load(f) for data in content["content"]: if data["coordinates"]: lat = data["coordinates"]["coordinates"][0] long = data["coordinates"]["coordinates"][1] features = { "coordinates": [lat, long], "text": data["text"], "id": data["id"], "created_at": data["created_at"], "location": data["location"], "buildings": [], } for tw in tweet['features']: coordinate = tw['geometry']['coordinates'] if match(lat, long, coordinate): features["buildings"].append(tw["properties"]) result["features"].append(features) jsonout.write(json.dumps(result, indent=4)) jsonout.close()
def print_solns(known, filter): sources = {'rule': [], 'told': [], 'init': [], 'atom': []} for (fact, proof) in known.members(): if not filter or match(filter, fact, {}, {})[0]: if type(proof) == type(()): sources['rule'].append((fact, proof)) # deduced elif proof == 'told' or proof == 'not': sources['told'].append(fact) elif proof == 'initial': sources['init'].append(fact) elif proof == 'atomic': sources['atom'].append(fact) if not sources['rule']: print 'I have not deduced any new facts.' else: print 'I deduced these facts...' for (fact, proof) in sources['rule']: print ' ', external([fact]) #, '(by rule',proof[0]+')' if sources['told']: print 'You told me these facts...' for fact in sources['told']: print ' ', external([fact]) if sources['init']: print 'I started with these facts...' for fact in sources['init']: print ' ', external([fact])
def print_solns(known, filter): sources = {'rule':[], 'told':[], 'init':[], 'atom':[]} for (fact, proof) in known.members(): if not filter or match(filter, fact, {}, {})[0]: if type(proof) == type(()): sources['rule'].append((fact, proof)) # deduced elif proof == 'told' or proof == 'not': sources['told'].append(fact) elif proof == 'initial': sources['init'].append(fact) elif proof == 'atomic': sources['atom'].append(fact) if not sources['rule']: print 'I have not deduced any new facts.' else: print 'I deduced these facts...' for (fact, proof) in sources['rule']: print ' ', external([fact]) #, '(by rule',proof[0]+')' if sources['told']: print 'You told me these facts...' for fact in sources['told']: print ' ', external([fact]) if sources['init']: print 'I started with these facts...' for fact in sources['init']: print ' ', external([fact])
def conjunct(ifs, known, dict, why): if ifs == []: return [(copy_dict(dict), [])] # all conjuncts matched res = [] head, tail = ifs[0], ifs[1:] if head[0] == 'ask': term = substitute(head[1:], dict) if ask_user(term, known, why): for (dict2, proof2) in conjunct(tail, known, dict, why): res.append((dict2, [(term, 'told')] + proof2)) elif head[0] == 'not': term = substitute(head[1:], dict) if not known.search_unique(term) or \ known.search_unique(['not'] + term): for (dict2, proof2) in conjunct(tail, known, dict, why): res.append((dict2, [(term, 'not')] + proof2)) else: for (fact, proof) in known.search(head, dict): matched, changes = match(head, fact, dict, {}) if matched: for (dict2, proof2) in conjunct(tail, known, dict, why): res.append((dict2, [(fact, proof)] + proof2)) for (var, env) in changes: env[var] = '?' return res
def gen_candidates(self, w, k): """get candidates of w within edit distance of k Args: w: Return: """ lev_dfa = self.construct_levenshten(w, k) return list(match(self.corpus_dfa, lev_dfa))
def search(pattern, db): """ Searches trough a database with given pattern and returns a list of matching entries """ retSeq = [] for entry in db: if match(entry, pattern): retSeq.append(entry) return retSeq
def post(self, *args, **kwargs): pics = self.request.files.get('picture', []) filename = pics[0]['filename'] + str(time.time()) save_path = './{}'.format(filename) print(save_path) with open(save_path, 'wb+') as f: f.write(pics[0]['body']) res = match(filename) self.write(str(res))
def regular_season(teams): """ Regular season - 14 days, 56 speedway matches - 4 matches each day. """ day_num = 1 all_results = [] for day in league: day_results = [] input("\n Naciśnij ENTER by przejść do kolejki nr. " + str(day_num)) print("\t\t\tKOLEJKA NR. " + str(day_num)) for one_match in day: print(one_match[0].team_name + " - " + one_match[1].team_name) input("\n Naciśnij ENTER by przejść do następnego meczu.\n") for one_match in day: match(one_match[0], one_match[1], day_results) print("\nWyniki KOLEJKI NR. " + str(day_num) + "\n") all_results.append(day_results) day_num += 1 for result in all_results[day_num - 2]: print(result) input("\n Naciśnij ENTER by przejść dalej \n") menu(day_num, teams) end_of_game(teams)
def bchain(kbase, state, back, known, pmode): top = state kindex, tindex = 0, 0 while 1: if kindex == None: print 'no (more) solutions [backwrd3.py]' return if state == None: if not report(kbase, top[0], top[1], pmode): return else: state, kindex, tindex, rule_set, back = backtrack(back) continue (dict, goals, curr, rid, parent) = state matched = 0 first_try = (kindex == 0 and tindex == 0) if first_try: rule_set = kbase.match_then(goals[curr], dict) for rule in rule_set[kindex:]: for then in rule['then'][tindex:]: dict2 = {} matched, changes = match(goals[curr], then, dict, dict2) if matched: back = (state, changes, kindex, tindex, rule_set, back) state = (dict2, rule['if'], 0, rule['rule'], state) kindex, tindex = 0, 0 break else: for var, env in changes: env[var] = '?' tindex = tindex + 1 if matched: break kindex, tindex = kindex + 1, 0 if not matched: if not first_try: state, kindex, tindex, rule_set, back = backtrack(back) else: if ask_user1(kbase, goals[curr], dict, known, state): state, kindex, tindex = nextgoal(state), 0, 0 else: state, kindex, tindex, rule_set, back = backtrack(back)
def GEN(goal, dict, goals, why, how): # match 'then' ask = 1 for rule in kbase: # select rule for then in rule['then']: # and descend dict2 = {} matched, changes = match(goal, then, dict, dict2) if matched: ask = 0 why2 = [(goal, dict, rule['rule'])] + why how2 = how + [(goal, (rule['rule'], dict2))] TEST(pushgoals(rule['if'], dict2, goals), why2, how2) for (var, env) in changes: env[var] = '?' if ask and ask_user(goal, dict, known, why): TEST(goals, why, how + [(goal, 'told')])
def GEN(goal, dict, goals, why, how): # match 'then' ask = 1 for rule in kbase.match_then(goal, dict): # select rule for then in rule['then']: # and descend dict2 = {} matched, changes = match(goal, then, dict, dict2) if matched: ask = 0 why2 = [(goal, dict, rule['rule'])] + why how2 = how + [(goal, (rule['rule'], dict2))] TEST(pushgoals(rule['if'], dict2, goals), why2, how2) for (var, env) in changes: env[var] = '?' if ask and ask_user(kbase, goal, dict, known, why): TEST(goals, why, how + [(goal, 'told')])
def GEN(goal, dict, goals, why, how): # match 'then' ask = 1 for rule in kbase: # select rule for then in rule["then"]: # and descend dict2 = {} matched, changes = match(goal, then, dict, dict2) if matched: ask = 0 why2 = [(goal, dict, rule["rule"])] + why how2 = how + [(goal, (rule["rule"], dict2))] TEST(pushgoals(rule["if"], dict2, goals), why2, how2) for (var, env) in changes: env[var] = "?" if ask and ask_user(goal, dict, known, why): TEST(goals, why, how + [(goal, "told")])
def bchain(kbase, state, back, known, pmode): top = state kindex, tindex = 0, 0 while 1: if kindex == None: print 'no (more) solutions [backwrd3.py]' return if state == None: if not report(kbase, top[0], top[1], pmode): return else: state, kindex, tindex, rule_set, back = backtrack(back) continue (dict, goals, curr, rid, parent) = state matched = 0 first_try = (kindex == 0 and tindex == 0) if first_try: rule_set = kbase.match_then(goals[curr], dict) for rule in rule_set[kindex:]: for then in rule['then'][tindex:]: dict2 = {} matched, changes = match(goals[curr], then, dict, dict2) if matched: back = (state, changes, kindex, tindex, rule_set, back) state = (dict2, rule['if'], 0, rule['rule'], state) kindex, tindex = 0, 0 break else: for var, env in changes: env[var] = '?' tindex = tindex+1 if matched: break kindex, tindex = kindex+1, 0 if not matched: if not first_try: state, kindex, tindex, rule_set, back = backtrack(back) else: if ask_user1(kbase, goals[curr], dict, known, state): state, kindex, tindex = nextgoal(state), 0, 0 else: state, kindex, tindex, rule_set, back = backtrack(back)
def bchain(kbase, state, back, known, pmode): top = state kindex, tindex = 0, 0 while 1: if kindex == None: print "no (more) solutions [backwrd3.py]" return if state == None: if not report(top[0], top[1], pmode): return else: state, kindex, tindex, back = backtrack(back) continue (dict, goals, curr, rid, parent) = state first_try = kindex == 0 and tindex == 0 matched = 0 for rule in kbase[kindex:]: for then in rule["then"][tindex:]: dict2 = {} matched, changes = match(goals[curr], then, dict, dict2) if matched: back = (state, changes, kindex, tindex, back) state = (dict2, rule["if"], 0, rule["rule"], state) kindex, tindex = 0, 0 break else: for var, env in changes: env[var] = "?" tindex = tindex + 1 if matched: break kindex, tindex = kindex + 1, 0 if not matched: if not first_try: state, kindex, tindex, back = backtrack(back) else: if ask_user1(goals[curr], dict, known, state): state, kindex, tindex = nextgoal(state), 0, 0 else: state, kindex, tindex, back = backtrack(back)
def show_proofs(known): while 1: print ans = raw_input('show proofs? ') if ans in ['y','Y','yes','YES']: [patt] = internal(raw_input('enter deductions pattern: ')) for (fact, proof) in known: if match(patt, fact, {}, {})[0]: trace_tree((fact, proof), 0) elif ans in ['n','N','no','NO']: break elif ans == 'where': print_solns(known, None) elif ans == 'browse': browse_pattern(rulebase, raw_input('enter browse pattern: ')) else: print 'what? (expecting "y", "n", "where", or "browse")'
def OR(goal, dict, why, how, cont): # match 'then' rules = 0 for rule in kbase: # select rule for then in rule['then']: # and descend dict2 = {} matched, changes = match(goal, then, dict, dict2) if matched: rules = 1 why2 = [(goal, dict, rule['rule'])] + why how2 = how + [(goal, (rule['rule'], dict2))] AND(rule['if'], dict2, why2, cont, how2) for (var, env) in changes: env[var] = '?' if not rules: if ask_user(goal, dict, known, why): apply(cont[0], cont[1] + (how + [(goal, 'told')],) )
def OR(goal, dict, why, how, cont): # match 'then' rules = 0 for rule in kbase: # select rule for then in rule['then']: # and descend dict2 = {} matched, changes = match(goal, then, dict, dict2) if matched: rules = 1 why2 = [(goal, dict, rule['rule'])] + why how2 = how + [(goal, (rule['rule'], dict2))] AND(rule['if'], dict2, why2, cont, how2) for (var, env) in changes: env[var] = '?' if not rules: if ask_user(goal, dict, known, why): apply(cont[0], cont[1] + (how + [(goal, 'told')], ))
def show_proofs(known): while 1: print ans = raw_input('show proofs? ') if ans in ['y', 'Y', 'yes', 'YES']: [patt] = internal(raw_input('enter deductions pattern: ')) for (fact, proof) in known: if match(patt, fact, {}, {})[0]: trace_tree((fact, proof), 0) elif ans in ['n', 'N', 'no', 'NO']: break elif ans == 'where': print_solns(known, None) elif ans == 'browse': browse_pattern(rulebase, raw_input('enter browse pattern: ')) else: print 'what? (expecting "y", "n", "where", or "browse")'
def OR(goal, why, how, top): ask = 1 res = [] dict1 = how[top][1][1] for rule in kbase: for then in rule['then']: dict2 = {} matched, changes = match(goal, then, dict1, dict2) if matched: ask = 0 why2 = [(goal, dict1, rule['rule'])] + why how2 = how + [(goal, (rule['rule'], dict2))] for proof in AND(rule['if'], why2, how2, len(how)): res.append(proof) for (var, env) in changes: env[var] = '?' if ask and ask_user(goal, dict1, known, why): res = [how + [(goal, 'told')]] return res
def OR(goal, stack, why, how): ask = 1 res = [] for rule in kbase: for then in rule['then']: dict2 = {} matched, changes = match(goal, then, stack[0], dict2) if matched: ask = 0 why2 = [(goal, stack[0], rule['rule'])] + why how2 = how + [(goal, [rule['rule'], '?'])] below = AND(rule['if'], [dict2] + stack, why2, how2) for (stack2, proof) in below: proof[len(how2)-1][1][1] = stack2[0] res.append((stack2[1:], proof)) for (var, env) in changes: env[var] = '?' if ask and ask_user(goal, stack[0], known, why): res = [(stack, how + [(goal, 'told')])] return res
def OR(goal, stack, why, how): ask = 1 res = [] for rule in kbase: for then in rule['then']: dict2 = {} matched, changes = match(goal, then, stack[0], dict2) if matched: ask = 0 why2 = [(goal, stack[0], rule['rule'])] + why how2 = how + [(goal, [rule['rule'], '?'])] below = AND(rule['if'], [dict2] + stack, why2, how2) for (stack2, proof) in below: proof[len(how2) - 1][1][1] = stack2[0] res.append((stack2[1:], proof)) for (var, env) in changes: env[var] = '?' if ask and ask_user(goal, stack[0], known, why): res = [(stack, how + [(goal, 'told')])] return res
def OR(goal, dict, why, how, cont): # match 'then' rules = 0 for rule in kbase: # select rule for then in rule['then']: # and descend try: dict2 = {} matched, changes = match(goal, then, dict, dict2) if matched: rules = 1 why2 = [(goal, dict, rule['rule'])] + why how2 = how + [(goal, (rule['rule'], dict2))] AND(rule['if'], dict2, why2, cont, how2) except backtrack: pass # try next rule for (var, env) in changes: env[var] = '?' # reset vars if not rules: if ask_user(goal, dict, known, why): # ask goal apply(cont[0], cont[1] + (how + [(goal, 'told')],) ) raise backtrack # all rules failed or answer='no'
def conjunct(ifs, known, dict, why): if ifs == []: return [(copy_dict(dict), 1.1, [])] res = [] head, tail = ifs[0], ifs[1:] if head[0] == 'ask': term = substitute(head[1:], dict) cf = ask_user(term, known, why) if cf != 0.0: for (dict2, cf2, proof2) in conjunct(tail, known, dict, why): res.append((dict2, min(cf, cf2), [(term, 'told')] + proof2)) else: for (fact, cf, proof) in known.search(head, dict): if cf == 0.0: continue matched, changes = match(head, fact, dict, {}) if matched: for (dict2, cf2, proof2) in conjunct(tail, known, dict, why): res.append((dict2, min(cf, cf2), [(fact, proof)] + proof2)) for (var, env) in changes: env[var] = '?' return res
def OR(goal, dict, why, how, cont): # match 'then' rules = 0 for rule in kbase: # select rule for then in rule['then']: # and descend try: dict2 = {} matched, changes = match(goal, then, dict, dict2) if matched: rules = 1 why2 = [(goal, dict, rule['rule'])] + why how2 = how + [(goal, (rule['rule'], dict2))] AND(rule['if'], dict2, why2, cont, how2) except backtrack: pass # try next rule for (var, env) in changes: env[var] = '?' # reset vars if not rules: if ask_user(goal, dict, known, why): # ask goal apply(cont[0], cont[1] + (how + [(goal, 'told')], )) raise backtrack # all rules failed or answer='no'
import img import imgio import transf import discret import split import match from PIL import Image #programa principal print(match(read_bn("2n2021/1matricula/sortida/digit_3.jpeg"), load_patterns()))
# 2-Llegir la imatge de la matricula.modul imgio # 3-Convertir la matricula en blanc i negre. modul discret img = rgb_to_bn(imgio.read_rgb(matricula)) img = vtrim(htrim(img[1])) print "Detectant els digits..." img_digits = [] numImg = (img, img) while True: numImg = split_digit(numImg[1]) img_digits += [numImg[0]] if numImg[1] == []: break numImg = ([], numImg[1]) total_dig = len(img_digits) digits = [] for i, digit in enumerate(img_digits): dig = str(match(digit, patterns)) if dig == "-1": continue digits += [dig] print "Completat", (i+1) / float(total_dig) * 100, "%" # 7-Mostrar l'enter que correspon a la matricula. print "\nMatrícula:", for i, num in enumerate(digits): print num, if i == 3 and total_dig > 4: print "-",
def get_matches(xyf): xyf = list(xyf) base = open(xyf[0][2]).read() for x, y, f in xyf: m = match(base, open(f).read()) yield x, y, f, m
def add_matrix(start, end): for i in range(start, end): mat, q = match(matrices[i - 1], matrices[i]) merger.add_matrix(mat, str(i - 1), str(i))
def getdata(id): toload=None for file in os.listdir("data"): if re.match("^"+str(id)+".*",file): toload=file break assert(toload is not None) print("loading ",toload) dframe=pd.read_excel(os.path.join('data',toload),dtype=np.str) scores=[] for i,d in zip(range(len(dframe)),dframe): if(i==16): scores=dframe[d] assert(len(scores)>0) sets=[] points=[] setma=0 setfan=0 scorema=0 scorefan=0 for (index,row),res in zip(dframe.iterrows(),scores): if(res in['樊得','马得']): bats=[] last=None for r in row[1:]: r=str(r).replace(' ',"") if len(r)<1: continue if not re.match("nan",r) and not r in ['樊得','马得']: b=None if re.match("^[abcd]-(A1|A2|B1|B2|C1|C2)$",r): b=bat(type=0,method=r[0],fall=r[2:]) elif re.match("^[abcd]$",r): b=bat(type=1,method=r) elif re.match("^\d+-[ABCD]$",r): b=bat(type=2,method=r[0:-2],fall=r[-1],last=last) elif re.match("^\d+$",r): b=bat(type=3,method=r,last=last) if b is None: print("report outlier",setma, setfan, scorema, scorefan, r, res) continue bats.append(b) last=b winner="fan" if res=='樊得' else "ma" p=point(bats,winner,scorema,scorefan) if winner=='fan': scorefan+=1 else: scorema+=1 points.append(p) else: if len(points)>0: s=set(points,setma,setfan) points=[] sets.append(s) if(scorema>scorefan): setma=setma+1 else: setfan=setfan+1 scorema=0 scorefan=0 m=match(sets) return m
def main(): input("게임을 시작하려면 엔터") print("\n" * 38) try: import save except: player_name = input("\n플레이어 이름을 입력하십시오. = ") while player_name == "": print("\n유효한 이름을 입력하십시오") player_name = input("플레이어 이름을 입력하십시오. = ") player_1 = Player(player_name, 1, 0, [], [], [], 0, 0, 0) plag = 0 time.sleep(1.3) print('\n' * 2) print("정상적으로 로그인 되었습니다.") time.sleep(0.7) print("정보 불러오는 중...") time.sleep(0.7) print(f"환영합니다. {player_name}님") time.sleep(1) while True: print("\n" * 38) turn_chack(player_1) # 아레나, 스텟(레벨) player_1.showinfo() print(f"나의스텟 (힘,민첩,모험) : {po_count}/{ag_count}/{ad_count}") if plag == 0: print("\n도움을 원한다면 'z' 입력") ans = input("\n무엇을 하시겠습니까? : ") if ans == "q" or ans == "w" or ans == "e" or ans == "r" or ans == "t" or ans == "y": match(player_1) elif ans == "a": martial_arts_inventory(player_1) elif ans == "s": inventory(player_1, 'item') continue elif ans == "d": showshop(player_1) continue elif ans == "z": print( "\n게임설명\n전투시작 : q,w,e,r,t,y\n무술 장착 및 해제 : a\n인벤토리 : s\n상점 : d\n도움말 : z\n게임종료 : p\ \n한국어를 웬만하면 누르지 마세요.(버그의 원인이 됩니다.)\n다 읽으셨다면 enter.") input() elif ans == "p": game_over() else: print("다시 입력해 주십시오") plag += 1