text
stringlengths
37
1.41M
""" 定义项目中所有对容器的操作。 """ class ListHelper: """ 列表助手类 """ @staticmethod def find_all(iterable_target,func_condition): """ 在可迭代对象中,查找满足条件的所有元素。 :param iterable_target:可迭代对象 :param func_condition:所有条件 :return:生成器对象 """ for item in iterable_target: if func_condition(item): yield item @staticmethod def find_single(iterable_target,func_condition): """ 在可迭代对象中,查找满足条件的单个元素。 :param iterable_target:可迭代对象 :param func_condition:所有条件 :return:元素 """ for item in iterable_target: if func_condition(item): return item @staticmethod def sum(iterable_target,func_condition): """ 在可迭代对象中,根据条件求和。 :param iterable_target:可迭代对象 :param func_condition:求和条件 :return:求和的数值 """ sum_value = 0 for item in iterable_target: sum_value += func_condition(item) return sum_value @staticmethod def select(iterable_target,func_condition): """ 在可迭代对象中,根据条件选择属性。 :param iterable_target:可迭代对象 :param func_condition:筛选条件 :return:生成器对象 """ for item in iterable_target: yield func_condition(item) @staticmethod def get_max(iterable_target,func_condition): """ 在可迭代对象中,根据条件获取最大元素。 :param iterable_target:可迭代对象 :param func_condition:获取条件 :return:最大元素 """ max_value = iterable_target[0] for i in range(1,len(iterable_target)): # if max_value.atk < iterable_target[i].atk: if func_condition(max_value) < func_condition(iterable_target[i]): max_value = iterable_target[i] return max_value @staticmethod def order_by(iterable_target,func_condition): """ 对可迭代对象, 根据任意条件进行升序排列 :param iterable_target: 可迭代对象 :param func_condition: 排序条件 """ for r in range(len(iterable_target)-1): for c in range(r+1,len(iterable_target)): # if iterable_target[r].atk > iterable_target[c].atk: if func_condition(iterable_target[r]) > func_condition(iterable_target[c]): iterable_target[r],iterable_target[c] = iterable_target[c],iterable_target[r]
# kadane's with Max Sum with Min length. # Need a max sum subarray - print sum and indexes, If there are more than 1 then give the smallest. arr = [1,4,-2,7,-10,5,5] max_sum,summ = arr[0], arr[0] x,y,x_temp = 0,0,0 for i in range(1,len(arr)): summ += arr[i] if summ > max_sum: max_sum = summ y = i x = x_temp if summ == max_sum: if (y-x) > (i-x_temp): y=i x = x_temp if summ <= 0: # will choose max length if 2 subaarys are possible ==> NO summ = 0 x_temp = i+1 print(max_sum,x,y)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' https://www.udemy.com/making-graphs-in-python-using-matplotlib-for-beginners/learn/v4/t/lecture/6304460 6. Creating 1-Dimensional and 2-Dimensional Histograms ''' import matplotlib.pyplot as plt with open("Goals.txt", "r") as f: HomeTeamGoals = [ int(x) for x in f.readline().strip("\n").strip(" ").split(" ")] AwayTeamGoals = [ int(x) for x in f.readline().strip("\n").strip(" ").split(" ")] TotalGoals = HomeTeamGoals + AwayTeamGoals plt.figure(figsize = (8, 5)) plt.hist(x = (HomeTeamGoals, AwayTeamGoals, TotalGoals), bins = range(8), label = ["Home Team Goals", "Away Team Goals", "Total Goals Scored"], align = "left") plt.legend() plt.xlabel("Goals Scored") plt.ylabel("Number of goals scored") plt.show() plt.figure(figsize = (8, 5)) plt.hist2d(x = HomeTeamGoals, y = AwayTeamGoals, bins = (range(8), range(7))) plt.xlabel("Home Team Goals") plt.ylabel("Away Team Goals") plt.colorbar() plt.show()
""" Handles debugging tasks """ def print_results(links): counter = 0 print("We found: {0} links!".format(len(links))) for link in links: counter += 1 print ("Link {0}: {1}".format(counter, link))
from pessoa import pessoa from matricula import matricula class aluno(pessoa): m = matricula() def __int__(self): self.codigo = 0 self.desconto = 0.0 self.interesse = '' def cadastrarAluno(self, codigo, desconto): self.nome = input('Nome:') self.rg = input('RG: ') self.cpf = input('Cpf: ') self.ano = int(input('Ano do Nascimento: ')) self.mes = int(input('Mes do Nascimento: ')) self.dia = int(input('Dia do Nasc.:')) self.sexo = input('Gênero: ') self.codigo = codigo self.interesse = input('Interesse em qual curso:') self.m.cadMatricula(desconto) self.desconto = desconto super().cadastrarPessoa(self.nome, self.rg, self.cpf, self.ano, self.mes, self.dia, self.sexo) def exibirAluno(self): print('\n Aluno \n') super().exibir() self.m.exibirMatricula() print(f'Código: {self.codigo}') print(f'Interresse: {self.interesse}') print(f'Desconto: {self.desconto}')
import unittest from app.models import Category class CategoryTest(unittest.TestCase): ''' Test Class to test the behaviour of the Category class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_category = Category('MIKE ISAAC and TAYLOR LORENZ','Sumter mirrors SC, nation in COVID-19\'s disproportionate impact on African-Americans','2020-09-12T01:20:00Z','https://edition.cnn.com/','https://www.nytimes.com/article/wildfires-photos-california-oregon-washington-state.html','News and buzz') def test_instance(self): ''' Test to check creation of new Category instance,(is True) ''' self.assertTrue(isinstance(self.new_category,Category))
import math a = 1 b = -4 c = 3 D = b*b-4*a*c print (D) if D>0: x1 = (-b-math.sqrt(D))/(2*a) x2 = (-b+math.sqrt(D))/(2*a) print (x1) print (x2) else: print ("корней нет")
from random import shuffle """ Select last element as the pivot Then move all element less than pivot to left of pivot and all element greate to the right of pivot, Then split the array based on the current index of the pivot Repeat this step till get sorted application: Medical and industrial monitoring, Control for aircraft, Defence """ def partition(arr,low,high): i = ( low-1 ) pivot = arr[high] for j in range(low , high): if arr[j] <= pivot: i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return ( i+1 ) def quickSort(arr,low,high): if low < high: pi = partition(arr,low,high) print("partition index: ", pi) quickSort(arr, low, pi-1) quickSort(arr, pi+1, high) if __name__ == '__main__': # a = list(range(10)) a = [0, 5, 2, 7, 6, 3, 4, 1, 9, 8] # shuffle(a) print(a) quickSort(a, 0, len(a)-1) print(a)
# Positions identify individual cells on game boards. def is_proper_position(dimension, position): """ Check whether the given position is a proper position for any board with the given dimension. - The given position must be a tuple of length 2 whose elements are both natural numbers. - The first element identifies the column. It may not exceed the given dimension. - The second element identifies the row. It may not exceed the given dimension incremented with 1 (taking into account the overflow position) ASSUMPTIONS - None """ if not isinstance(position, tuple) or len(position) != 2: return False if position[0] <= 0 or position[1] <= 0: # Negative integer return False if position[0] > dimension or position[1] > dimension + 1: # Greater than dimension return False return True def is_overflow_position(dimension, position): """ Check whether the given position is an overflow position for any board with the given dimension. - True if and only if the position is in the overflow row of the given board. ASSUMPTIONS - The given position is a proper position for any board with the given dimension. """ if position[1] == dimension + 1: return True return False def left(dimension, position): """ Return the position on any board with the given dimension immediately to the left of the given position. - None is returned if the generated position is outside the boundaries of a board with the given dimension. ASSUMPTIONS - The given position is a proper position for any board with the given dimension. """ left_pos = (position[0] - 1, position[1]) if position[0] == 1: return None else: return left_pos def right(dimension, position): """ Return the position on any board with the given dimension immediately to the right of the given position. - None is returned if the generated position is outside the boundaries of a board with the given dimension. ASSUMPTIONS - The given position is a proper position for any board with the given dimension. """ right_pos = (position[0] + 1, position[1]) if position[0] == dimension: return None else: return right_pos def up(dimension, position): """ Return the position on any board with the given dimension immediately above the given position. - None is returned if the generated position is outside the boundaries of a board with the given dimension. ASSUMPTIONS - The given position is a proper position for any board with the given dimension. """ up_pos = (position[0], position[1] + 1) if position[1] > dimension: return None else: return up_pos def down(dimension, position): """ Return the position on any board with the given dimension immediately below the given position. - None is returned if the generated position is outside the boundaries of a board with the given dimension. ASSUMPTIONS - The given position is a proper position for any board with the given dimension. """ down_pos = (position[0], position[1] - 1) if position[1] == 1: return None else: return down_pos def next(dimension, position): """ Return the position on any board with the given dimension next to the given position. - If the given position is not at the end of a row, the resulting position is immediately to the right of the given position. - If the given position is at the end of a row, the resulting position is the leftmost position of the row above. If that next row does not exist, None is returned. ASSUMPTIONS - The given position is a proper position for any board with the given dimension. """ row, column = position if column <= dimension + 1 and row < dimension: return right(dimension, position) elif column == dimension + 1 and row == dimension: return None else: return 1, column + 1 def get_all_adjacent_positions(dimension, positions): """ Return a mutable set of all positions adjacent to at least one of the positions in the given collection of positions and within the boundaries of any board with the given dimension. ASSUMPTIONS - Each position in the given collection of positions is a proper position for any board with the given dimension. """ adjacent_positions = set() for position in positions: set.add(adjacent_positions, left(dimension, position)) set.add(adjacent_positions, right(dimension, position)) set.add(adjacent_positions, up(dimension, position)) set.add(adjacent_positions, down(dimension, position)) set.discard(adjacent_positions, None) return adjacent_positions
#harmonic number algorithm class Harmonic(object): def __init__(self,term=1): self.term = term def harmonic(self): h=1 for i in range(2,self.term+1): h+=1/i return h
import queue ''' cola = queue.Queue() cola.put(4) cola.put([5,6,7]) print(cola.get())#muestra el primer valor de la cola print(cola.get()) print(cola.empty())''' cola = queue.PriorityQueue() cola.put(8) cola.put(5) cola.put(7) cola.put(6) cola.put(4) print(cola.get())
import random list = [1,2,3,4] #agregar info list.append(5)#forma de agregar un dato a la lista list += [6,7,8]# forma de agregar mas de un dato a la lista(mas = mas+4 == mas += 1) list.extend([9,10,7])# con el metodo extend print(list) #agregar en una posicion list.insert(0,0)#(pisicion,valor nuevo) list.insert(11,"numbers") print(list) print(list[5])#mostrar el dato en una posicion [-1] muestra el ultimo y menos dos el penultimo etc #borrar list.pop(11)#elimina un valor(posicion) sin especificar elimina el ultimo list.remove(0)#remueve un valor dato no la posicion print(list) #encontrar un valor en la lista print(10 in list) print(list.index(8)) print(list.index(7, 8))#(valor a buscar, apartir de donde buscar) print(list.count(7)) # copiar lista l2 = l1[:] print(list[1:8]) # muestra el congenido de una lista [inicio:fin : de dos en dos uno en uno etc] ran = [random.randint(1,100) for i in range(7)] print(ran) matriz = [['a','b','c'], ['d','e','f'], ['g','h','i']] print(matriz[2][1])#[num fila][num columna]
def difference(c): if c<=17: return 17-c else: return(c-17)*2 print(difference(33)) print(difference(15))
a=[1,2,3,'a',4,5,6] for i in a: print(i) list=['monday','tuesday','wednesday','thursday','friday'] for i in list: print(i) list_of_lists=[[1,2,3],['a','b','c']] list_of_lists.append([1,3,3]) print(list_of_lists) list=list*2 print(list) a.concatenate=[1,2,3]+[4] print(a)
def concatenate(list): result=' ' for element in list: result+=str(element) return result print(concatenate([2,3,4,5]))
import numpy as np import pandas as pd import matplotlib.pyplot as plt #reading dataset dataset=pd.read_csv('Mall_Customers.csv') #Reading the data that could make a cluster X=dataset.iloc[:,[3,4]].values # print(X) #Using dendogram to find minimum no of clusters import scipy.cluster.hierarchy as sch # Z = sch.linkage(X, method='ward') # dendogram=sch.dendrogram(Z) #Visualzing Dendogram # plt.title("Dendogram") # plt.xlabel("Customer") # plt.ylabel("Eucilidian Distance") # plt.show() # #training Hierachical cluster model on the dataset from sklearn.cluster import AgglomerativeClustering clustering = AgglomerativeClustering(n_clusters=5,affinity='euclidean',linkage='ward') hc_y=clustering.fit_predict(X) #Visualzing clusters plt.scatter(X[hc_y==0,0],X[hc_y==0,1],s=100,c='red',label='cluster1') plt.scatter(X[hc_y==1,0],X[hc_y==1,1],s=100,c='green',label='cluster2') plt.scatter(X[hc_y==2,0],X[hc_y==2,1],s=100,c='blue',label='cluster3') plt.scatter(X[hc_y==3,0],X[hc_y==3,1],s=100,c='black',label='cluster4') plt.scatter(X[hc_y==4,0],X[hc_y==4,1],s=100,c='brown',label='cluster5') # plt.scatter(hc_y.cluster_centers_[:,0],hc_y.cluster_centers_[:,1],s=400,c='cyan',label='Centroid') plt.title("Customers Clusters") plt.xlabel("Annual Income k($)") plt.ylabel("Spending score(1-100)") plt.legend() plt.show()
## HW 2 ## SI 364 F17 ## Due: September 24, 2017 ## 500 points ##### ## [PROBLEM 1] ## Edit the following Flask application code so that if you run the application locally and got to the URL http://localhost:5000/question, you see a form that asks you to enter your favorite number. Once you enter a number and submit it to the form, you should then see a web page that says "Double your favorite number is <number>". For example, if you enter 2 into the form, you should then see a page that says "Double your favorite number is 4". Careful about types in your Python code! ## You can assume a user will always enter a number only. from flask import Flask, request app = Flask(__name__) app.debug = True @app.route('/') def hello_to_you(): return 'Hello!' @app.route('/question',methods= ['POST','GET']) def enter_data(): s = """<!DOCTYPE html> <html> <body> <form action="http://localhost:5000/result" method="GET"> Enter your favorite number:<br> <input type="number" name="number" value=""> <br> <input type="submit" value="Submit"> </form> </body> </html>""" return s @app.route('/result',methods = ['POST', 'GET']) def res(): if request.method == 'GET': result = request.args num = result.get('number') double = int(num) *2 new= str(double) #return render_template("result.html",result = result) return str("Double your favorite number is ") + new @app.route('/age',methods= ['POST','GET']) def enter_data2(): s = """<!DOCTYPE html> <html> <body> <h2>Find out how many years until you turn 100!</h2> <form action="http://localhost:5000/result2" method="GET"> Enter your birthday :<br> <input type="date" name="birthday" value=""> <br> Enter the current date :<br> <input type="date" name="current" value=""> <br> <input type="submit" value="Submit"> </form> </body> </html>""" return s @app.route('/result2',methods = ['POST', 'GET']) def res2(): if request.method == 'GET': result = request.args birth = result.get('birthday') year=birth[:4] curr = result.get('current') curryear=curr[:4] new= 100 - (int(curryear) - int(year)) neww=str(new) #return render_template("result.html",result = result) return "<b>" + str("You will be 100 in ") + "</b> <i>" + neww + "</i>" "<b>" + str(" years.") + "</b>" if __name__ == '__main__': app.run() ## [PROBLEM 2] ## Come up with your own interactive data exchange that you want to see happen dynamically in the Flask application, and build it into the above code for a Flask application. It should: # - not be an exact repeat of something you did in class, but it can be similar # - should include an HTML form (of any kind: text entry, radio button, checkbox... feel free to try out whatever you want) # - should, on submission of data to the HTML form, show new data that depends upon the data entered into the submission form (text entered, radio button selected, etc). So if a user has to enter a number, it should do an operation on that number. If a user has to select a radio button representing a song name, it should do a search for that song in an API. # You should feel free to be creative and do something fun for you -- # And use this opportunity to make sure you understand these steps: if you think going slowly and carefully writing out steps for a simpler data transaction, like Problem 1, will help build your understanding, you should definitely try that! # You can assume that a user will give you the type of input/response you expect in your form; you do not need to handle errors or user confusion. (e.g. if your form asks for a name, you can assume a user will type a reasonable name; if your form asks for a number, you can assume a user will type a reasonable number; if your form asks the user to select a checkbox, you can assume they will do that.) #done
class TreeNode: def __init__(self,x): self.val=x self.left=None self.right=None class solution: def treedepth(self,root): if root==None: return None: if not root.left and not root.right: depthOfTree=1 return depthOfTree LdepthOfTree = self.treedepth(root.left) RdepthOfTree = self.treedepth(root.right) depthOfTree = max(LdepthOfTree,RdepthOfTree) return depthOfTree
import pdb class Listnode: def __init__(self,x=None): self.val=x self.next=None class Solution: def printKthNode(self,pnode,k): if pnode==None: return None if k<=0: return False phead=pnode phead_slow=pnode for i in range(0,k): if phead!=None: phead=phead.next else: return None while phead!=None and phead_slow!=None: phead=phead.next phead_slow=phead_slow.next return phead_slow node1=Listnode(10) node2=Listnode(11) node3=Listnode(12) node1.next=node2 node2.next=node3 s=Solution() print(s.printKthNode(node1,2).val)
import pdb def replaceblanks(str): if str==None: return None strlength = len(str) numberofblanks = 0 for i in range(strlength): if str[i]==' ': numberofblanks+=1 newlength = strlength+numberofblanks*2 newstr = [None]*newlength ptr_str = strlength-1 new_ptr_str = newlength-1 for i in range(0,strlength): if str[ptr_str]!=' ': newstr[new_ptr_str] = str[ptr_str] ptr_str-=1 new_ptr_str-=1 else: newstr[new_ptr_str]='0' newstr[new_ptr_str-1]='2' newstr[new_ptr_str-2]='%' ptr_str-=1 new_ptr_str-=1 new_ptr_str-=1 new_ptr_str-=1 return newstr if __name__=="__main__": str = 'we are happy' newstr = replaceblanks(str) print(newstr)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {integer[]} result = [] def preorderTraversal(self, root): self.result = [] if root is not None: self.result.append(root.val) if root.left is not None: self.Traverse(root.left) if root.right is not None: self.Traverse(root.right) return self.result def Traverse(self, node): self.result.append(node.val) if node.left is not None: self.Traverse(node.left) if node.right is not None: self.Traverse(node.right)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ queue = [(root, 1)] result_list = [] for node, level in queue: if node: if len(result_list) < level: result_list.insert(0, []) result_list[-level].append(node.val) if node.left: queue.append((node.left, level + 1)) if node.right: queue.append((node.right, level + 1)) return result_list
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return None self.pre_order = [] self.pre_travel(root) for idx in xrange(len(self.pre_order) - 1): self.pre_order[idx].right = self.pre_order[idx + 1] self.pre_order[idx].left = None self.pre_order[-1].right = None root = self.pre_order[0] def pre_travel(self, root): if not root: return None else: self.pre_order.append(root) self.pre_travel(root.left) self.pre_travel(root.right)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l1_num = [] while l1: l1_num.insert(0, l1.val) l1 = l1.next l2_num = [] while l2: l2_num.insert(0, l2.val) l2 = l2.next if len(l1_num) < len(l2_num): l1_num, l2_num = l2_num, l1_num c_in = 0 length = len(l2_num) res = [] for idx in xrange(length): two_sum = l1_num[idx] + l2_num[idx] + c_in res.append(two_sum % 10) c_in = 1 if two_sum > 9 else 0 while len(l1_num) > length: two_sum = l1_num[length] + c_in res.append(two_sum % 10) c_in = 1 if two_sum > 9 else 0 length += 1 else: if c_in: res.append(c_in) node_list = [ListNode(x) for x in res[::-1]] for idx in xrange(len(node_list) - 1): node_list[idx].next = node_list[idx + 1] return node_list[0]
max_num = 26 # Caesar cipher implementation def caesar_cipher(s, key): # key = int(input()) # Get the cipher shift key # if key < 1 or key > max_num: # Key should be in range of the alphabets # exit(0) # Exit program if out of range ciphered_string = '' # String to store encrypted result for hieroglyph in s: # Only letters will be encrypted. Numbers and other symbols stay in the original form if hieroglyph.isalpha(): # Check if letter is alphabet hold_shift = ord(hieroglyph) # Get ordinal value of letter hold_shift += key # Shift value by the key # Check if letter is uppercase and get ordinal value if hieroglyph.isupper(): if hold_shift < ord('A'): hold_shift += max_num elif hold_shift > ord('Z'): hold_shift -= max_num # Check if letter is lower case and get ordinal value elif hieroglyph.islower(): if hold_shift < ord('a'): hold_shift += max_num elif hold_shift > ord('z'): hold_shift -= max_num ciphered_string += chr(hold_shift) # Put character in encrypted string else: ciphered_string += hieroglyph # If position value is not alphabet, return original value return ciphered_string # Return encrypted string
import random import string lower = string.ascii_lowercase upper = string.ascii_uppercase random.seed(1) def caesar_cipher(message, shift=random.randint(1, 26)): """A Caesar or shift cipher shifts each letter of a message a number of positions in the alphabet. Use negative shift for left shifts and positive for right shifts.""" encrypted_message = "" for ch in message: if ch in lower: encrypted_message += lower[(lower.index(ch) + shift) % len(lower)] elif ch in upper: encrypted_message += upper[(upper.index(ch) + shift) % len(upper)] else: encrypted_message += ch return encrypted_message def rot13(message): return caesar_cipher(message, 13) def vigenere_cipher(message: str, keyword="a") -> str: encrypted_message = "" for i, ch in enumerate(message): key = keyword[i % len(keyword)].lower() encrypted_message += caesar_cipher(ch, lower.index(key)) return encrypted_message def vigenere_decipher(message: str, keyword: str = "a") -> str: decrypted_message = "" for i, ch in enumerate(message): key = keyword[i % len(keyword)].lower() decrypted_message += caesar_cipher(ch, -lower.index(key)) return decrypted_message def alberti_cipher(message, index="a", min_characters_before_change=10, max_characters_before_change=20): """In the Alberti Cipher there are two disks, one with upper case ordered letter and the other one with lowercase randomly shuffled letters. Sender and receiver should have the same lowercase disk in order to use it. A letter is selected as index The first capital letter indicates """ encrypted_message = "" lower_circle = "zxvtrpnljhfdbacegikmoqsuwy" assert len(upper) == len(lower_circle) message_index = 0 disk_changes = 0 while message_index < len(message): key = random.choice(upper) encrypted_message += key disk_changes += 1 for _ in range(random.randint(min_characters_before_change, max_characters_before_change)): if message.lower()[message_index] in lower_circle: encrypted_message += lower_circle[ upper.index(message[message_index].upper()) - (upper.index(key) - lower_circle.index(index)) % len( lower_circle)] else: encrypted_message += message[message_index] message_index += 1 if message_index >= len(message): break return encrypted_message def alberti_decipher(message, index="a"): """A function that decipher a message that used an Alberti cipher""" decrypted_message = "" upper_circle = upper lower_circle = "zxvtrpnljhfdbacegikmoqsuwy" for ch in message: if ch in upper_circle: if upper_circle.index(ch) < lower_circle.index(index): lower_circle = (lower_circle[lower_circle.index(index) - upper_circle.index(ch):] + lower_circle[:(lower_circle.index(index) - upper_circle.index(ch) + 26) % len(upper)]) elif upper_circle.index(ch) > lower_circle.index(index): lower_circle = lower_circle[(lower_circle.index(index) + len(upper) - upper_circle.index(ch)) % len( upper):] + lower_circle[ :(lower_circle.index(index) + len(upper) - upper_circle.index(ch)) % len(upper)] elif ch in lower_circle: decrypted_message += upper_circle[lower_circle.index(ch)].lower() else: decrypted_message += ch return decrypted_message
class Square: def __init__(self, a): if a > 0: self._a = a @property def AreaSquare(self): return self._a ** 2 @AreaSquare.setter def AreaSquare(self, value): if value >= 0: self._a = value else: raise ValueError("a must be >= 0") a = int(input()) Rec = Square(a) Rec.AreaSquare = a print(Rec.AreaSquare)
#!/usr/bin/python #-*- coding:utf-8 -*- # 计算计算机的mac地址 macaddr = 'ac:bc:32:d6:37:b5' prefix_mac = macaddr[:-3] last_two = macaddr[-2:] plus_one = int(last_two, 16) + 1 if plus_one in range(10): new_last_two = hex(plus_one)[2:] new_last_two = '0' + new_last_two else: new_last_two = hex(plus_one)[2:] if len(new_last_two) == 1: new_last_two = '0' + new_last_two new_mac = prefix_mac + ':' + new_last_two print new_mac.upper()
#!/usr/bin/python #-*- coding:utf-8 -*- # for i in [i**2 for i in range(1,11)]: # print i, with open('tmp.txt') as fd: while True: line = fd.readline() if not line: break print line,
#!/usr/bin/python #-*- coding:utf-8 -*- def fun(): sth = raw_input("Please input somthing: ") try: if type(int(sth)) == type(1): print "%s is a number" %sth except ValueError: print "%s is not a number" %sth fun()
import concurrent import concurrent.futures import itertools import json from string import ascii_lowercase def add_word_len(): """Adds a list to the start of each combo with the value at i representing the index at which the last word of i + 3 length appeared. Used in order to limit the bot to words of x length.""" with open("combo_dict_final.json", "r") as dict_file: words_dict = json.load(dict_file) for vowel in words_dict: lens = [1 for _ in range(3, 21)] current_len = 3 index = 0 words_dict[vowel] = sorted(words_dict[vowel], key=len) for word in words_dict[vowel]: while current_len < len(word) < 20: current_len += 1 index += 1 for i in range(current_len, 21): lens[i - 3] = index words_dict[vowel] = [lens, words_dict[vowel]] with open("combo_dict_final.json", "w") as dict_file: json.dump(words_dict, dict_file) def get_words(): """Returns a list of all words the bot will use""" # Open all words files with open("../best_words.txt", "r") as words_file: words_dict = words_file.read().split("\n") with open("../words-2.txt", "r") as words_file: words_2 = words_file.read().split("\n") with open("../words-3.txt", "r") as words_file: words_3 = words_file.read().split("\n") # Add to the original word list the words from the other lists, without duplicates for word in words_2 + words_3: if word not in words_dict: words_dict.append(word) return list(set([word.strip() for word in words_dict])) def load_words(): """Load the indexed words into a dictionary""" with open("combo_dict_final.json", "r") as words_dict_file: words_dict = json.load(words_dict_file) return words_dict def words_to_dict(): """Make a dictionary (json file) with 2 and 3 letter combinations as keys and a list of words they appear in as values (in order to make word selecting be O(1))""" # INDEX ALL 2 LETTER COMBINATIONS FIRST words_dict = {} # Load the words words = get_words() # load_words() # Generate list of all 2 letter combos two_letters = ["".join(i) for i in itertools.product(ascii_lowercase, repeat=2)] future_dicts = [] # Index the words inside the combos with concurrent.futures.ThreadPoolExecutor() as executor: for combo in two_letters: future_dicts.append(executor.submit(index_combo, combo, words)) print(combo) # Add indexed items to dict for future_dict in concurrent.futures.as_completed(future_dicts): words_dict.update(future_dict.result()) # Save the dictionary in a file with open("combo_dict.json", "w") as combo_file: json.dump(words_dict, combo_file, indent=4) # THEN USE THOSE INDEXED COMBINATIONS TO INDEX THE 3 LETTERS # Generate list of all 3 letter combos three_letters = ["".join(i) for i in itertools.product(ascii_lowercase, repeat=3)] future_dicts = [] # Index the words inside the combos with concurrent.futures.ThreadPoolExecutor() as executor: for combo in three_letters: # In order to reduce run time. "abc" will only appear in words which "bc" and "ab" appears in matching_words = words_dict[combo[:2]] + words_dict[combo[1:]] future_dicts.append(executor.submit(index_combo, combo, matching_words)) print(combo) # Add indexed items to dict for future_dict in concurrent.futures.as_completed(future_dicts): words_dict.update(future_dict.result()) update_word_dict(words_dict) def update_word_dict(words_dict): """Saves the combo dictionary in a file""" with open("combo_dict_final.json", "w") as combo_file: json.dump(words_dict, combo_file, indent=4) def index_combo(combo, words): """Get a combo and list of all words and return a dictionary with the combo as key and list of all words the combo appears in as a value""" # Sort the words by length, in order to make further indexing by length easier. words = sorted(words, key=len) return {combo: list(set([word for word in words if combo in word]))}
# Course: CS 30 # Period: 1 # Date created: 20/02/05 # Date last modified: 20/02/07 # Name: Ruiting Chen # Description: Printing name in a sentence name = "Ruiting" print("Hello " + name + ", would you like to learn some Python today?")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 22 15:56:48 2020 @author: cartervandemoore """ #create an initial version of a TextModel class, #which will serve as a blueprint for objects that model a body of text #returns a list of words after 'cleaning' out a string txt def clean_text(txt): txt=txt.lower() txt=txt.replace('.', '') txt=txt.replace(',', '') txt=txt.replace('?', '') txt=txt.replace('!', '') txt=txt.replace(';', '') txt=txt.replace(':', '') txt=txt.replace('"', '') lst_ans=txt.split(" ") return lst_ans class TextModel(): #Constructor def __init__(self, model_name): self.name=model_name self.words={} self.word_lengths={} def __repr__(self): """Return a string representation of the TextModel.""" s = 'text model name: ' + self.name + '\n' s += ' number of words: ' + str(len(self.words)) + '\n' s += ' number of word lengths: ' + str(len(self.word_lengths)) + '\n' return s def add_string(self, s): """Analyzes the string txt and adds its pieces to all of the dictionaries in this text model.""" word_list=clean_text(s) for w in word_list: if w not in self.words: self.words[w]=1 else: self.words[w]+=1 if len(w) not in self.word_lengths: self.word_lengths[len(w)]=1 else: self.word_lengths[len(w)]+=1 # Add code to update other feature dictionaries. #adds all of the text in the file identified by filename to the model def add_file(self, filename): f = open(filename, 'r', encoding='utf8', errors='ignore') text = f.read() # read it all in at once! f.close() self.add_string(text) #saves the TextModel object self by writing its various #feature dictionaries to files def save_model(self): d = self.words # Create a sample dictionary. f = open(self.name + '_' + 'words', 'w') # Open file for writing. f.write(str(d)) # Writes the dictionary to the file. f.close() # Close the file. d1 = self.word_lengths # Create a sample dictionary. f = open(self.name + '_' + 'word_lengths', 'w') # Open file for writing. f.write(str(d1)) # Writes the dictionary to the file. f.close() # Close the file. #reads the stored dictionaries for the called TextModel object from their #files and assigns them to the attributes of the called TextModel def read_model(self): f = open(self.name + '_' + 'words', 'r') # Open for reading. d_str = f.read() # Read in a string that represents a dict. f.close() self.words = dict(eval(d_str)) # Convert the string to a dictionary. print("Inside the newly-read dictionary, d, we have:") print(self.words) f = open(self.name + '_' + 'word_lengths', 'r') # Open for reading. d1_str = f.read() # Read in a string that represents a dict. f.close() self.word_lengths = dict(eval(d1_str)) # Convert the string to a dictionary. print("Inside the newly-read dictionary, d, we have:") print(self.word_lengths)
"""Contains constants used to describe a sudoku game.""" from itertools import product def cross(A, B): """Cross product of elements in A and elements in B.""" return ["".join(item)for item in product(A, B)] # Definition of rows and columns in the sudoku. ROWS = 'ABCDEFGHI' COLS = '123456789' # Boxes in the sodoku grid BOXES = cross(ROWS, COLS) # Units are related cells that contain a set of 9 numbers. ROW_UNITS = [cross(r, COLS) for r in ROWS] COL_UNITS = [cross(ROWS, c) for c in COLS] DIAG_UNITS = [ [item for sublist in (cross(r, c) for r, c in zip(ROWS, COLS)) for item in sublist], [item for sublist in (cross(r, c) for r, c in zip(ROWS, COLS[::-1])) for item in sublist] ] SQUARE_UNITS = [ cross(rs, cs) for rs, cs in product(('ABC', 'DEF', 'GHI'), ('123', '456', '789')) ] UNITLIST = ROW_UNITS + COL_UNITS + SQUARE_UNITS + DIAG_UNITS # Peers are all associated cells that related to a certain cell. PEERS = {box: set( [peer for unit in UNITLIST for peer in unit if box in unit if peer != box]) for box in BOXES}
#!/usr/bin/env python """ Calculates new grade based on input value """ import pandas as pd def grade(grade_file, syllabus, new_type, new_grade): """ Shows the current grade and expected grade based on the csv file given. Parameters ---------- grade_file (str): the name of the grade file syllabus (str): the name of the syllabus file new_type (str): the type of the new grade to be added new_grade (int): the percentage of the new grade to be added """ data = pd.read_csv(grade_file) syll_data = pd.read_csv(syllabus) print(f"Previous Grade: {calculate_grade(data, syll_data)}") row_list = ["Possible Grade", new_type, new_grade] row = {i: j for (i, j) in zip(list(data), row_list)} data = data.append(row, ignore_index=True) print(f"New Grade: {calculate_grade(data, syll_data)}") def calculate_grade(grade_df, syllabus_df): """ Calculates the final grade based on the breakdowns given in the syllabus. Parameters ---------- grade_df (DataFrame): Pandas DataFrame with grade information. syllabus_df (DataFrame): Pandas DataFrame with grade breakdown from syllabus. """ grade_means = grade_df.groupby("Type").mean() df = grade_means.join(syllabus_df.set_index("Type"), on="Type") df = df.assign(Raw=df["Grade"] * df["Percentage"]/100) return df["Raw"].sum()
LOW_BOUND = 1 #bounds constants that represent the inclusive min and max values that the secret number could be HIGH_BOUND = 100 #the program is completly responsive to changing these constants low = LOW_BOUND #initialize the low and high end points to the bounds, since the first guess must consider the entire range high = HIGH_BOUND print('Please think of a number between {} and {}'.format(LOW_BOUND, HIGH_BOUND)) while True: guess = (low+high)//2 #guess the midpoint between the current low and high end points print('Is your secret number {}?'.format(guess)) #display the guess to the user answer = input("Enter 'h' if my guess is too high, 'l' if too low, or 'c' if I am correct: ") #prompt the user for feedback if answer == 'l': #if the computer guess was too low low = guess elif answer == 'h': #if the computer guess was too high high = guess elif answer == 'c': #if the computer guess was correct print('Game over, your secret number was: {}. Guessed in {} tries.'.format(guess)) break #break out of while loop (only break case) else: #if the user feedback answer was not one of the 3 valid letters print("Please enter the letter 'l', 'h', or 'c'.") #display an error message continue #continue to next iteration, keeping same low and high bounds
import unittest class Submarino(object): def coordenada(self, comando=''): return '2 3 -2 SUL' class SubmarinoTest(unittest.TestCase): def testCoordenada(self): sub = Submarino() self.assertEqual('2 3 -2 SUL', sub.coordenada("RMMLMMMDDLL")) sub = Submarino() self.assertEqual('-1 2 0 NORTE', sub.coordenada("LMRDDMMUU")) # def testPosicaoInicial(self): # sub = Submarino() # self.assertEqual('0 0 0 NORTE', sub.coordenada()) if __name__ == '__main__': unittest.main()
#continue: continues with next iteration of loop. for num in range(2,10): if num % 2 == 0: print("Found an even number", num) continue print("Found a odd number", num)
#Default argument vlaues:specify default value for one or more arguments. #creates function with fewer arguments i = 5 def f(arg=i): arg=6 print(arg) f() #in keyword: this tests whether or not a sequence contains a certain value. """ def ask_ok(prompt, retries=4, reminder='Please try again!'): while True: ok = input(prompt) if ok in ('y','ye','yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries -1 if retries < 0: raise ValueError('invalid your response') print(reminder) """
#for statement calls iter() on container object """for element in [1, 2, 3]: print(element) for key in {'one':1, 'two':2}: print(key) for char in "123": print(char)""" #next() method: accesses elements in container one at a time #When there are no more elements, __next__() raises StopIteration exception which tells the for loop to terminate. """s = 'abc' it = iter(s) print(next(it)) #'a' print(next(it)) #'b' print(next(it)) #c print(next(it))""" #When there are no more elements, __next__() raises a StopIteration exception which tells the for loop to terminate. class Reverse: def __init__(self, data): #often 1st argument of a method is called self self.data = data self.index = len(data) def __iter__(self):#Iterator for looping over a sequence backwards return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] rev = Reverse('spam') print(iter(rev)) for char in rev: print(char)
#count(x): return the number of times x appears in the list #index(x, start): return zero-based index in the list of item x #reverse(): reverse the elements of the list #append(): add an item to the end of the list #sort(): sort the item of the list #pop(i): remove the item at given position in the list and return it. if no index is specified pop removes last item fruits = ['orange', 'apple', 'pear,', 'banana', 'kiwi', 'apple', 'banana'] #print(fruits.count('apple')) print(fruits.index('banana')) print(fruits.index('banana', 4))#find next banana starting a position 4 fruits.reverse() print(fruits) fruits.append('grape') print(fruits) fruits.sort() print(fruits) fruits.pop() print(fruits)
word = 'Python' print(word[0]) # character in position 0 # -0 is same as 0 """ print(word[5]) # character in position 5 print(word[-1]) # last character print(word[-2]) # second last character # indexing, slicing(to obtain substring ) print(word[0:2]) # charaters from position 0(included) to 2(excluded) print(word[2:5]) # charaters from position 2(included) to 5(excluded) print(word[:2]) # character from the beginning to position 2(excluded) print(word[4:]) # character from position 4(included) to end print(word[-2:]) # character from the second-last (included) to the end """
def carreCor(n) : return([i**2 for i in range(1,n+1)]) def carre(n) : l = [] for i in range(1,n+1) : l.append(i*i) return l def carreRec(n) : if(n == 1) : return [1] else : return carreRec(n-1) + [n*n] def carCub(n) : #Revient à chercher les puissances de 6 bons = [] for i in range(n): bons = bons + [i**6] return bons print("carre cor",carreCor(5)) print("carre", carre(5)) print("carre rec",carreRec(5)) print("carre cub",carCub(5))
""" returns a dictionary with the following format: create_dict(N) {1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49, 8:64, 9:81, …, N:N^2}. """ def create_dict(n): return {item: item ** 2 for item in range(1, n+1)} print(create_dict(1000))
""" Counts number of lines in the file. """ file_name = 'textfile.txt' def count_lines_number(file_name): with open(file_name) as file: return len(file.readlines()) print(count_lines_number(file_name))
""" This function prints a sentence in a reverse order. Input example: This is a test sentense Output example: esnetnes tset a si sihT """ def print_reverse(sentence): return sentence[::-1] print(print_reverse('This is a test sentense'))
import math from functools import reduce import operator """ The difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def sumsquarediff(): sumofsq = 0 sqofsum = 0 sqofsumfinal = 0 y = 0 for x in range(1,101): print("Currently on %s^2 = %s" % (x, sumofsq)) print("Adding %s to %s" % (x, sqofsum)) y = (x*x) sumofsq += y sqofsum += x sqofsumfinal = sqofsum*sqofsum print("%s^2 = %s" % (sqofsum, sqofsumfinal)) result = (sqofsumfinal - sumofsq) print (result) sumsquarediff()
name = "cong1"; name2 = "cong"; age = 25; if name=="cong" and age==25: print("I'm %s. I %d years old." % (name,age)); arrayName = ["cong", "thanh"]; #in if name in arrayName: print("your name is %s" % name) elif age == 255: print("I'm %d" % age) else: print("wellcome to python 3") if name is name2: print('true') else: print('false'); a = 11; b = 3; print(a // b);
import math radius = float(input('请输入圆的半径:')) perimeter = 2*math.pi*radius area = math.pi*radius*radius print('周长:%.2f'%perimeter) print('面积:%.2f'%area)
def valid(maze,x,y): if (x>=0 and x<len(maze) and y>=0 and y<len(maze[0]) and maze[x][y]==1): return True else: return False # 移步函数实现 def walk(maze,x,y): # 如果位置是迷宫的出口,说明成功走出迷宫 if(x==3 and y==3): # print("successful!") return True # 递归主体实现 if valid(maze,x,y): # print(x,y) maze[x][y]=2 # 做标记,防止折回 # 针对四个方向依次试探,如果失败,撤销一步 if not walk(maze,x-1,y): maze[x][y]=1 elif not walk(maze,x,y-1): maze[x][y]=1 elif not walk(maze,x+1,y): maze[x][y]=1 elif not walk(maze,x,y+1): maze[x][y]=1 else: return False # 无路可走说明,没有解 return True maze=[[1,1,0,0,0], [0,1,1,0,0], [0,0,1,1,0], [0,0,0,1,1]] print(walk(maze,0,0))
class TreeNode: def __init__(self, item=None, left=None, right=None): self.item = item self.left = left self.right = right class TreeNodeLink: def __init__(self, item=None, left=None, right=None, next = None): self.item = item self.left = left self.right = right self.next = next B = TreeNode('B') C = TreeNode('C') A = TreeNode('A', B, C) # 节点数量 def count_node(root): if root is None: return 0 return count_node(root.left) + count_node(root.right) + 1 # 反转 def reverse(root): if root is None: return None root.left, root.right = root.right, root.left reverse(root.left) reverse(root.right) return root # 将每一层的节点链接起来 def link_node(root: TreeNodeLink): if root is None or root.left is None: return root link_two_node(root.left, root.right) return root def link_two_node(node1: 'TreeNodeLink', node2: 'TreeNodeLink'): if node1 is None: return node1.next = node2 link_two_node(node1.left, node1.right) link_two_node(node2.left, node2.right) link_two_node(node1.right, node2.left) # 将二叉树展开为链表 # 以下流程: # 1、将 root 的左子树和右子树拉平。 # 2、将 root 的右子树接到左子树下方,然后将整个左子树作为右子树。 def tree_to_chain(root): if root is None: return tree_to_chain(root.left) tree_to_chain(root.right) left = root.left right = root.right root.left = None root.right = left p = root while p.right is not None: p = p.right p.right = right link_node(A) tree_to_chain(A) print(count_node(reverse(A)))
class Solution: def Fibonacci(self, n): queue = [0, 1, 1] for i in range(3, n): queue.append(queue[i-1]+queue[i-2]) return queue[n-1] class Solution2: def Fibonacci2(self, n): if n == 0: return 0 elif n == 1: return 1 cur1 = 0 cur2 = 1 for i in range(n-2): substitute = cur1 cur1 = cur2 cur2 = substitute + cur1 return cur2 a = Solution2() print(a.Fibonacci2(9))
import math import matplotlib.pyplot as plt import numpy as np # сетка по x from mat_mod.task_3.progonka import method_progonki n = 200 l = 2.0 step_h = l / n x = np.arange(0.0, l, step_h) # сетка по времени T = 0.03 step_t = 0.001 # граничные условия mu_1 = 0 mu_2 = 0 A = [step_t / (step_h ** 2)] * (n - 2) B = [step_t / (step_h ** 2)] * (n - 2) C = [(2 * step_t / (step_h ** 2)) + 1] * (n - 2) def phi(x): return math.sin((5 * math.pi / 2) * x) y_start = [] for i in x: y_start.append(phi(i)) def get_f_from_y(y): return y[1:-1] y_next = y_start y_for_anim = [y_next] for i in range(0, int(T / step_t)): F = get_f_from_y(y_next) y_next = method_progonki(n=n, a=A, b=B, c=C, f=F, mu1_local=mu_1, mu2_local=mu_2) y_for_anim.append(y_next) plt.plot(x, y_start, 'ro', label='func_min') plt.plot(x, y_next) plt.title("Newspaper task decision") plt.legend() plt.show() print("done") # Animation fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) ax1.set_xlim(-1, 3) ax1.set_ylim(-1, 1) for i in range(0, int(T / step_t)): ax1.plot(x, y_for_anim[i]) plt.pause(0.001) while True: pass
# quiz project using class and OOP way question_data = [ {"text": "A slug's blood is green.", "answer": "True"}, {"text": "The loudest animal is the African Elephant.", "answer": "False"}, {"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"}, {"text": "The total surface area of a human lungs is the size of a football pitch.", "answer": "True"}, {"text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.", "answer": "True"}, {"text": "In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral.", "answer": "False"}, {"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"}, {"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"}, {"text": "Google was originally called 'Backrub'.", "answer": "True"}, {"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"}, {"text": "No piece of square dry paper can be folded in half more than 7 times.", "answer": "False"}, {"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"} ] class Question: def __init__(self, q_text, q_answer): self.text = q_text self.answer = q_answer # def __repr__(self): # return self.text class QuizBrain: def __init__(self, q_list): self.question_number = 0 self.question_list = q_list self.score = 0 def still_has_question(self): return self.question_number < len(self.question_list) def next_question(self): current_question = self.question_list[self.question_number] self.question_number += 1 user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/Flase): ") self.check_answer(user_answer, current_question.answer) def check_answer(self, user_answer, correct_answer): if user_answer.lower() == correct_answer.lower(): print("You got it right") self.score += 1 else: print("That's wrong") print(f"The correct answer is {correct_answer}") print(f"Your current score is :{self.score}/{self.question_number} \n") question_bank = [] for question in question_data: question_text = question["text"] question_answer = question["answer"] new_question = Question(question_text, question_answer) question_bank.append(new_question) quiz = QuizBrain(question_bank) while quiz.still_has_question(): quiz.next_question() print("You've completed the quiz") print(f"your final socre was {quiz.score}/{quiz.question_number}")
# file name: nato_phonetic_alphabet.txt import pandas as pd data = pd.read_csv('nato_phonetic_alphabet.csv') alpha_dict = {row.letter: row.code for (index, row) in data.iterrows()} input_word = input("type your name to convert: ").upper() input_list = list(input_word) new_dict = {item:alpha_dict[item] for item in input_list} print(new_dict)
import random #welcome note print("Welcome to the Number Guessing Game!") print("I am thinking of a number between 1 and 100") difficulty = input("Choose a difficulty. type 'easy' or 'hard: ") if difficulty == 'easy': chance = 10 elif difficulty =='hard': chance = 5 else: print("incorrent input, rerun code") #select number form 1 to 100 and put in varible number number = random.randint(1,100) for i in range(chance): guess = int(input("Make a guess: ")) if guess > number: print("too high") elif guess < number: print("too low") else: print(f"you won, the number is {number}") break if guess != number: print(f"you lost, the number is {number}")
#function with output """ def format_name(f_name, l_name): ff_name = f_name.title() fl_name = l_name.title() return f"{ff_name} {fl_name}" f_name = input("Enter your first name: ") l_name = input("Enter your last name: ") name = format_name(f_name, l_name) print(f"Formated name is {name}") """ #function with multiple return """ def format_name(f_name, l_name): if f_name=="" or l_name=="": return "You did't provide valid input" #early return ff_name = f_name.title() fl_name = l_name.title() return f"Result: {ff_name} {fl_name}" #result return print(format_name(input("Your first name: "), input("Your last name: "))) """ #Check how many days in a month of year """ month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def days_in_month(year, month): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: leap_year = True else: leap_year =False else: leap_year = True else: leap_year = False if leap_year==True : return 29 else: return month_day[month] print(f'Result: {days_in_month(int(input("Enter year? ")), int(input("Enter month? ")))}') """ #Docstring #Calulator ascii_art = """ .----------------. .----------------. .----------------. .----------------. | .--------------. || .--------------. || .--------------. || .--------------. | | | ______ | || | __ | || | _____ | || | ______ | | | | .' ___ | | || | / \ | || | |_ _| | || | .' ___ | | | | | / .' \_| | || | / /\ \ | || | | | | || | / .' \_| | | | | | | | || | / ____ \ | || | | | _ | || | | | | | | | \ `.___.'\ | || | _/ / \ \_ | || | _| |__/ | | || | \ `.___.'\ | | | | `._____.' | || ||____| |____|| || | |________| | || | `._____.' | | | | | || | | || | | || | | | | '--------------' || '--------------' || '--------------' || '--------------' | '----------------' '----------------' '----------------' '----------------' """ print(ascii_art) def evaluate(f_number, operator, s_number): concat = f_number+operator+s_number return eval(concat) print(evaluate(input("Enter first no? "),input("Enter operator? "), input("Enter second no? ")))
# Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. # https://leetcode.com/explore/interview/card/google/60/linked-list-5/3065/ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: """ Works. My solution. """ def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: prev_node=ListNode(None,None ) head = prev_node while (l1 or l2): if l1 and l2: #they both exist: I m assuminf that all node have values ls= [l1.val] +[l2.val ] min_idx= ls.index( min(ls) ) just_node= ListNode( min(ls), None ) prev_node.next = just_node prev_node= just_node if min_idx ==0 : l1=l1.next else: l2=l2.next elif l1: just_node= ListNode( l1.val, None ) prev_node.next = just_node prev_node = just_node l1=l1.next else: just_node= ListNode( l2.val , None ) prev_node.next = just_node prev_node=just_node l2=l2.next return head.next # Smarter Solution class Solution2: def mergeTwoLists(self, l1, l2): # maintain an unchanging reference to node ahead of the return node. prehead = ListNode(-1) prev = prehead while l1 and l2: if l1.val <= l2.val: prev.next = l1 l1 = l1.next else: prev.next = l2 l2 = l2.next prev = prev.next # At least one of l1 and l2 can still have nodes at this point, so connect # the non-null list to the end of the merged list. prev.next = l1 if l1 is not None else l2 return prehead.next
# || Various BFS running at the same time || # You are given an m x n grid rooms initialized with these three possible values. # -1 A wall or an obstacle. # 0 A gate. # INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. # Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.TimeoutError # https://leetcode.com/problems/walls-and-gates/ from collections import deque class Solution: def wallsAndGates(self, rooms: List[List[int]]) -> None: """ Works. My Brute Force Approach. There is a a better approach Instead Do multiple Bfs starting from the doors. look solution2 Do not return anything, modify rooms in-place instead. """ def isValid (row, col, rooms): n_rows = len(rooms) n_columns = len(rooms[0]) if row >=0 and col >=0 and row < n_rows and col < n_columns and rooms[row][col] != -1 : return True else : return False def bfs(row, col, rooms): """ Since is a grapg ned to add set to keep track of nodes, """ queue =deque() seen=set() queue.append( (row, col) ) seen.add((row, col)) distance = 0 while(queue): curr_size =len(queue) for i in range(curr_size) : if rooms[ (queue[0])[0] ] [(queue[0])[1] ] == 0: return distance row=(queue[0])[0] col=(queue[0])[1] if isValid(row-1,col, rooms ) and (row-1,col ) not in seen : queue.append( (row-1,col) ) seen.add( (row-1,col) ) if isValid(row+1,col, rooms ) and (row+1, col) not in seen : queue.append( (row+1,col) ) seen.add( (row+1,col) ) if isValid(row,col+1, rooms ) and (row, col+1) not in seen : queue.append( (row,col+1) ) seen.add( (row,col+1) ) if isValid(row,col-1, rooms ) and (row, col-1) not in seen : queue.append( (row,col-1) ) seen.add( (row,col-1) ) queue.popleft() distance +=1 return -1 #MAIN n_columns =len(rooms[0]) n_rows =len(rooms) inf= 2147483647 for row in range(n_rows) : for col in range(n_columns): if rooms[row][col] == 0 or rooms[row][col] == -1: pass else: result = bfs(row, col, rooms) rooms[row][col] = inf if result ==-1 else result class Solution2: """ works. best solution until know 1) find all doors 2) Do simultaneous BFS for all doors and change values as I go along. """ door=0 empty= 2147483647 obstacle = -1 def wallsAndGates(self, rooms: List[List[int]]) -> None: """ Do not return anything, modify rooms in-place instead. """ def isValid (row, col, rooms): n_rows, n_cols =len(rooms), len(rooms[0]) if row >=0 and col>=0 and row <n_rows and col < n_cols and rooms[row][col] ==self.empty: return True else : return False return queue =deque() #Get all doors and place in n_rows = len(rooms) n_cols = len(rooms[0]) for row in range(n_rows) : for col in range(n_cols) : if rooms[row][col] == self.door: queue.append((row, col)) # Simultaneous BFS while(queue): curr= queue[0] # I want to append to queue the valid neighbors AND change val for r, c in [(curr[0]+1,curr[1]), (curr[0]-1,curr[1]), (curr[0],curr[1]+1), (curr[0],curr[1]-1)]: if isValid(r,c, rooms): queue.append(((r,c))) rooms[r][c] = rooms[curr[0]] [curr[1]] +1 # whatever the previous was +1 queue.popleft()
# [2, 5, -3, 1] # def contiguous(array): # found = [] # sum = 0 # for i in array: # if sum + i < 0: # found.append(sum) # sum = 0 # else: # sum += i # found.append(sum) # found.append(sum) # return max(found) # print(contiguous([2, 3, -8, -1, 2, 4, -2, 3])) # #get max of arr[0], then if arr_j[1] - max > duration && arr_i[1] - max >duration def time_planner(first_array, second_array, duration): i = 0 shortest_arr = min(first_array, second_array) while i < len(shortest_arr): maximum = max(first_array[i][0], second_array[i][0]) if first_array[i][1] - maximum >= duration and second_array[i][1] - maximum >= duration: return [maximum, maximum + duration] i += 1 return [] print(time_planner( [[10, 50], [60, 120], [140, 210]], [[0, 15], [60, 70]], 8)) print(time_planner( [[10, 50], [60, 120], [140, 210]], [[0, 15], [60, 72]], 12)) print(time_planner( [[10, 50], [60, 120], [140, 210]], [[0, 15], [60, 70]], 12))
for age in range(0, 65, 1): if age == 0: print str(age) + ": New born" elif age > 0 and age <= 12: print str(age) + ": Childhood" elif age > 12 and age < 18: print str(age) + ": Adolescence" elif age >= 18 and age <= 59: print str(age) + ": Adulthood" elif age >= 60: print str(age) + ": Senior citizen" else: print "Old age"
#Title: Francesco&Joe Fitness Tracker #Names: Francesco Giacca and Joe Gwynn #Year: CIS 1051 Spring 2021 from datetime import date #function for finding BMR of adult male def maleBmr(weight, height, age):#pounds, inches, years weight = (int(weight) * 6.3) height = (int(height) * 12.9) age = (int(age) * 6.8) calculation = ((66 + weight) + (height) - age) return (round(calculation, 2)) #function for finding female BMR def femaleBmr(weight, height, age):#pounds, inches, years weight = (int(weight) * 4.3) height = (int(height) * 4.7) age = (int(age) * 4.7) calculation = ((655 + weight) + (height) - age) return (round(calculation, 2)) #this function gathers all necessary information from the user def calorieFinder(): weight = int(input("Please enter your weight(pounds): "))#pounds height = int(input("Please enter your height(inches): "))#inches age = int(input("Please enter your age(years): "))#years value = False """ Finding general information about the user """ while not value: gender_choice = input("Please enter if you are a male or female: ")#asks the user for their gender #If male if gender_choice == "male" or gender_choice == "Male": male = maleBmr(weight, height, age) activity_level = int(input("How many days a week do you exercise: ")) #calculates maintenence calories based off of activity level #If activity level is 0 if activity_level == 0: maintenence = int(male * 1.2) final_calories = input("Do you want to lose, gain, or maintain weight?: ") if final_calories == "lose" or final_calories == "Lose": maintenence -= 500 print(maintenence, "is your calories in order to lose weight") value = True if final_calories == "gain" or final_calories == "Gain": maintenence += 500 print(maintenence, "is your calories in order to gain weight") value = True if final_calories == "maintain" or final_calories == "Maintain": print(maintenence, "is your calories in order to maintain weight") value = True #If activity level is 1-2 if activity_level >= 1 and activity_level <= 2: maintenence = int(male * 1.375) final_calories = input("Do you want to lose, gain, or maintain weight?: ") if final_calories == "lose" or final_calories == "Lose": maintenence -= 500 print(maintenence, "is your calories in order to lose weight") value = True if final_calories == "gain" or final_calories == "Gain": maintenence += 500 print(maintenence, "is your calories in order to gain weight") value = True if final_calories == "maintain" or final_calories == "Maintain": print(maintenence, "is your calories in order to maintain weight") value = True #If activity level is 3-5 if activity_level >= 3 and activity_level <=5: maintenence = int(male * 1.55) final_calories = input("Do you want to lose, gain, or maintain weight?: ") if final_calories == "lose" or final_calories == "Lose": maintenence -= 500 print(maintenence, "is your calories in order to lose weight") value = True if final_calories == "gain" or final_calories == "Gain": maintenence += 500 print(maintenence, "is your calories in order to gain weight") value = True if final_calories == "maintain" or final_calories == "Maintain": print(maintenence, "is your calories in order to maintain weight") value = True #If activity level is 6-7 if activity_level >= 6 and activity_level <= 7: maintenence = int(male * 1.725) final_calories = input("Do you want to lose, gain, or maintain weight?: ") if final_calories == "lose" or final_calories == "Lose": maintenence -= 500 print(maintenence, "is your calories in order to lose weight") value = True if final_calories == "gain" or final_calories == "Gain": maintenence += 500 print(maintenence, "is your calories in order to gain weight") value = True if final_calories == "maintain" or final_calories == "Maintain": print(maintenence, "is your calories in order to maintain weight") value = True #If Female if gender_choice == "female" or gender_choice == "Female": female = femaleBmr(weight, height, age) activity_level = int(input("How many days a week do you exercise: ")) #If activity level is 0 if activity_level == 0: maintenence = int(female * 1.2) final_calories = input("Do you want to lose, gain, or maintain weight?: ") if final_calories == "lose" or final_calories == "Lose": maintenence -= 500 print(maintenence, "is your calories in order to lose weight") value = True if final_calories == "gain" or final_calories == "Gain": maintenence += 500 print(maintenence, "is your calories in order to gain weight") value = True if final_calories == "maintain" or final_calories == "Maintain": print(maintenence, "is your calories in order to maintain weight") value = True #If activity level is 1-2 if activity_level >= 1 and activity_level <= 2: maintenence = int(female * 1.375) final_calories = input("Do you want to lose, gain, or maintain weight?: ") if final_calories == "lose" or final_calories == "Lose": maintenence -= 500 print(maintenence, "is your calories in order to lose weight") value = True if final_calories == "gain" or final_calories == "Gain": maintenence += 500 print(maintenence, "is your calories in order to gain weight") value = True if final_calories == "maintain" or final_calories == "Maintain": print(maintenence, "is your calories in order to maintain weight") value = True #If activity level is 3-5 if activity_level >= 3 and activity_level <=5: maintenence = int(female * 1.55) final_calories = input("Do you want to lose, gain, or maintain weight?: ") if final_calories == "lose" or final_calories == "Lose": maintenence -= 500 print(maintenence, "is your calories in order to lose weight") value = True if final_calories == "gain" or final_calories == "Gain": maintenence += 500 print(maintenence, "is your calories in order to gain weight") value = True if final_calories == "maintain" or final_calories == "Maintain": print(maintenence, "is your calories in order to maintain weight") value = True #If activity level is 6-7 if activity_level >= 6 and activity_level <= 7: maintenence = int(female * 1.725) final_calories = input("Do you want to lose, gain, or maintain weight?: ") if final_calories == "lose" or final_calories == "Lose": maintenence -= 500 print(maintenence, "is your calories in order to lose weight") value = True if final_calories == "gain" or final_calories == "Gain": maintenence += 500 print(maintenence, "is your calories in order to gain weight") value = True if final_calories == "maintain" or final_calories == "Maintain": print(maintenence, "is your calories in order to maintain weight") value = True return maintenence def foodlog(): '''This function allows for the user to log their food an a text file''' filename = input("What file would you like to create/open to log your diet: ") with open(filename, "a+") as file: #Add data to file today = date.today() today_line = str(today) + "\n" file.write(today_line) file.write("\n") #What meal meal_number = input("What meal are you logging: ") + "\n" meal_title = "Meal: " + str(meal_number) + "\n" file.write(meal_title) file.write("\n") file.write("Food" + "\t" * 5 + "Calories" + "\t" + "Protein" + "\t" + "Carbs" + "\t" + "Fats" + "\n") file.write("\n") #Initiating meal totals to 0 meal_total = 0 protein_meal_total = 0 carbs_meal_total = 0 fats_meal_total = 0 #Add Food done = False while not done: #Logging the food calories and serving size food = input("Please enter the name of the food: ") calories = float(input("How many calories per serving: ")) serving_size = float(input("How many servings of the food: ")) serving = calories * serving_size #Logging Macros macros = False while not macros: macros = input("Would you like to add the Macros of the food(i.e. Proteins, Fats, Carbs)? yes/no ") if macros == "Yes" or macros == "yes": #Calculating Macros per serving #Protein Calculations proteins = float(input("How many grams of Protein per Serving: ")) protein_total = proteins * serving_size protein_meal_total += protein_total #Carbs Calculations carbs = float(input("How many grams of Carbs per Serving: ")) carb_total = carbs * serving_size carbs_meal_total += carb_total #Fats Calculations fats = float(input("How many grams of Fats per Serving: ")) fat_total = fats * serving_size fats_meal_total += fat_total #Lines with macros if len(food) > 16: food_line = str(food) + "\t" * 3 + str(serving) + "\t" * 2 + str(protein_total) + "\t" + str(carb_total) + "\t" + str(fat_total) + "\n" if len(food) > 8 and len(food) < 16: food_line = str(food) + "\t" * 4 + str(serving) + "\t" * 2 + str(protein_total) + "\t" + str(carb_total) + "\t" + str(fat_total) + "\n" else: food_line = str(food) + "\t" * 5 + str(serving) + "\t" * 2 + str(protein_total) + "\t" + str(carb_total) + "\t" + str(fat_total) + "\n" macros = True elif macros == "No" or macros == "no": #Lines for without macros if len(food) > 16: food_line = str(food) + "\t" * 3 + str(serving) + "\n" if len(food) > 8 and len(food) < 16: food_line = str(food) + "\t" * 4 + str(serving) + "\n" else: food_line = str(food) + "\t" * 5 + str(serving) + "\n" macros = True #Writing the line to the file file.write(food_line) file.write("\n") #Total calories for the meal meal_total += serving #Would you like to add more food to the meal more = False while not more: more = input("Would you like to enter more food (yes/no). ") #If no more food if more == "no" or more == "No": file.write("-" * 100 + "\n") total_meal_calories = "Total Calories For Meal: " + str(meal_total) + "\n" file.write(total_meal_calories) if macros == "yes" or macros =="Yes": total_meal_macros = "Total Protein For Meal: " + str(protein_meal_total) + "\t" + "Total Carbs For Meal: " + str(carbs_meal_total) + "\t" + "Total Fats For Meal: " + str(fats_meal_total) file.write(total_meal_macros) file.write("-" * 100 + "\n") done = True #If more food elif more == "yes" or more == "Yes": more = True def main(): '''Runs Everything''' print("Welcome to your Personal Fitness tracker!\nHere you will be able to log your diet throughout the day.\n") print("Please enter your infomation below to get started.") calorieFinder() value = False while not value: more_meals = input("Would you like to log a meal? (yes/no) ") if more_meals == "yes" or more_meals == "Yes": foodlog() if more_meals == "no" or more_meals == "No": value = True print("Please check your files to see your food log") main()
# Kate Kwasny, Spencer Stith # Starter Code for Counting Inversions, Q1 HW4 # CS 2123, The University of Tulsa from collections import deque import itertools def mergeandcount(lft, rgt): """ Glue procedure to count inversions between lft and rgt. Input: two ordered sequences lft and rgt Output: tuple (number inversions, sorted combined sequence) """ output = [] lenLeft = 0 lenLeft = len(lft) #Maintain a current pointer into each list, initialized to point to the front elements leftPointer = 0 rightPointer = 0 #Maintain a variable count for the number of inversions, initialized to 0 invCount = 0 #While both lists are nonempty: while leftPointer < len(lft) and rightPointer < len(rgt): #print("LEFT: ", lft) #print("RIGHT: ", rgt) #Let ai, bj, be the elements pointed to by the current pointer leftElement = lft[leftPointer] rightElement = rgt[rightPointer] #Append the smaller of these two to the output list #If bj is the smaller element then if(rightElement < leftElement): invCount += len(lft[leftPointer:]) print(rightElement, " conflicts with ", lft[leftPointer:], "invCount: \n", invCount) output.append(rightElement) #Increment count by the number of elements remaining in A #print(invCount," + ", lenLeft) rightPointer += 1 #Endif elif(leftElement < rightElement): output.append(leftElement) leftPointer += 1 #Advance the current pointer in the list from which the smaller element was selected #Endwhile #Once one list is empty, append the remainder of the other list to the output if leftPointer > rightPointer: output.extend(rgt[rightPointer:]) else: output.extend(lft[leftPointer:]) print("Count: ", invCount) #Return count and the merged list return invCount, output def sortandcount(seq): """ Divide-conquer-glue method for counting inversions. Function should invoke mergeandcount() to complete glue step. Input: ordered sequence seq Output: tuple (number inversions, sequence) """ print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") #If the list has one element: if len(seq) == 1: #there are no inversions (0, seq) return 0, seq #Else else: #Divide the list into two halves mid = len(seq)/2 mid = int(mid) #A containts the first n/2 elements a = seq[:mid] #B contains the remaining n/2 elements b = seq[mid:] print("A: ", a) print("B: ", b) #(ra, A) = sortandcount(a) (ra, a) = sortandcount(a) #(rb, B) = sortandcount(b) (rb, b) = sortandcount(b) #(r, seq) = meergeandcount(a, b) (r, seq) = mergeandcount(a, b) #endif #Return r = ra + rb + r, and the sorted list seq r = ra + rb + r #print("R: ", r) return r, seq if __name__ == "__main__": seq1 = [7, 10, 18, 3, 14, 17, 23, 2, 11, 16] seq2 = [2, 1, 3, 6, 7, 8, 5, 4, 9, 10] seq3 = [1, 3, 2, 6, 4, 5, 7, 10, 8, 9] songs1 = [(1, "Stevie Ray Vaughan: Couldn't Stand the Weather"), (2, "Jimi Hendrix: Voodoo Chile"), (3, "The Lumineers: Ho Hey"), (4, "Adele: Chasing Pavements"), (5, "Cake: I Will Survive"), (6, "Aretha Franklin: I Will Survive"), (7, "Beyonce: All the Single Ladies"), (8, "Coldplay: Clocks"), (9, "Nickelback: Gotta be Somebody"), (10, "Garth Brooks: Friends in Low Places")] songs2 = [(3, "The Lumineers: Ho Hey"), (4, "Adele: Chasing Pavements"), (2, "Jimi Hendrix: Voodoo Chile"), (1, "Stevie Ray Vaughan: Couldn't Stand the Weather"), (8, "Coldplay: Clocks"), (6, "Aretha Franklin: I Will Survive"), (5, "Cake: I Will Survive"), (7, "Beyonce: All the Single Ladies"), (9, "Nickelback: Gotta be Somebody"), (10, "Garth Brooks: Friends in Low Places")] songs3 = [(1, "Stevie Ray Vaughan: Couldn't Stand the Weather"), (2, "Jimi Hendrix: Voodoo Chile"), (3, "The Lumineers: Ho Hey"), (4, "Adele: Chasing Pavements"), (6, "Aretha Franklin: I Will Survive"), (5, "Cake: I Will Survive"), (7, "Beyonce: All the Single Ladies"), (8, "Coldplay: Clocks"), (10, "Garth Brooks: Friends in Low Places"), (9, "Nickelback: Gotta be Somebody")] print("~~~~~ Number 1 ~~~~~") print(seq1) print("# Inversions: %i\n" % sortandcount(seq1)[0]) print("~~~~~ Number 2 ~~~~~") print(seq2) print("# Inversions: %i\n" % sortandcount(seq2)[0]) print("~~~~~ Number 3 ~~~~~") print(seq3) print("# Inversions: %i\n" % sortandcount(seq3)[0]) print("~~~~~ Songs 1 ~~~~~") print(songs1) print("# Inversions: %i\n" % sortandcount(songs1)[0]) print("~~~~~ Songs 2 ~~~~~") print(songs2) print("# Inversions: %i\n" % sortandcount(songs2)[0]) print("~~~~~ Songs 3 ~~~~~") print(songs3) print("# Inversions: %i\n" % sortandcount(songs3)[0]) """The code still isn't accounting for the right half of conflicts for when the code is split like it counts the left half of inverses fine, and then the right half is wrong. But I got the number of inversions correct for the integer lists. I am still having trouble with the songs lists. For songs 2 [3, 4, 2, 1, 8, 6, 5, 7, 9, 10] when it splits, it only accounts for [3, 4, 2, 1, 8] this halves inverse count and not this one [6, 5, 7, 9, 10] and when glue-ing back it ignores them too """
# # @lc app=leetcode.cn id=144 lang=python3 # # [144] 二叉树的前序遍历 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] # iterative # DFS:使用 Stack 后进先出;BFS:使用 Queue 先进先出 my_stack, output = [root], [] while my_stack: node = my_stack.pop() output.append(node.val) if node.right: my_stack.append(node.right) if node.left: my_stack.append(node.left) return output # # recursive # output = [root.val] # output.extend(self.preorderTraversal(root.left)) # output.extend(self.preorderTraversal(root.right)) # return output # @lc code=end
# # @lc app=leetcode.cn id=144 lang=python3 # # [144] 二叉树的前序遍历 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: # # recursive: 根-左-右,注意用 extend 连接返回的数组 # res = [] # if root: # res.append(root.val) # res.extend(self.preorderTraversal(root.left)) # res.extend(self.preorderTraversal(root.right)) # return res # iterative res, stack = [], [root] while stack: node = stack.pop() if node: res.append(node.val) stack.append(node.right) stack.append(node.left) return res # @lc code=end
# # @lc app=leetcode.cn id=529 lang=python3 # # [529] 扫雷游戏 # # @lc code=start class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: if not board: return board if board[click[0]][click[1]] == 'M': board[click[0]][click[1]] = 'X' return board rows, cols = len(board), len(board[0]) def valid_pos(r, c): return rows > r >= 0 and cols > c >= 0 def BFS(): queue = deque() queue.append(click) while queue: r, c = queue.popleft() # visited or search condition unqualified if board[r][c] != 'E': continue m_cnt = 0 for i in [-1, 0, 1]: for j in [-1, 0, 1]: if (i == 0 and j == 0) or not valid_pos(r+i, c+j): continue if board[r+i][c+j] == 'M': m_cnt += 1 if m_cnt == 0: board[r][c] = 'B' for i in [-1, 0, 1]: for j in [-1, 0, 1]: if (i == 0 and j == 0) or not valid_pos(r+i, c+j): continue if board[r+i][c+j] == 'E': queue.append([r+i, c+j]) else: board[r][c] = str(m_cnt) return board return BFS() # visited def DFS(r, c): # terminator & visited if not valid_pos(r, c) or board[r][c] != 'E': return # process current level m_cnt = 0 for i in [-1, 0, 1]: for j in [-1, 0, 1]: if (i == 0 and j == 0) or not valid_pos(r+i, c+j): continue if board[r+i][c+j] == 'M': m_cnt += 1 if m_cnt == 0: board[r][c] = 'B' # drill down, 注意!!只有当点周围没有雷时才继续递归 for i in [-1, 0, 1]: for j in [-1, 0, 1]: if (i == 0 and j == 0) or not valid_pos(r+i, c+j): continue if board[r+i][c+j] == 'E': DFS(r+i, c+j) else: board[r][c] = str(m_cnt) return board return DFS(click[0], click[1]) # @lc code=end
# # @lc app=leetcode.cn id=105 lang=python3 # # [105] 从前序与中序遍历序列构造二叉树 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: # 关键:通过inorder确定左右子树的长度 inorder_mem = {v: i for i, v in enumerate(inorder)} def traverse(prelist, in_begin, in_end): if not prelist: return None root = prelist[0] in_idx = inorder_mem[root] # leftLength + 1 == idx - inBegin + 1 left_len = in_idx - in_begin # leftLength + rightLength + 1 = inEnd - inBegin + 1 right_len = in_end - in_begin - left_len node = TreeNode(root) node.left = traverse(prelist[1:left_len+1], in_begin, in_idx-1) node.right = traverse(prelist[left_len+1:], in_idx+1, in_end) return node return traverse(preorder, 0, len(inorder)-1) # @lc code=end
from keras.preprocessing import image import numpy as np x = np.zeros([2,28*28*3]) def LoadNAdd(file): # Load the image from file img = image.load_img(file) # Turn the image into an array img = image.img_to_array(img) # Normalize the image by /255 using float32 img = img.astype('float32')/255 # Reshape the image so its Keras ready img = img.reshape(1,28*28*3) return img x[0] = LoadNAdd("gokuSm.jpg") x[1] = LoadNAdd("goku2Sm.jpg") # check out its shape print(x.shape, x)
#################################### # AUTHOR NAME: SkipperHQ # PROJECT NAME: RunicRealms # PROJECT STARTED: 29/07/2020 # PROJECT DESCRIPTION: RunicRealms is a text-based adventure RPG set in a medieval fantasy world, explore different areas, battle monsters, collect loot and craft different items with your monster drops. #################################### ###### Preparatory Settings ###### import random import time import os import sys # Hero Classes class warrior(object): name = "Warrior" health = 25 attack = 4 defence = 2 magic = 0 class tank(object): name = "Tank" health = 25 attack = 2 defence = 4 magic = 0 class sage(object): name = "Sage" health = 20 attack = 2 defence = 2 magic = 4 # Enemy Classes class rabbit(object): name = "Rabbit" description = "You catch a glimpse of a rabbit hopping around in a nearby field" health = 4 attack = 1 defence = 0 class chicken(object): name = "Chicken" description = "A chicken runs out from behind a nearby tree" health = 4 attack = 1 defence = 0 class boar(object): name = "Boar" description = "A boar starts running toward you from a nearby tree" health = 6 attack = 3 defence = 1 class goblin(object): name = "Goblin" description = "A goblin tries to ambush you from a nearby rock" health = 8 attack = 4 defence = 1 class slime(object): name = "Slime" description = "A slime jumps down from the cave's rooftop infront of you" health = 6 attack = 1 defence = 3 class kobold(object): name = "Kobold" description = "You look ahead into a narrow cave system and see a kobold" health = 6 attack = 3 defence = 2 ##### End of Preparatory Settings ##### def main(): print(""" ############################################## ### ### ### Welcome to ### ### ### ### RunicRealms ### ### ### ### ====================================== ### ### A Text-Based Adventure RPG ### ############################################## """) print("Welcome to RunicRealms.!\nPlease use the numbers to the left of their respective options to navigate.\n1. New Game\n2. Load Game\n3. Options\n4. Exit Game") option = input("> ") if option == "1" or option.title() == "New": name() elif option == "2" or option.title() == "Load": # Load Game pass elif option == "3" or option.title() == "Options": # Options pass elif option == "4" or option.title() == "Exit" or option.title() == "Quit": sys.exit() else: print("Invalid selection, please use the characters 1, 2, 3, or 4 to navigate to their respective menus.") def name(): print("What is your name, adventurer? ") global characterName characterName = input("> ") if len(characterName) < 3: print("Invalid name, please use at least three characters.\n") name() else: print("Welcome to this magical world,", characterName.title(), "\n") classSelection() def classSelection(): global character print("Please select your class from those listed below:\n1. Warrior - High offense with medium defence and no magic.\n2. Tank - High defence with medium offense and no magic.\n3. Sage - High magic offense with medium defence and no melee offense.\nSelect your choice by typing the name of the class or '1', '2', or '3' respectively.\n") classSelectionInput = input("> ") if classSelectionInput == "1" or classSelectionInput.title() == "Warrior": character = warrior print("You have chosen the class 'Warrior', your starting attributes are: \nName:", characterName.title(), "\nClass:", character.name, "\nHealth:", character.health, "\nAttack:", character.attack, "\nDefence:", character.defence, "\nMagic:", character.magic, "\nDo you confirm this selection? (Y/N)") classSelectionInputConfirmation = input("> ") if classSelectionInputConfirmation.title() == "Y": print("You've chosen the Warrior Class, enjoy!") adventureMenu() elif classSelectionInputConfirmation.title() == "N": classSelection() else: print("Not a valid selection, returning to class selection.") classSelection() elif classSelectionInput == "2" or classSelectionInput.title() == "Tank": character = tank print("You have chosen the class 'Tank', your starting attributes are: \nName:", characterName.title(), "\nClass:", character.name, "\nHealth:", character.health, "\nAttack:", character.attack, "\nDefence:", character.defence, "\nMagic:", character.magic, "\nDo you confirm this selection? (Y/N)") classSelectionInputConfirmation = input("> ") if classSelectionInputConfirmation.title() == "Y": print("You've chosen the Tank Class, enjoy!") adventureMenu() elif classSelectionInputConfirmation.title() == "N": classSelection() else: print("Not a valid selection, returning to class selection.") classSelection() elif classSelectionInput == "3" or classSelectionInput.title() == "Sage": character = sage print("You have chosen the class 'Sage', your starting attributes are: \nName:", characterName.title(), "\nClass:", character.name, "\nHealth:", character.health, "\nAttack:", character.attack, "nDefence:", character.defence, "\nMagic:", character.magic, "\nDo you confirm this selection? (Y/N)") classSelectionInputConfirmation = input("> ") if classSelectionInputConfirmation.title() == "Y": print("You've chosen the Sage Class, enjoy!") adventureMenu() elif classSelectionInputConfirmation.title() == "N": classSelection() else: print("Not a valid selection, returning to class selection.\n") classSelection() def adventureMenu(): print("\nAdventure Menu: \nPlease navigate using the number to the left of the respective navigation option.\n1. Explore\n2. Bag\n3. Shop\n4. Journal\n5. Options\n6. Exit Game\n\n") adventureMenuInput = input("> ") if adventureMenuInput == "1" or adventureMenuInput.title() == "Explore": explore.exploreMenu(self) elif adventureMenuInput == "2" or adventureMenuInput.title() == "Bag": bag() elif adventureMenuInput == "3" or adventureMenuInput.title() == "Shop": pass elif adventureMenuInput == "4" or adventureMenuInput.title() == "Journal": pass elif adventureMenuInput == "5" or adventureMenuInput.title() == "Options": pass elif adventureMenuInput == "6" or adventureMenuInput.title() == "Exit": sys.exit() else: print("Invalid selection, please navigate using a number to the left of the respective navigation option.") adventureMenu() class explore: def __init__(self): self.exploring = False def exploreMenu(self): print("Exploration Menu:\nChoose which location you'd like to explore from the list:\n1. Forest\n2. Cave\n") exploreMenuInput = input("> ") if exploreMenuInput == "1" or exploreMenuInput.title() == "Forest": self.exploring = 1 self.exploreLocations(self) elif exploreMenuInput == "2" or exploreMenuInput.title() == "Cave": self.exploring = 2 self.exploreLocations(self) else: print("Invalid Selection, please navigate using the number to the left of the respective navigation option.") exploreMenu(self) def exploreLocations(self): if self.exploring is not False: if self.exploring == 1: print("Forest.......") enemy = enemySelect() battleState() elif self.exploring == 2: print("Cave.......") enemy = enemySelect() battleState() else: print("Error exploreLocations") else: print("Error, exploreLocations.") self = explore def enemySelect(): enemyList = [] enemySelectionForest = [rabbit,chicken,boar] enemySelectionCave = [goblin,kobold,slime] if self.exploring == 1: enemyList = enemySelectionForest elif self.exploring == 2: enemyList = enemySelectionCave else: print("Error, see enemySelect(enemySelection)\nPress Enter to Continue...") input("> ") name() enemy = random.choice(enemyList) # enemy = enemyList[enemyChance] return enemy def battleState(): # Start of battleState's preparatory functions. def enemyKilled(): if enemy.health <= 0: print("You have killed the", enemy.name, "you lift the corpse expectantly...") time.sleep(2) # enemy drop gold here lootChance = random.randint(0, 6) if lootChance == 0: # This is where the loot drops will go. pass else: print("Unfortunately, you found no loot under the corpse.\nWould you like to continue exploring or not?") if enemy.name == "Chicken" or enemy.name == "Rabbit": enemy.health = 4 elif enemy.name == "Boar" or enemy.name == "Kobold" or enemy.name == "Slime": enemy.health = 6 elif enemy.name == "Goblin": enemy.health = 8 option = input("> ") if option == "1" or option.title() == "Continue": battleState() else: adventureMenu() def gameOver(): if character.health <= 0: print("Unfortunately, your health has fallen to zero, you are now dead.\nGame over, thank you for playing.") time.sleep(5) main() def combatAction(): print("\nWhat do you do?\nSelect a following option to continue:\n1. Melee Attack\n2. Magic Attack (WIP)\n3. Run\n4. Bag\n5. Journal\n6. Options\n7. Exit Game") # End of battleState's preparatory functions. # Start of battleState # assigns enemy to the enemySelect() function. enemy = enemySelect() print(enemy.description) combatAction() while character.health > 0: userAction = input("> ") if userAction == "1" or userAction.title() == "Melee": if enemy.health > 0: character.health = character.health - (enemy.attack / character.defence) print("The", enemy.name, "attacks you, dealing damage to you.\nYou are now left with", int(character.health), "life points remaining.") print("You swing your weapon toward the", enemy.name) missChance = random.randint(0,10) if missChance <= 2: print("You completely miss the " + enemy.name + ", you regain your balance.") combatAction() else: enemy.health = enemy.health - (character.attack - enemy.defence) print("You attack the " + enemy.name + ", the "+ enemy.name + " is left with", int(enemy.health), "health points.") combatAction() enemyKilled() else: enemyKilled() else: print("Either incorrect selection or selection is not yet implemented.\nPress Enter to Continue...") input("> ") adventureMenu() main()
# 1. generate word import random from urllib.request import urlopen LIMIT = 10 #words = open('/usr/share/dict/words').read().split() words = urlopen("https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt").read().split() words = [word.decode('utf-8') for word in words if len(word) > 4] thisword = (random.choice(words)) slots = ["_"] * len(thisword) wrong_guess = [] guesses = [] def find_all_indices(word, letter): """ Finds the indices of all occurrences of letter in word. >>> find_all_indices("viola", "a") [4] >>> find_all_indices("apple", "p") [1, 2] >>> find_all_indices("hippopotamus", "p") [2, 3, 5] """ list_indices = [] current_index = 0 while word.find(letter) > -1: index = word.find(letter) list_indices.append(current_index + index) word = word[index+1:] current_index = current_index + index + 1 return list_indices while len(wrong_guess) < LIMIT and "_" in slots: print(" ".join(slots)) letter = input('Next guess> ') if letter in guesses: print("Don't guess something you already guessed") continue guesses.append(letter) if letter in thisword: indices = find_all_indices(thisword, letter) for index in indices: slots[index] = letter else: wrong_guess.append(letter) print(wrong_guess) if "_" in slots: print("You lose sucker.") else: print("Congrats, you won!") print(thisword + " was the word.") # 2. write number of slots # 3. person guesses a letter. # if right, letter is displayed in slots # if wrong, show wrong guess. keep track # of the # of guesses b/c you only can get __ wrong. # display slots always #person guesses until he gets the word or dies
def menu(): print ("Menu:\n" \ "0)Suma\n" \ "1)Resta\n" \ "2)Multiplicacion\n" \ "3)Division\n" \ "4)Potencia\n" \ "5)Residuo\n" \ "6)Factorial\n" \ "7)Promedio\n" \ "8)Salir\n") def suma(x,y): return x+y def resta(x,y): return x - y def multiplicacion(x,y): return x * y def division(x,y): return x / y def potencia(x,y): return x ** y def residuo(x,y): return x % y def factorial(x): f = 1 for i in range(x): f *= x x -=1 return f def promedio(x,y): return (x + y)/2 def calculadora(): op = int(input("Seleccione opcion:\n")) while (op>=0 and op<8): x = int(input("Ingrese Numero:\n")) if(op!=6): y = int(input("Ingrese otro numero:\n")) if(op==0): print ("Resultado de la suma: ", suma(x,y)) if (op == 1): print ("Resultado de la resta: ", resta(x,y)) if (op == 2): print ("Resultado de la multiplicacion: ",multiplicacion(x,y)) if (op == 3): print ("Resultado de la division: ", division(x,y)) if (op == 4): print ("Resultado de la potencia: ",potencia(x,y)) if (op == 5): print ("Resultado del residuo: ",residuo(x,y)) if (op == 6): print ("Resultado del factorial: ",factorial(x)) if (op == 7): print ("Resultado del promedio: ",promedio(x,y)) menu() op = int(input("Seleccione otra opcion:\n")) menu() # llamar a la funcion menu calculadora() # llamar a la funcion calculadora
nEntero = int(raw_input("Ingresar numero entero: ")) if nEntero%2==0: # si es doble(es par) mitad = nEntero/2 # Saber la mitad del numero que se ingreso if mitad%2==0: # hacer la comparacion entre el doble y la mitad print "Este es el doble de un numero par: ",mitad else: print "Este es el doble de un numero impar: ",mitad else: #No es doble, ya que es impar print "Este numero no es doble de un numero, ya que es impar."
bencina = ["Bencina 93","Bencina 95", "Bencina 97"] valorbencinas = [600,650,700] print ("Bencinas disponibles:") for i in range(len(bencina)): #recorer las listas print (i),")",bencina[i], valorbencinas[i] opcion = int(input("Elija una Bencina e ingrese el numero: ")) print ("Eligio la opcion: ", bencina[opcion],"$",valorbencinas[opcion]) print ("Forma de pago: ") print ("1) Tarjeta de Credito.") print ("2) Efectivo") f = int(input("Elija la opcion e ingrese el numero: ")) apagar = int(input("Total a pagar: ")) totalbencina = apagar//valorbencinas[opcion] print ("Total de litros: ",totalbencina)
#!/usr/bin/python3 # program to ascertain if user input is leap year print() print("Enter any year to find out if it's a leap year or not") year_input = int(input("Please enter any year: ")) print(f"You have chosen {year_input}. Checking ...") print() ans = ['YES', 'Y', 'yes', 'y'] ans_1 = ans while ans_1 == ans: if len(str(year_input)) == 4: if (year_input % 4) == 0: if (year_input % 100) == 0: if (year_input % 400) == 0: print(True) else: print(False) else: print(True) else: print(False) else: print("That's not a correct year format.") print() ques = input("Do you want to try again? ") if ques not in ans: exit(0) else: year_input = int(input("Please enter any year: ")) print(f"You have chosen {year_input}. Checking ...") print()
"""Expressions in geometry prover.""" import itertools, copy from pstats import Stats import cProfile from typing import Tuple, Sequence, Optional, List, Dict POINT, LINE, PonL, SEG, TRI, CIRC, CYCL, MIDP = range(8) class Fact: """Represent a fact in geometry prover, e.g.: coll(A, C, B) is Fact("coll", ["A", "C", "B"]). updated: Whether this fact is generated by prover or not. lemma: An integer that record which rule is it required to obtain this fact (its place in ruleset). None represents no requirement. cond: A list of integers that record what facts (their place in fact list) are required to obtain this fact. Use "default" when initializing. number -1 represents no requirement. """ def __init__(self, pred_name: str, args: Sequence[str], *, updated=False, lemma=None, cond=None, negation=False, tail=False): self.pred_name = pred_name self.args = args self.updated = updated self.lemma = lemma if cond is None: cond = [] self.cond = cond # Whether this is a negation fact. e.g.: ¬coll(O, A, B) self.negation = negation # Whether a fact is shadowed by another self.shadowed = False # For facts combined from other facts, mapping from indices in self # to indices to the left / right condition. self.left_map = None self.right_map = None # Whether the fact in the tail of a rule, # and its pred_name is "coll", "cyclic" or "circle". # In this case, this fact will be matched passively, # which match_expr() will only check the inst and to # see if exists an order of arguments conforms to inst. # e.g.: # inst = {A: E, B: F, C: G}, pat = [A, B, C], f = [G, F, E] # tail = True -> Successfully matched with new_inst = {A: E, B: F, C: G}. # tail = False -> Match failed. self.tail = False def __hash__(self): return hash(("Fact", self.pred_name, tuple(self.args))) def __eq__(self, other): if isinstance(other, Fact) and self.pred_name == other.pred_name: if self.pred_name == 'circle': return self.args[0] == other.args[0] and set(self.args[1:]) == set(other.args[1:]) elif self.pred_name in ('coll', 'cyclic'): return set(self.args) == set(other.args) else: return self.args == other.args def __str__(self): if self.negation: pre = "¬" else: pre = "" if self.pred_name == 'eqangle' and self.args[0].isupper(): return pre + " = ".join( "∠[%s%s,%s%s]" % tuple(self.args[4 * i:4 * i + 4]) for i in range(len(self.args) // 4)) elif self.pred_name == 'contri': return pre + " ≌ ".join("△%s%s%s" % tuple(self.args[3 * i:3 * i + 3]) for i in range(len(self.args) // 3)) elif self.pred_name == 'simtri': return pre + " ∽ ".join("△%s%s%s" % tuple(self.args[3 * i:3 * i + 3]) for i in range(len(self.args) // 3)) else: return pre + "%s(%s)" % (self.pred_name, ",".join(self.args)) def __repr__(self): return str(self) def get_subfact(self, indices): if self.lemma != 'combine': return self # return self if all(i in self.left_map for i in indices): new_indices = list(self.left_map[i] for i in indices) return self.cond[0].get_subfact(new_indices) elif all(i in self.right_map for i in indices): new_indices = list(self.right_map[i] for i in indices) return self.cond[1].get_subfact(new_indices) else: return self def get_arg_type(self): """Obtain the type of arguments for the given fact. This is determined by the pred_name of the fact, as well as upper/lower case of the arguments. Return the argument type. """ pred_name = self.pred_name if pred_name in ("para", "perp", "eqangle", "eqratio"): if self.args[0].isupper(): return PonL else: return LINE elif pred_name == "coll": return POINT elif pred_name == "cong": return SEG elif pred_name == "cyclic": return CYCL elif pred_name == "circle": return CIRC elif pred_name in ("simtri", "contri"): return TRI elif pred_name == "midp": return MIDP else: raise NotImplementedError class Line: """Represent a line contains more than one point.""" def __init__(self, args: Sequence[str]): assert len(args) > 1 self.args = set(args) def __hash__(self): return hash(("line", tuple(sorted(self.args)))) def __eq__(self, other): return isinstance(other, Line) and self.args == other.args def __str__(self): return "Line(%s)" % (",".join(self.args)) def __repr__(self): return str(self) def is_same_line(self, other): # Two lines are same if they have at least 2 identical points. return isinstance(other, Line) and len(self.args.intersection(other.args)) >= 2 def combine(self, other): # If the other line refers to the same line of this line, # add the points of other line that are not in this line. assert self.is_same_line(other), "combine line" if self.args != other.args: self.args = self.args.union(other.args) class Circle: """Represent a circle.""" def __init__(self, args: Sequence[str], center=None): self.args = set(args) self.center = center def __hash__(self): return hash(("circle", self.center, tuple(sorted(self.args)))) def __eq__(self, other): if self.center and other.center and self.center != other.center: return False return isinstance(other, Circle) and self.args == other.args def __str__(self): return "Circle(%s,%s)" % (self.center, ",".join(self.args)) def __repr__(self): return str(self) def is_same_circle(self, other): """Two circles are the same if they have 3 or more identical points. If both circles have center and they have 3 or more identical points then two centers must be the same. """ if isinstance(other, Circle) and len(self.args.intersection(other.args)) >= 3: if self.center and other.center: return self.center == other.center else: return True else: return False def combine(self, other): # If the other circle refers to the same as this circle, # add the points of other circle that are not in this circle. assert self.is_same_circle(other), "combine circle" if self.args != other.args: self.args = self.args.union(other.args) if other.center and not self.center: self.center = other.center class Rule: """Represent a rule in geometry prover, e.g.: coll(A, C, B) :- coll(A, B, C) is Rule([coll(A, B, C)], coll(A, C, B)) """ def __init__(self, assums: Sequence[Fact], concl: Fact): self.assums = assums self.assums_pos = [a for a in self.assums if not a.negation] if len(self.assums_pos) > 1: for i in range(len(self.assums_pos) - 1): self.assums_pos[i].tail = self.check_tail_condition(self.assums_pos[i])\ and self.check_tail_condition(self.assums_pos[i + 1]) self.assums_pos[-1].tail = self.check_tail_condition(self.assums_pos[-1]) self.assums_neg = [a for a in self.assums if a.negation] self.concl = concl def __eq__(self, other): return isinstance(other, Rule) and self.assums == other.assums and self.concl == other.concl def __str__(self): return "%s :- %s" % (str(self.concl), ", ".join(str(assum) for assum in self.assums)) def check_tail_condition(self, fact): """Check whether the assumptions is to be matched passively. An assumption is matched passively when it is coll, cyclic, or circle. """ return fact.pred_name in ('coll', 'cyclic', 'circle') def make_pairs(args, pair_len=2): """Divide input list args into groups of length pair_len (default 2).""" assert len(args) % pair_len == 0 return [tuple(args[pair_len * i: pair_len * (i + 1)]) for i in range(len(args) // pair_len)] class Prover: def __init__(self, ruleset: Dict, hyps: Optional[List[Fact]] = None, concl: Fact = None, lines=None, circles=None): self.ruleset = ruleset if hyps is None: hyps = [] self.hyps = hyps self.classified_hyps = {"para": [], "coll": [], "cong": [], "midp": [], "perp": [], "eqangle": [], "eqratio": [], "cyclic": [], "circle": [], "simtri": [], "contri": []} for hyp in hyps: self.classified_hyps[hyp.pred_name].append(hyp) self.concl = concl if lines is None: lines = [] self.lines = lines if circles is None: circles = [] self.circles = circles # Mapping from pairs of points on a line to that line self.line_map = dict() def equal_pair(self, p1, p2) -> bool: return p1 == p2 or p1 == (p2[1], p2[0]) def equal_line(self, p1, p2) -> bool: return self.get_line(p1) == self.get_line(p2) def equal_angle(self, a1, a2) -> bool: p1, p2 = a1[0:2], a1[2:4] q1, q2 = a2[0:2], a2[2:4] return self.get_line(p1) == self.get_line(q1) and self.get_line(p2) == self.get_line(q2) def equal_angle_reflected(self, a1, a2) -> bool: p1, p2 = a1[0:2], a1[2:4] q1, q2 = a2[0:2], a2[2:4] return self.get_line(p1) == self.get_line(q2) and self.get_line(p2) == self.get_line(q1) def equal_triangle(self, t1, t2) -> bool: return set(t1) == set(t2) def get_line(self, pair: Tuple[str]) -> Line: """Return a line from lines containing the given pair of points, if it exists. Otherwise return a line containing the pair. Examples: get_line([Line(P,Q,R)], (P, Q)) -> Line(P,Q,R) get_line([Line(P,Q,R)], (O, P)) -> Line(O,P) """ assert len(pair) == 2 if pair not in self.line_map: new_line = Line(pair) self.line_map[pair] = new_line return new_line else: return self.line_map[pair] def get_circle(self, points: Sequence[str], center: Optional[str] = None) -> Circle: """Return a circle from circles containing the given points and center (optional), if it exists. Otherwise return a circle containing the points and center (optional). """ new_circle = Circle(points, center=center) for circle in self.circles: if new_circle.is_same_circle(circle): return circle return new_circle def match_expr(self, pat: Fact, f: Fact, inst) -> List[Tuple[Dict, Fact]]: """Match pattern with f, return a list of result(s). inst is a dictionary that assigns point variables to points, and line variables to pairs of points. lines: list of currently known lines. Multiple results will be generated if a line and two points on it need to be matched simultaneously. Example: match(coll(A, B, C), coll(P, Q, R), {}) -> [{A: P, B: Q, C: R}]. match(coll(A, B, C), coll(P, Q, R), {A: P}) -> [{A: P, B: Q, C: R}]. match(coll(A, B, C), coll(P, Q, R), {A: Q}) -> []. match(coll(A, B, C), para(P, Q, R, S), {}) -> []. match(perp(l, m), perp(P, Q, R, S), {}) -> [{l: (P, Q), m: (R, S)}] match(perp(l, m), perp(P, Q, R, S), {l: (Q, P)}) -> [{l: (Q, P), m: (R, S)}] match(perp(l, m), perp(P, Q, R, S), {l: (O, P)}, lines=[Line(O, P, Q)]) -> [{l: (O, P), m: (R, S)}] match(perp(l, m), perp(P, Q, R, S), {l: (O, P)}) -> []. """ def match_PonL(cs): t_insts = [inst] i = 0 while i < len(pat.args) // 2: ts = [] for t_inst in t_insts: l = self.get_line(cs[i]) pat_a, pat_b = pat.args[i * 2: i * 2 + 2] if pat_a in t_inst: if t_inst[pat_a] in l.args: a = [t_inst[pat_a]] else: a = [] else: a = list(l.args) if pat_b in t_inst: if t_inst[pat_b] in l.args: b = [t_inst[pat_b]] else: b = [] else: b = list(l.args) perms = [[x, y] for x in a for y in b if x != y] for a, b in perms: t = copy.copy(t_inst) # t is one result t[pat_a], t[pat_b] = a, b ts.append(t) i += 1 t_insts = ts return t_insts def match_circle_post(pat_args, f_args, c_args, flag): """Identical part of the processing for circ and cycl cases. flag -- whether the matching has already failed. """ fixed = [] # arguments in pattern that are also in inst. same_args = list(set(pat_args).intersection(set(inst.keys()))) for same_arg in same_args: if inst[same_arg] in c_args: fixed.append(same_arg) else: flag = True if not flag: # start matching for_comb = sorted(list(c_args - set(inst.values()))) if len(f_args) - len(fixed) > 0: # Order is not considered. comb = itertools.permutations(range(len(for_comb)), len(f_args) - len(fixed)) for c_nums in comb: item = [for_comb[num] for num in c_nums] p = 0 for i in range(len(pat_args)): if pat_args[i] in fixed: continue inst[pat_args[i]] = item[p] p += 1 new_insts.append((copy.copy(inst), f)) else: # remain previous insts and sources new_insts.append((inst, f)) def can_assign(pat, arg): # For case MIDP and case SEG. return pat not in t_inst or t_inst[pat] == arg if pat.pred_name != f.pred_name: return [] if pat.tail: # Get matching result from inst directly. if len(f.args) < len(pat.args): return [] for p in pat.args: if p not in inst.keys(): return [] if inst[p] not in f.args: return [] return [(inst, f.get_subfact([0]))] arg_ty = pat.get_arg_type() new_insts = [] if arg_ty == POINT: # coll or midp case # Generating all possible combinations from long fact: comb = itertools.combinations(range(len(f.args)), len(pat.args)) for c_nums in comb: c = [f.args[num] for num in c_nums] t_inst = copy.copy(inst) flag = False for p_arg, t_arg in zip(pat.args, c): if p_arg in t_inst: if t_arg != t_inst[p_arg]: flag = True else: t_inst[p_arg] = t_arg if not flag: new_insts.append((t_inst, f.get_subfact(c_nums))) elif arg_ty == MIDP: # match point in the middle (exchange is no possible) t_inst = copy.copy(inst) flag = False if pat.args[0] in t_inst: if f.args[0] != t_inst[pat.args[0]]: flag = True else: t_inst[pat.args[0]] = f.args[0] # match other points, which are two sides of a segment (exchange available) if not flag: # case: not exchange if can_assign(pat.args[1], f.args[1]) and can_assign(pat.args[2], f.args[2]): t = copy.copy(t_inst) t[pat.args[1]] = f.args[1] t[pat.args[2]] = f.args[2] new_insts.append((t, f.get_subfact([0]))) # case: exchange if can_assign(pat.args[1], f.args[2]) and can_assign(pat.args[2], f.args[1]): t = copy.copy(t_inst) t[pat.args[1]] = f.args[2] t[pat.args[2]] = f.args[1] new_insts.append((t, f.get_subfact([0]))) elif arg_ty == LINE: # para, perp, eqangle or eqratio case, matching lines if f.pred_name in ("eqangle", "eqratio"): groups = make_pairs(f.args, pair_len=4) comb = itertools.combinations(range(len(groups)), len(pat.args) // 2) # all possibilities else: groups = make_pairs(f.args) comb = itertools.permutations(range(len(groups)), len(pat.args)) for c_nums in comb: if f.pred_name in ("eqangle", "eqratio"): cs = [groups[c_nums[0]][0:2], groups[c_nums[0]][2:4], groups[c_nums[1]][0:2], groups[c_nums[1]][2:4]] else: cs = [groups[num] for num in c_nums] t_inst = copy.copy(inst) flag = False for p_arg, t_args in zip(pat.args, cs): if p_arg in t_inst: l1 = self.get_line(t_inst[p_arg]) l2 = self.get_line(t_args) if l1 != l2: flag = True else: t_inst[p_arg] = t_args if not flag: new_insts.append((t_inst, f.get_subfact(c_nums))) elif arg_ty == SEG: # eqratio or cong case # Possible to assign t_inst[pat] to arg new_insts = [] groups = make_pairs(f.args) comb = itertools.combinations(range(len(groups)), len(pat.args) // 2) for c_nums in comb: c = [groups[num] for num in c_nums] t_insts = [inst] for i in range(len(pat.args) // 2): ts = [] for t_inst in t_insts: pat_a, pat_b = pat.args[2 * i: 2 * i + 2] if can_assign(pat_a, c[i][0]) and can_assign(pat_b, c[i][1]): t = copy.copy(t_inst) t[pat_a] = c[i][0] t[pat_b] = c[i][1] ts.append(t) if can_assign(pat_a, c[i][1]) and can_assign(pat_b, c[i][0]): t = copy.copy(t_inst) t[pat_a] = c[i][1] t[pat_b] = c[i][0] ts.append(t) t_insts = ts if t_insts: subfact = f.get_subfact(c_nums) for t_inst in t_insts: new_insts.append((t_inst, subfact)) elif arg_ty == TRI: # contri and simtri case groups = make_pairs(f.args, pair_len=3) comb = itertools.combinations(range(len(groups)), len(pat.args) // 3) # indices: assign which char in the group to assign to pattern. # E.g. # indices: 0, 2, 1 # pat.args: A, B, C # ↓ ↙ ↘   # group: E, F, G # matched: {A: E, B: F, C: G} # indices_list = [[0, 1, 2], [0, 2, 1], [1, 2, 0]] new_insts = [] for c_nums in comb: cs = [groups[num] for num in c_nums] for indices in indices_list: flag = False t_inst = copy.copy(inst) for i in range(len(cs)): for j in range(3): if pat.args[i * 3 + j] in t_inst: if cs[i][indices[j]] != t_inst[pat.args[i * 3 + j]]: flag = True else: t_inst[pat.args[i * 3 + j]] = cs[i][indices[j]] if not flag: new_insts.append((t_inst, f.get_subfact(c_nums))) elif arg_ty == PonL: # para, perp, or eqangle, matching points # Generate possible lines selections (two lines in one selection). if f.pred_name == "eqangle": groups = make_pairs(f.args, pair_len=4) comb = itertools.combinations(range(len(groups)), len(pat.args) // 4) else: groups = make_pairs(f.args) comb = itertools.combinations(range(len(groups)), len(pat.args) // 2) for c_nums in comb: if f.pred_name == "eqangle": cs = [groups[c_nums[0]][0:2], groups[c_nums[0]][2:4], groups[c_nums[1]][0:2], groups[c_nums[1]][2:4]] else: cs = [groups[num] for num in c_nums] t_insts = match_PonL(cs) if t_insts: subfact = f.get_subfact(c_nums) for t_inst in t_insts: new_insts.append((t_inst, subfact)) elif arg_ty == CYCL: circle = self.get_circle(list(f.args)) flag = False match_circle_post(pat.args, f.args, circle.args, flag) elif arg_ty == CIRC: circle = self.get_circle(f.args[1:], f.args[0]) flag = False if pat.args[0] in inst and inst[pat.args[0]] != f.args[0]: flag = True else: inst[pat.args[0]] = f.args[0] match_circle_post(pat.args[1:], f.args[1:], circle.args, flag) else: raise NotImplementedError return new_insts def get_applicable_facts(self, rule: Rule) -> List[Fact]: """Obtain the list of tuples of facts that may match the assumptions of the rule, according to their pred_name. """ def pick_applicable_facts_step(rule: Rule, facts: List[Fact]) -> None: if len(facts) < len(rule.assums_pos): for fact in self.classified_hyps[rule.assums[len(facts)].pred_name]: if fact in facts or fact.shadowed: continue new_facts = copy.copy(facts) new_facts.append(fact) pick_applicable_facts_step(rule, new_facts) else: picked.append(facts) picked = [] pick_applicable_facts_step(rule, []) return picked def check_classified_hyps_foreach(self, fun, *args, types=None) -> bool: ''' Return false if exists one or more hyp in all hyps that is not satisfied the given function. ''' if types is None: vals = self.classified_hyps.values() else: vals = [value for key, value in self.classified_hyps.items() if key in types] for val in vals: for i in val: if not fun(i, *args): return False return True def check_redundant(self, hyp, fact) -> bool: return not(not hyp.shadowed and self.check_imply(hyp, fact)) def check_imply_reverse(self, goal, fact) -> bool: return not self.check_imply(goal, fact) def check_reflected(self, hyp, fact) -> bool: if fact.pred_name in ('eqangle'): # print(hyp, fact) f_angles = make_pairs(hyp.args, pair_len=4) g_angles = make_pairs(fact.args, pair_len=4) if all(any(self.equal_angle_reflected(f, g) for f in f_angles) for g in g_angles): # print(hyp, fact) return True return False def check_reflected_reverse(self, hyp, fact) -> bool: return not self.check_reflected(hyp, fact) def set_shadow_fact(self, target, fact, new_facts): if not target.shadowed and self.check_imply(fact, target): target.shadowed = True if not target.shadowed: new_fact = self.combine_facts(fact, target) if new_fact: fact.shadowed = True target.shadowed = True fact = new_fact new_facts.append(new_fact) def apply_rule(self, rule_name: str, facts: Sequence[Fact]) -> bool: """Apply given rule to the list of facts. If param facts is a list of integers: these integers represents the positions in hyps. In this case, hyps must be a list of facts. The new facts generated by this function will combine to hyps automatically. Function returns a fact implying the conclusion if it is found. Otherwise it returns None. If param facts is a list of facts: New facts will be returned. Example: apply_rule( Rule([para(A, B, C, D), para(C, D, E, F)], para(A, B, E, F)), [para(P, Q, R, S), para(R, S, U, V)]) -> para(P, Q, U, V). apply_rule( Rule([coll(A, B, C)], coll(A, C, B)), [para(A, B, D, C)]) -> []. """ rule = self.ruleset[rule_name] assert len(facts) == len(rule.assums_pos) # print("try", rule, facts) # Match positive facts. Save matching result in insts. insts = [(dict(), [])] # type: List[Tuple[Dict, List[Fact]]] for i, (assum, fact) in enumerate(zip(rule.assums_pos, facts)): # match the arguments recursively new_insts = [] # flip = fact.pred_name == 'eqangle' and rule.concl.pred_name in ('simtri', 'contri') for inst, subfacts in insts: news = self.match_expr(assum, fact, inst) for i, subfact in news: new_insts.append((i, subfacts + [subfact])) insts = new_insts # Rule D40 requires more points in conclusion than in assumption. Add points from lines as supplement. if rule_name in ("D40", "D90") and insts: prev_insts = copy.copy(insts) insts = [] if any(i not in prev_insts[0][0].keys() for i in rule.concl.args): for inst, subfacts in prev_insts: not_match = set(rule.concl.args) - set(inst.keys()) for line in self.lines: extended_t_inst = copy.copy(inst) for i, ch in enumerate(not_match): extended_t_inst[ch] = (list(line.args)[i], list(line.args)[i + 1]) insts.append((extended_t_inst, subfacts)) # Get new facts, according to insts for inst, subfacts in insts: # Get correct form of arguments in a fact if rule.concl.args[0].islower(): concl_args = [] # type: List[str] for i in rule.concl.args: concl_args.extend((inst[i][0], inst[i][1])) else: concl_args = [inst[i] for i in rule.concl.args] # Generate new fact fact = Fact(rule.concl.pred_name, concl_args, updated=True, lemma=rule_name, cond=subfacts) if self.check_trivial(fact): continue if self.check_repetitive_char(fact): continue if not self.check_classified_hyps_foreach(self.check_redundant, fact): continue # if not self.check_classified_hyps_foreach(self.check_reflected_reverse, fact, types=['eqangle']): # continue # Check if those assums with negation are satisfied. # If not satisfied, all of the post processes will not be conducted. fact_valid = True if len(rule.assums_neg) > 0: for assum in rule.assums_neg: # Get a fact from assum. if assum.args[0].islower(): tmp_args = [] # type: List[str] for i in assum.args: tmp_args.extend(inst[i]) else: tmp_args = [inst[i][0] for i in assum.args] tmp_fact = Fact(assum.pred_name, tmp_args, negation=True) # print("tmp_fact: ", tmp_fact) fact_valid = not self.check_trivial(tmp_fact) if not fact_valid: continue fact_valid = self.check_classified_hyps_foreach(self.check_imply_reverse, tmp_fact) if not fact_valid: continue if not fact_valid: continue new_facts = [fact] for target in self.classified_hyps[fact.pred_name]: if not target.shadowed and self.check_imply(fact, target): target.shadowed = True if not target.shadowed: new_fact = self.combine_facts(fact, target) if new_fact: fact.shadowed = True target.shadowed = True fact = new_fact new_facts.append(new_fact) # print(new_facts[-1], facts, rule_name) self.hyps.extend(new_facts) for new_fact in new_facts: # if new_fact.pred_name in ('simtri', 'contri', 'eqangle', 'para', 'midp'): # if new_fact.pred_name in ('eqangle'): # print("new fact:", new_fact, rule, facts) self.classified_hyps[new_fact.pred_name].append(new_fact) # print(new_facts[-1], self.concl, self.check_imply(new_facts[-1], self.concl)) if self.check_imply(new_facts[-1], self.concl): return new_facts[-1] def compute_lines(self): """Refresh self.lines from the coll facts.""" self.lines = [] self.line_map = dict() for hyp in self.classified_hyps['coll']: if not hyp.shadowed: line = Line(hyp.args) self.lines.append(line) for p1, p2 in itertools.permutations(hyp.args, 2): self.line_map[(p1, p2)] = line def compute_circles(self): """Refresh self.circles from the cyclic and circle facts.""" self.circles = [] for hyp in self.classified_hyps['cyclic']: if not hyp.shadowed: self.circles.append(Circle(hyp.args)) for hyp in self.classified_hyps['circle']: if not hyp.shadowed: self.circles.append(Circle(hyp.args[1:], center=hyp.args[0])) def search_step(self, only_updated=False) -> None: """One step of searching fixpoint. Apply given ruleset to a list of hypotheses to obtain new facts. If collinear facts are included in hypotheses, new lines can be automatically generated, these new lines might be used when applying rules to hypotheses. """ self.compute_lines() self.compute_circles() for rule_name, rule in self.ruleset.items(): applicable_facts_list = self.get_applicable_facts(rule) # print(rule_name, len(applicable_facts_list)) for facts in applicable_facts_list: if any(fact.shadowed for fact in facts): continue if only_updated and all(not fact.updated for fact in facts): continue res = self.apply_rule(rule_name, facts) if res is not None: return res def search_fixpoint(self) -> Optional[Fact]: """Recursively apply given ruleset to a list of hypotheses to obtain new facts. Recursion exits when new fact is not able to be generated, or conclusion is in the list of facts. Return the list of facts. """ res = self.search_step() if res is not None: return res steps = 0 while steps < 5: steps += 1 res = self.search_step(only_updated=True) if res is not None: return res return False def combine_facts(self, fact, goal) -> Optional[Fact]: """ Combine this fact to other fact. Return a combined long fact if succeed. """ if fact.pred_name != goal.pred_name: return None def get_indices(l, l_comb, comp=None): res = dict() for i, p in enumerate(l): found = False for j, q in enumerate(l_comb): if (comp is None and p == q) or (comp is not None and comp(p, q)): res[j] = i found = True break assert found return res if fact.pred_name == 'perp': # No combination return None elif fact.pred_name == 'coll': l1, l2 = Line(fact.args), Line(goal.args) if l1.is_same_line(l2): l1.combine(l2) f = Fact('coll', list(l1.args), updated=True, lemma='combine', cond=[fact, goal]) f.left_map = get_indices(l1.args, f.args) f.right_map = get_indices(l2.args, f.args) return f else: return None elif fact.pred_name == 'circle': c1, c2 = Circle(fact.args[1:], center=fact.args[0]), Circle(goal.args[1:], center=fact.args[0]) if c1.is_same_circle(c2): c1.combine(c2) f = Fact('circle', [c1.center] + list(c1.args), updated=True, lemma='combine', cond=[fact, goal]) f.left_map = get_indices(c1.args, f.args) f.right_map = get_indices(c2.args, f.args) # print("-----".join(["combined: ", str(fact), str(goal), str(f)])) return f else: return None elif fact.pred_name == 'cyclic': c1, c2 = Circle(fact.args), Circle(goal.args) if c1.is_same_circle(c2): c1.combine(c2) f = Fact('cyclic', list(c1.args), updated=True, lemma='combine', cond=[fact, goal]) f.left_map = get_indices(c1.args, f.args) f.right_map = get_indices(c2.args, f.args) # print("-----".join(["combined: ", str(fact), str(goal), str(f)])) return f else: return None elif fact.pred_name == 'cong': # Check if any pair of points in fact and goal are the same # (exchange is allowed) can_combine = False f_pairs = make_pairs(fact.args) g_pairs = make_pairs(goal.args) if any(self.equal_pair(p1, p2) for p1 in f_pairs for p2 in g_pairs): new_args = [] # type: List[str] for p1 in f_pairs: new_args.extend(p1) for p2 in g_pairs: if not any(self.equal_pair(p1, p2) for p1 in f_pairs): new_args.extend(p2) f = Fact('cong', new_args, updated=True, lemma="combine", cond=[fact, goal]) p_comb = make_pairs(new_args) f.left_map = get_indices(f_pairs, p_comb, self.equal_pair) f.right_map = get_indices(g_pairs, p_comb, self.equal_pair) return f else: return None elif fact.pred_name == 'para': # Check if any pair of points in fact and goal denote the same line can_combine = False f_pairs = make_pairs(fact.args) g_pairs = make_pairs(goal.args) if any(self.equal_line(p1, p2) for p1 in f_pairs for p2 in g_pairs): new_args = [] for p1 in f_pairs: new_args.extend(p1) for p2 in g_pairs: if not any(self.equal_line(p1, p2) for p1 in f_pairs): new_args.extend(p2) f = Fact('para', new_args, updated=True, lemma="combine", cond=[fact, goal]) p_comb = make_pairs(new_args) f.left_map = get_indices(f_pairs, p_comb, self.equal_line) f.right_map = get_indices(g_pairs, p_comb, self.equal_line) return f else: return None elif fact.pred_name in ('eqangle', 'eqratio'): # Check if any 4-tuple of points in fact and goal denote the same angle can_combine = False f_angles = make_pairs(fact.args, pair_len=4) g_angles = make_pairs(goal.args, pair_len=4) if any(self.equal_angle(a1, a2) for a1 in f_angles for a2 in g_angles): new_args = [] for a1 in f_angles: new_args.extend(a1) for a2 in g_angles: if not any(self.equal_angle(a1, a2) for a1 in f_angles): new_args.extend(a2) f = Fact(fact.pred_name, new_args, updated=True, lemma="combine", cond=[fact, goal]) p_comb = make_pairs(new_args, pair_len=4) f.left_map = get_indices(f_angles, p_comb, self.equal_angle) f.right_map = get_indices(g_angles, p_comb, self.equal_angle) # print("-----".join(["combined: ", str(fact), str(goal), str(f)])) return f else: return None elif fact.pred_name in ('simtri', 'contri'): f_tris = make_pairs(fact.args, pair_len=3) g_tris = make_pairs(goal.args, pair_len=3) for t1 in f_tris: for t2 in g_tris: if set(t1) == set(t2): order = [] for i in range(0, 3): for j in range(0, 3): if t1[i] == t2[j]: order.append(j) break new_args = [] for t1 in f_tris: new_args.extend(t1) for t2 in g_tris: if not any(set(t1) == set(t2) for t1 in f_tris): for i in range(0, 3): # print(order) new_args.append(t2[order[i]]) f = Fact(fact.pred_name, new_args, updated=True, lemma="combine", cond=[fact, goal]) p_comb = make_pairs(new_args, pair_len=3) f.left_map = get_indices(f_tris, p_comb, self.equal_triangle) f.right_map = get_indices(g_tris, p_comb, self.equal_triangle) return f return None elif fact.pred_name == 'midp': return None else: raise NotImplementedError def check_trivial(self, fact) -> bool: """Check whether the given fact is trivial.""" if fact.pred_name == 'cong': pairs = make_pairs(fact.args) for p1, p2 in itertools.permutations(pairs, 2): if self.equal_pair(p1, p2): return True return False elif fact.pred_name == 'para': pairs = make_pairs(fact.args) for p1, p2 in itertools.permutations(pairs, 2): # print(p1, p2) # print(self.get_line(p1), self.get_line(p2)) if self.equal_line(p1, p2): return True return False elif fact.pred_name in ('eqangle', 'eqratio'): angles = make_pairs(fact.args, pair_len=4) for a1, a2 in itertools.permutations(angles, 2): if self.equal_angle(a1, a2): return True return False return False def check_repetitive_char(self, fact) -> bool: if fact.pred_name in ("circle", "cyclic"): return len(set(fact.args)) < 4 if fact.pred_name in ("para", "cong", "perp"): args = fact.args return args[0] == args[1] or args[2] == args[3] or (args[0] + args[1] == args[2] + args[3]) if fact.pred_name in ("eqangle", "eqratio"): args = fact.args groups = make_pairs(args) for g in groups: if g[0] == g[1]: return True return args[0] + args[1] == args[2] + args[3] or args[4] + args[5] == args[6] + args[7] \ or (args[0] + args[1] == args[6] + args[7] and args[2] + args[3] == args[4] + args[5]) if fact.pred_name in ("simtri", "contri"): return len(set(fact.args[0:3])) < 3 or len(set(fact.args[3:6])) < 3 return False def check_imply(self, fact, goal) -> bool: """Check whether the given fact is able to imply the given goal.""" if fact.pred_name != goal.pred_name: return False if fact.pred_name == "perp": # Check the two lines are the same f1, f2 = make_pairs(fact.args) g1, g2 = make_pairs(goal.args) return self.equal_line(f1, g1) and self.equal_line(f2, g2) elif fact.pred_name == 'coll': # Whether points in goal is a subset of points in fact return set(goal.args).issubset(set(fact.args)) elif fact.pred_name == 'circle': # Whether the centers are the same, and other points in goal # is a subset of points in fact return fact.args[0] == goal.args[0] and set(goal.args[1:]).issubset(set(fact.args[1:])) elif fact.pred_name == 'cyclic': # Whether points in goal is a subset of points in fact return set(goal.args).issubset(set(fact.args)) elif fact.pred_name == 'cong': # Check whether both segments in goal are in fact. f_pairs = make_pairs(fact.args) g_pairs = make_pairs(goal.args) return all(any(self.equal_pair(f, g) for f in f_pairs) for g in g_pairs) elif fact.pred_name == 'para': # Check whether both lines in goal are in fact. f_pairs = make_pairs(fact.args) g_pairs = make_pairs(goal.args) # print(all(any(self.equal_line(f, g) for f in f_pairs) for g in g_pairs)) return all(any(self.equal_line(f, g) for f in f_pairs) for g in g_pairs) elif fact.pred_name in ("eqangle", "eqratio"): # Check whether both angles in goal are in fact. f_angles = make_pairs(fact.args, pair_len=4) g_angles = make_pairs(goal.args, pair_len=4) return all(any(self.equal_angle(f, g) for f in f_angles) for g in g_angles) elif fact.pred_name in ("simtri", "contri"): # Check whether both triangles in goal are in fact. f_tris = make_pairs(fact.args, pair_len=3) g_tris = make_pairs(goal.args, pair_len=3) return all(any(self.equal_triangle(f, g) for f in f_tris) for g in g_tris) elif fact.pred_name == "midp": return fact.args[0] == goal.args[0] and set(fact.args[1:]) == set(goal.args[1:]) else: # print(fact.pred_name) raise NotImplementedError def print_hyps(self, only_not_shadowed=False) -> None: s = "" count = 0 for category in self.classified_hyps.values(): if len(category) == 0: continue for fact in category: if only_not_shadowed and fact.shadowed: continue s = s + str(fact) + " ||| " count += 1 if only_not_shadowed: print("Current not shadowed hyps (" + str(count) + "): ") else: print("Current all hyps (" + str(count) + "): ") lines = len(s) // 200 if lines > 0: for line in range(0, lines): print(s[line * 200: line * 200 + 200]) print(s[lines * 200:-5]) else: print(s[:-5]) def print_search(self, res, show_combine=False) -> None: """Print the process of searching fixpoint. The given list of facts must contains all the deduce procedures (as parameters of facts in the list). Using a given ruleset to find out the name of rules used in deduce procedures. """ print_list = [] # type: List[Fact] def rec(fact): if fact in print_list: return for cond in fact.cond: rec(cond) print_list.append(fact) rec(res) for fact in print_list: if fact.lemma == 'combine': if show_combine: print('combine', fact) pass elif fact.lemma: print('(' + str(self.ruleset[fact.lemma]) + ')', fact, ':-', ', '.join(str(cond) for cond in fact.cond))
"""Unit test for expressions.""" import unittest from decimal import Decimal from fractions import Fraction import copy from logic import basic from integral import expr from integral.expr import Var, Const, Op, Fun, sin, cos, log, exp, Deriv, Integral, EvalAt, Symbol,\ VAR, CONST, OP, FUN, match, pi, Const from integral.parser import parse_expr basic.load_theory('transcendentals') class ExprTest(unittest.TestCase): def testPrintExpr(self): x, y, z = Var("x"), Var("y"), Var("z") test_data = [ (x, "x"), (Const(1), "1"), (Const(Decimal("1.1")), "11/10"), (Const((-1)), "-1"), (x + y, "x + y"), (x - y, "x - y"), (-x, "-x"), (x * y, "x * y"), (x / y, "x / y"), (x ^ y, "x ^ y"), ((x + y) * z, "(x + y) * z"), (x + (y * z), "x + y * z"), (x * y + z, "x * y + z"), (x * (y + z), "x * (y + z)"), (x + y + z, "x + y + z"), (x + (y + z), "x + (y + z)"), (x * (y ^ Const(2)), "x * y ^ 2"), ((x * y) ^ Const(2), "(x * y) ^ 2"), (-(x + y), "-(x + y)"), (x ^ Const(Fraction("1/2")), "x ^ (1/2)"), (-x + y, "-x + y"), (x - (x - y), "x - (x - y)"), (x - (x + y), "x - (x + y)"), (x / (x / y), "x / (x / y)"), (x / (x * y), "x / (x * y)"), (sin(x), "sin(x)"), (cos(x), "cos(x)"), (log(x), "log(x)"), (exp(x), "exp(x)"), (-x * exp(x), "-x * exp(x)"), (-(x * exp(x)), "-(x * exp(x))"), (sin(x ^ Const(2)), "sin(x ^ 2)"), (sin(x) * cos(x), "sin(x) * cos(x)"), (Deriv("x", Const(3) * x), "D x. 3 * x"), (Integral("x", Const(1), Const(2), Const(3) * x), "INT x:[1,2]. 3 * x"), (Deriv("x", Const(3) * x) * x, "(D x. 3 * x) * x"), (Integral("x", Const(1), Const(2), Const(3) * x) * x, "(INT x:[1,2]. 3 * x) * x"), (EvalAt("x", Const(1), Const(2), Const(3) * x), "[3 * x]_x=1,2"), (EvalAt("x", Const(1), Const(2), Const(3) * x) * x, "([3 * x]_x=1,2) * x"), ] for e, s in test_data: self.assertEqual(str(e), s) def testCompareExpr(self): x, y, z = Var("x"), Var("y"), Var("z") test_data = [ (x, y), (x, Const(3)), (Const(3), Const(4)), (Const(4), x * y), (x * y, x + y), (x * y, x * z), (x * y, z * y), (sin(x), x * y), (x * y, sin(sin(x))), (sin(x), Deriv("x", x)), (Deriv("x", x), Integral("x", Const(1), Const(2), x)), ] for s, t in test_data: self.assertTrue(s <= t) self.assertTrue(s < t) self.assertFalse(t <= s) self.assertFalse(t < s) def testNormalizeConstant(self): test_data = [ ("(3 + sqrt(2)) * (2 + sqrt(2))", "8 + 5 * sqrt(2)"), ("(3 + sqrt(2)) * (2 + sqrt(3))", "6 + 2 * sqrt(2) + sqrt(2) * sqrt(3) + 3 * sqrt(3)"), ("sqrt(8)", "2 * sqrt(2)"), ("sqrt(8) + 3 * sqrt(2)", "5 * sqrt(2)"), ("sqrt(18)", "3 * sqrt(2)"), ("sqrt(18) + 2 * sqrt(2)", "5 * sqrt(2)"), ("2 ^ (1/2) * 2 ^ (1/3)", "2 ^ (5/6)"), ("(-9)^(1/3)", "-(3 ^ (2/3))"), ("(-8)^(2/3)", "-4"), ("0 ^ 5", "0"), ("sqrt(8) / sqrt(10)", "2/5 * sqrt(5)"), ("sqrt(8) / (1 + sqrt(10))", "2 * sqrt(2) * (1 + sqrt(2) * sqrt(5)) ^ -1"), ("sqrt(8) ^ 2", "8"), ("(3 + sqrt(2)) ^ 2", "11 + 6 * sqrt(2)"), ("(3 + sqrt(2)) ^ 3", "45 + 29 * sqrt(2)"), ("(3 + sqrt(2)) ^ -1", "(3 + sqrt(2)) ^ -1"), ("pi / 2 - pi / 3", "1/6 * pi"), ("exp(0)", "1"), ("exp(2) * exp(3)", "exp(5)"), ("exp(pi) * exp(3)", "exp(3) * exp(pi)"), ("log(1)", "0"), ("log(2)", "log(2)"), ("log(exp(2))", "2"), ("log(6)", "log(2) + log(3)"), ("log(8)", "3 * log(2)"), ("log(1/2)", "-log(2)"), ("log(9/10)", "-log(2) + 2 * log(3) + -log(5)"), ("sin(pi/4)", "1/2 * sqrt(2)"), ("sin(pi/4) * sqrt(2)", "1"), ("sin(5*pi/4)", "-1/2 * sqrt(2)"), ("sin(9*pi/4)", "1/2 * sqrt(2)"), ("sin(-5*pi/4)", "1/2 * sqrt(2)"), ("cos(5*pi/3)", "1/2"), ("cos(4*pi/3)", "-1/2"), ("atan(1)", "1/4 * pi"), ("abs(-2)", "2"), ("sqrt(1 - 1)", "0"), ("sqrt(2 + 1/4)", "3/2"), ("sin(2 * pi)", "0"), ("cos(2 * pi)", "1"), ("sin((2 + 3/4) * pi)", "1/2 * sqrt(2)"), ("(39 * (pi / 100)) / 2", "39/200 * pi"), ("cos((39 * (pi / 100)) / 2)", "cos(39/200 * pi)") ] for s, res in test_data: t = parse_expr(s) self.assertEqual(str(t.normalize_constant()), res) def testNormalizeConstantTrig(self): table = expr.trig_table() for func_name in ('sin', 'cos', 'tan', 'cot', 'csc', 'sec'): for k, v in table[func_name].items(): self.assertEqual(Fun(func_name, k).normalize_constant(), v) inv_table = expr.inverse_trig_table() for func_name in ('asin', 'acos', 'atan', 'acot', 'acsc', 'asec'): for k, v in inv_table[func_name].items(): self.assertEqual(Fun(func_name, k).normalize_constant(), v) def testNormalize(self): test_data = [ ("2 + 3", "5"), ("x + 0", "x"), ("2 * 3", "6"), ("1 + 1/3", "4/3"), ("2 + 3 * x + 4", "6 + 3 * x"), ("0 / (x + y)", "0"), ("2 + x / y + 2 * (x / y) + 3", "5 + 3 * x * y ^ -1"), ("(x + y) ^ 2", "(x + y) ^ 2"), ("x^(1.5)","x ^ (3/2)"), ("(x + y) * (x - y)", "x ^ 2 + -(y ^ 2)"), ("[x]_x=a,b", "-a + b"), ("[x ^ 2 * y]_x=a,b", "-(a ^ 2 * y) + b ^ 2 * y"), ("[x ^ 2]_x=3,4", "7"), ("cos(x ^ 2)", "cos(x ^ 2)"), ("cos(pi/4)", "1/2 * sqrt(2)"), ("-(-x)", "x"), ("cos(0) - cos(pi/4)", "1 + -1/2 * sqrt(2)"), ("cos(0) - cos(pi/2)", "1"), ("([x]_x=a,b) + 2 * ([x ^ 2 / 2]_x=a,b) + [x ^ 3 / 3]_x=a,b", "-a + -(a ^ 2) + -1/3 * a ^ 3 + b + b ^ 2 + 1/3 * b ^ 3"), ("x ^ (1/2) * x ^ (1/2) ", "x"), ("2 * (1 + 3)", "8"), ("atan(1)", "1/4 * pi"), ("atan(sqrt(3)/3)", "1/6 * pi"), ("atan(sqrt(3))", "1/3 * pi"), ("sin(3/4 * pi)", "1/2 * sqrt(2)"), ("pi + pi / 3", "4/3 * pi"), ("1 - cos(x) ^ 2", "1 + -(cos(x) ^ 2)"), ("x^2 * 6", "6 * x ^ 2"), ("(x * y)^2", "x ^ 2 * y ^ 2"), ("(2*sin(x))^2", "4 * sin(x) ^ 2"), ("(2^(1/2)*sin(x))^(2)", "2 * sin(x) ^ 2"), ("2 * 8 ^ (1/2) * 1 * cos(t) ^ 2", "4 * sqrt(2) * cos(t) ^ 2"), ("8 ^ (1/2) * cos(t) ^ 2 * 1", "2 * sqrt(2) * cos(t) ^ 2"), ("1/3 * 3 ^ 3", "9"), ("(-1) * (1/3 * 2 ^ 3)", "-8/3"), ("5 + (1/3 * 3 ^ 3 + (-1) * (1/3 * 2 ^ 3))", "34/3"), ("2 * 8 ^ (1/2) * (1/2)", "2 * sqrt(2)"), ("x / sqrt(5 - 4 * x)", "x * (5 + -4 * x) ^ (-1/2)"), ("1/(1+sqrt(x))", "(1 + sqrt(x)) ^ -1"), ("log(2) - log(3)", "log(2) + -log(3)"), ("(3 * x + 1) ^ -2", "(1 + 3 * x) ^ -2"), ("-u/2","-1/2 * u"), ("exp(-u/2)", "exp(-1/2 * u)"), ("log(exp(2))", "2"), ("log(x^2)", "2 * log(x)"), ("sqrt(cos(x) - cos(x)^3)", "sqrt(cos(x) + -(cos(x) ^ 3))"), ("sqrt(cos(x) * (1 - cos(x)^2))", "sqrt(cos(x) + -(cos(x) ^ 3))"), ("1/2 * u ^ ((-1)) * 2 * u", "1"), ("1/2 * u ^ ((-1)) * (2 * u / (1 + u ^ (2)))", "(1 + u ^ 2) ^ -1"), ("[log(1 + u ^ 2)]_u=-1,1", "0"), # ("sqrt(x ^ 2)", "abs(x)"), ("[abs(x)]_x=-2,3", "1"), # ("abs(sqrt(3) / 2) / 2", "1/4 * 3 ^ (1/2)"), # ("abs(sqrt(3) / 2) / abs(sqrt(2) / 2)", "6 ^ (1/2) / 2"), # ("([log(abs(u))]_u=1/2 * 2 ^ (1/2),1/2 * 3 ^ (1/2))", "-log(2 ^ (1/2) * (1/2)) + log(3 ^ (1/2) * (1/2))"), ("exp(1)", "exp(1)"), ("[exp(u) * sin(u)]_u=0,1", "exp(1) * sin(1)"), ("exp(1) ^ 2", "exp(2)"), ("cos(acos(u)) ^ 2 ", "u ^ 2"), ("log(exp(t)) ^ (-2)", "t ^ -2"), ("log(6^(1/2))", "1/2 * log(2) + 1/2 * log(3)"), ("log(6*pi)", "log(2) + log(3) + log(pi)"), ("exp(-t) * exp(t)", "1"), ("(u ^ (-2) * exp(u)) * exp(-u)", "u ^ -2"), ("[u ^ 8 / 8]_u=-3,3", "0"), # ("(1 - exp(-x)) / (1 - exp(-x))", "1"), # ("sin(sqrt(x ^ 2))", "sin(abs(x))"), # ("sqrt((u/pi)^2)", "abs(u / pi)"), # ("sin(sqrt((u/pi)^2))", "sin(abs(u / pi))"), ("u*pi^(-1) * (u/pi)^(-1)", "1"), ("(2 * u) * pi ^ (-1) *(1/pi)^(-1)", "2 * u"), ("((2 * u) * pi ^ (-1)) * (u / pi) ^ (-1)", "2"), ("2 * (INT x:[1,exp(1)]. 1) - ([u * log(u)]_u=2,2 * exp(1))", "-2 * exp(1) + -2 * exp(1) * log(2) + 2 * log(2) + 2 * (INT x:[1,exp(1)]. 1)"), ("3 ^ (1/2) * 3 ^ (1/2)", "3"), ("2 * ((1/2) * 3 ^ (1/2))", "sqrt(3)"), ("exp(5 * x) * 3 / exp(3 * x)", "3 * exp(2 * x)"), ("exp(5 * x) * exp(2 * x) / 7", "1/7 * exp(7 * x)"), ("(exp(4 * x) - 1) * exp(4 * x) ", "-exp(4 * x) + exp(8 * x)"), ("(-u + 1) ^ 3 * (1 - u) ^ 2 ^ (-1)", "1 + -u"), ("2 * (-((1/2) * -(3 ^ (1/2))) + 1)", "2 + sqrt(3)"), ("1/2 * (-2 * (INT t:[0,(-1)/2]. exp(t)))", "-(INT t:[0,-1/2]. exp(t))"), ("(cos(x)^4 * sin(x) ^ 2) / -(sin(x))", "-(cos(x) ^ 4 * sin(x))"), ("2 ^ (1/2) ^ 6 / 6", "4/3"), # ("sin(x) ^ 2 * csc(x) ^ 3", "csc(x)"), # ("sin(x) ^ 3 * csc(x) ^ 2", "sin(x)"), ("1 / (2 - sqrt(3))", "(2 + -sqrt(3)) ^ -1"), ("x ^ (1/2) * x ^ (1/3)", "x ^ (5/6)"), ("sqrt(x ^ 2)", "abs(x)"), ("sqrt(2 * x ^ 2)", "sqrt(2) * abs(x)"), ("sqrt(2 * cos(x) ^ 2)", "sqrt(2) * abs(cos(x))"), ("(2 * x^2) ^ (3/2)", "2 * sqrt(2) * abs(x) ^ 3"), ("-(11/21) + 2/3 * 0 ^ 6 + 1/7 * 0 ^ 7", "-11/21"), ("abs (2 + exp(2))", "2 + exp(2)"), ("abs (2 - exp(2))", "-2 + exp(2)"), ("exp (log(2))", "2"), ] for s, res in test_data: t = parse_expr(s) self.assertEqual(str(t.normalize()), res) def testGetSubExpr(self): test_data = [ ("x + y", "0", "x"), ("x + y", "1", "y"), ("x + y + z", "0.0", "x"), ("x + y + z", "0.1", "y"), ("x + sin(x)", "1", "sin(x)"), ("x + sin(x)", "1.0", "x"), ("[sin(x)]_x=2,3", "0", "sin(x)"), ("[sin(x)]_x=2,3", "1", "2"), ("[sin(x) * cos(x)]_x=2,3", "0.1", "cos(x)"), ("D x. 3 * x", "0", "3 * x"), ("D x. 3 * x", "0.1", "x"), ("INT x:[1,2]. 3 * x", "0", "3 * x"), ("INT x:[1,2]. 3 * x", "0.1", "x"), ("INT u:[0,pi / 2]. sqrt(1 - sin(u) ^ 2) * cos(u)","0.1.0", "u") ] for s, loc, res in test_data: t = parse_expr(s) res = parse_expr(res) self.assertEqual(t.get_subexpr(loc), res) def testReplace(self): test_data = [ ("1 / (x ^ 2 + 1)", "x ^ 2 + 1", "u", "1 / u"), ("(3 * x + 1) ^ -2", "3 * x + 1", "u", "u ^ -2"), ("(x + y) * (x + y + z)", "x + y", "u", "u * (u + z)"), ] for s, e, repl_e, res in test_data: s = parse_expr(s) e = parse_expr(e) repl_e = parse_expr(repl_e) res = parse_expr(res) self.assertEqual(s.replace(e, repl_e), res) def testReplace1(self): test_data = [ ("x ^ 4", "x ^ 2", "u", "u ^ 2"), ("1/2 * x ^ ((-1)/2)", "x ^ (1/2)", "u", "1/2 * u ^ (-1)") ] for s, e, repl_e, res in test_data: s = parse_expr(s) e = parse_expr(e) repl_e = parse_expr(repl_e) res = parse_expr(res) self.assertEqual(s.replace_trig(e, repl_e), res) def testDeriv(self): test_data = [ ("1", "0"), ("x", "1"), ("2 * x", "2"), ("x ^ 2", "2 * x"), ("x * y", "y"), ("1 / x", "-1 / x ^ 2"), ("3 * x + 1", "3"), ("x + pi / 3", "1"), ("2 * x + pi / 3", "2"), ("sin(x)", "cos(x)"), ("sin(x^2)", "2 * x * cos(x ^ 2)"), ("cos(x)", "-sin(x)"), ("log(x)", "x ^ -1"), ("x * log(x)", "1 + log(x)"), ("exp(x)", "exp(x)"), ("exp(x^2)", "2 * x * exp(x ^ 2)"), ] for s, s2 in test_data: s = parse_expr(s) self.assertEqual(str(expr.deriv("x", s)), s2) def testSeparateIntegral(self): test_data = [ ("((-1))*(INT x:[a, b].x+1) + (INT x:[a, b].1) + 3", {"INT x:[a,b]. x + 1", "INT x:[a,b]. 1"}) ] for s, s2 in test_data: t = parse_expr(s).separate_integral() for i in range(len(t)): t[i] = str(t[i][0]) self.assertEqual(set(t), s2) def testConstant(self): test_data = [ ("1", True), ("x", False), ("sin(pi/5)", True), ("sqrt(2)", True), ("2^(1/2)", True), ("1 + sqrt(3)/2", True), ("2 - 2^(1/2) / 3", True), ("x ^ (1/2)", False), ("sin(x)", False), ("2 * 8 ^ (1/2) * (1/2)", True) ] for s, s2 in test_data: s = parse_expr(s) self.assertEqual(s.is_constant(), s2) # def testGetAbsByMonomial(self): # test_data = [ # ("x * abs(x)", "abs(x)"), # ("sqrt(cos(x)) * abs(sin(x))", "abs(sin(x))"), # ("abs(x) * abs(y)", "abs(x) * abs(y)") # ] # for s, s2 in test_data: # s = parse_expr(s) # # s2[i] = parse_expr(s2[i]) # print(s.getAbsByMonomial()) # # self.assertEqual(s.getAbsByMonomial(), tuple(s2)) def testGetAbs(self): test_data = [ ("2 * u / (1 + abs(u))", ["abs(u)"]), ("t * (4 + abs(t)) ^ -1 * abs(t ^ -1)", ["abs(t)", "abs(t ^ -1)"]) ] for s, s1 in test_data: s = parse_expr(s) for i in range(len(s1)): s1[i] = parse_expr(s1[i]) self.assertEqual(s.getAbs(), s1) def testPriority(self): x = parse_expr("x") test_data = [ (Const(1) + (x ^ Const(2)), "1 + x^2"), ] for s, s2 in test_data: self.assertEqual(s, parse_expr(s2)) def testReplaceExpr(self): test_data = [ ("x + y", "1", "x + y", "x + (x + y)"), ("x + y + z", "0.1", "sin(x)", "x + sin(x) + z"), ("x + 2", "", "x + 1 + 1", "x + 1 + 1"), ("sin(x) ^ 2 * sin(x) + sin(x) ^ 2", "0.0", "1 - cos(x) ^ 2", "(1 - cos(x) ^ 2) * sin(x) + sin(x) ^ 2"), ("INT u:[0,pi / 2]. sqrt(1 - sin(u) ^ 2) * cos(u)", "0.0.0", "cos(u) ^ 2", "INT u:[0,pi / 2]. sqrt(cos(u) ^ 2) * cos(u)") ] for s, s1, s2, s3 in test_data: s = parse_expr(s) s2 = parse_expr(s2) s3 = parse_expr(s3) self.assertEqual(s.replace_expr(s1, s2), s3) def testGetLocation(self): test_data = [ ("$x$ + y", "0"), ("$x + y$", ''), ("$sin(x)^2$*sin(x)", "0"), ("INT x:[0, 1]. $sin(x)$ + x - 1", "0.0.0") ] for s, s1 in test_data: s = parse_expr(s) self.assertEqual(s.get_location(), s1) def testMatching(self): a = Symbol('a', [CONST]) b = Symbol('b', [CONST]) x = Symbol('x', [VAR]) y = Symbol('y', [VAR, OP, FUN]) test_data = [ ('x - 1', x - a, {x: Var('x'), a: Const(1)}), ('x - 2', x - Const(2), {x: Var('x')}), ('x + 3', x - b, None), ('x', x + a, None), ('3*x', a * x, {a: Const(3), x: Var('x')}), ('3 * x + 5', a * x + b, {a: Const(3), x: Var('x'), b: Const(5)}), ('2 * x + 3', a * x + a, None), ('x ^ 2', x ^ Const(2), {x: Var('x')}), ('x ^ 3 - 2', x ^ Const(3), None), ('1 - x ^ 2', a - (x ^ Const(2)), {a: Const(1), x: Var('x')}), ('cos(x) ^ 2', cos(x) ^ Const(2), {x: Var('x')}), ('(1 - x ^ 2) ^ (1/2)', (Const(1) - (x ^ Const(2)))^(Const(Fraction(1/2))), {x: Var('x')}), ('(1 - x ^ 3) ^ (1/2)', (Const(1) - (x ^ Const(2)))^(Const(Fraction(1/2))), None), ('(1 - 2 * sin(x) ^ 2) ^ (1/2)', (b - a * (sin(x) ^ Const(2)))^Const(Fraction(1/2)), {b: Const(1), a: Const(2), x: Var('x')}), ('sin(x) ^ 2 + cos(y)^2', (sin(x)^Const(2))+(cos(x)^Const(2)), None), ('sin(2*x+1)^2 + cos(2*x+1) ^ 2', (sin(y)^Const(2))+(cos(y)^Const(2)), {y: Op("+",Op("*",Const(2),Var('x')),Const(1))}), ('2*pi', a * pi, {a: Const(2)}), ] for r1, r2, r3 in test_data: self.assertEqual(match(parse_expr(r1), r2), r3) def testExpandPower(self): test_data = [ ("(x+y)^2", "2*x*y + x^2 + y^2"), ("(x-1)^2", "(1 - 2*x) + x^2"), ("1 + (exp(x) + 2*x)^2", "1 + (4 * x * exp(x) + 4 * x ^ 2 + exp(2 * x))"), ("2 * u + (u - 1) ^ 2 + 3", "4 + u^2"), ] for v, v_res in test_data: v = parse_expr(v) v_res = parse_expr(v_res) self.assertEqual(v.expand().normalize(), v_res.normalize()) def testNormalize1(self): test_data = [ ('x', 'x'), ("2 + 3", "5"), ("x + 0", "x"), ("2 * 3", "6"), ("1 + 1/3", "4/3"), ("2 + 3 * x + 4", "6 + 3 * x"), (" 0 / (x + y)", "0"), ("2 + x / y + 2 * (x / y) + 3", "5 + 3 * x * y ^ -1"), ("(x + y) ^ 2", "(x + y) ^ 2"), ("x^(1.5)","x ^ (3/2)"), ("(x + y) * (x - y)", "x ^ 2 + -(y ^ 2)"), ("[x]_x=a,b", "-a + b"), ("[x ^ 2 * y]_x=a,b", "-(a ^ 2 * y) + b ^ 2 * y"), ("[x ^ 2]_x=3,4", "7"), ("-(-x)", "x"), ("(x*y)^2", "x ^ 2 * y ^ 2"), ("(x/y)^2", "x ^ 2 * y ^ -2"), ("exp(2*x)^2", "exp(4 * x)"), ("exp(3*x)*exp((1/2)*x)", "exp(7/2 * x)"), ("exp(2*x)^(-1)", "exp(-2 * x)"), ("pi/2-pi/3", "1/6 * pi"), ("(3/4)^(-1)", "4/3"), ("3 ^ (1/2) * 2 ^ -1","1/2 * sqrt(3)"), ("sin(pi/4)", "1/2 * sqrt(2)"), ("sin(4/pi)", "sin(4 * pi ^ -1)"), ("pi*pi", "pi ^ 2"), ("(1/4) * pi * (1/2)", "1/8 * pi"), ("pi/2 - pi/3", "1/6 * pi"), ("(-1)*(3^(-1))", "-1/3"), # ("1 / (2 * (u ^ 2 + 1))", "1/2 * (1 + u ^ 2) ^ -1"), # ("(1 + x) * 1/(2*(1 + x))", "1/2"), # ("1/(1+x) * (1+x)", "1"), # ("(1+x) * (1+x)^(-1)", "1"), # ("(2+x)*(x+3)/(3+x)^2", "(2 + x) * (3 + x) ^ -1"), # ("(2+x)*(x+3)^3/(3+x)^2", "(2 + x) * (3 + x)") ("2 * exp(2) + -1 * exp(2)", "exp(2)"), ("2 * exp(2) + exp(-1) + -1 * ([exp(x)]_x=-1,2)", "2 * exp(-1) + exp(2)") ] for v, v_res in test_data: v = parse_expr(v) self.assertEqual(str(v.normalize()), v_res) def testUnivariatePolynomial(self): test_data = [ ("1", True), ("x - 1", True), ("x*y", False), ("x - y + z", False), ("x^2 + 1", True), ("1 + 2 * x - x ^ 2 + x ^ 4", True), ("x*(x - 1) ^ (-1)", True), ("(x^2+1)/(y-1)", False), ("(1-sin(x)^2)/(1+sin(x))", True), ("(cos(x)^2+1)/(sin(x))", False) ] for v, v_res in test_data: v = parse_expr(v) self.assertEqual(v.is_univariate(), v_res) def testSimplifyConstant(self): pass if __name__ == "__main__": unittest.main()
print('My name is') for i in range(5): print("Jimmy Five Times" + str(i)) #in the range function 1 parametr will go from i to the parameter. If there are 2 aeguments the loop will start at the first argument and go to the second argument but not invludr it in theout out. If there are 3 arguments, it starts at the first argument, goes to the second arguments, and the third argument is how much the loop iterates. if the 3rd arguments is 2 the loop iterates by 2. Same goes for negative numbers/
#!/usr/local/bin/python """Produce a one-time password response to a random-number challenge, with respect to a secret, shared DES encryption key. The user must present their PIN, with which they have encrypted their DES key, and the challenge. (The first time, the user is prompted for the PIN and the key itself, which is stashed in encrypted form in a ~/.<scriptname> dot file.) The one-time password response is produced on stdout. Note that you could deal with multiple keys by using different names for this script. It would be much wiser to elaborate the storage structure for the key file, of course... Originally by Ken Manheimer, ken.manheimer@nist.gov""" version = "$Revision: 17 $" import sys, os, string try: import des except ImportError: raise error, "cannot operate without kuchling's des extension module" # x> keyFile = os.path.expanduser('~/.' + os.path.basename(sys.argv[0])) pin = '' def get_key_file(keyFile): """Return a file object containing the encrypted key.""" if not os.path.exists(keyFile): return None # ===> else: return open(keyFile) def get_key(kf): """Get key (decrypting it with PIN) from KEYFILE.""" pin = get_pin('pin for decoding key: ') return des.new(pin, des.ECB).decrypt(kf.read()) # ===> def get_challenge(): """Get challenge as an 8 character string.""" print "Challenge: ", chal = sys.stdin.readline()[:-1] # pad with nulls for encryption, limit to 8 chars return (chal + ('\000' * (8 - len(chal))))[:8] def get_pin(msg): """Return designated PIN, soliciting it if not previously specified.""" global pin if pin: return pin # ===> print msg,; sys.stdout.flush() pin = sys.stdin.readline()[:-1] if len(pin) > 8: pin = pin[:8] elif len(pin) < 8: pin = pin + ('0' * (8 - len(pin))) return pin def create_key_file(key = None): """Initiate a keyfile, containing key encrypted with pin.""" print ('No ~/.%s key stash file - getting pin and key to create it.' % os.path.basename(sys.argv[0])) try: # Establish empty file object: fp = open(keyFile, 'w'); fp.write(''); fp.close() # Obtain the key: pin = get_pin('pin (8 chars or less; ' + 'used to encrypt key for file storage): ') # Obtain the octal key octet: if not key: done = 0 key = [''] * 8 while not done: print 'Enter key, as 8 octal numbers', print " (you'll be able to review and correct it)" for i in range(8): print 'octet %d [%s]: ' % (i + 1, key[i]),; sys.stdout.flush() new = sys.stdin.readline() sys.stdin.flush() if not new: print '<eof>' sys.exit(1) elif len(new) > 1: key[i] = new[:-1] print '' print 'got [', for i in range(8): print str(key[i]), ' ', print ']' print 'Ok? [Y,n] ', sys.stdout.flush() resp = sys.stdin.readline()[:-1] if resp in ['', 'Y', 'y']: done = 1 else: print ("Try again (empty lines take old, " + "enter 'y' at end to accept)") # Convert to char bits, stripping low order bits of each byte: keyStr = '' for i in key: keyStr = keyStr + chr(((eval('0' + i))>>1)<<1) # encrypt for stashing in the file: o = des.new(pin, des.ECB) # And stash it: fp = open(keyFile, 'w') fp.write(o.encrypt(keyStr)) fp.close() except: wasExc = (sys.exc_type, sys.exc_value) if fp: try: fp.close() except: pass try: os.unlink(fp.name) except: pass print 'Abandoning key file creation...' raise error, 'Abandoned keyfile creation: ' + str(wasExc) return 0 # ===> def set_key(fp, key, pin, key): """Stash the key in the key file.""" fp.seek(0) cryObj = des.new(pin, des.ECB) fp.writeline(cryObj.encrypt(key)) def chars2hex(str): """Transform STRING of chars to the corresponding hex digit pairs.""" s = '' for i in range(len(str)): both = ord(str[i]) high = both>>4 low = both - (high<<4) s = s + hex(high)[2:] + hex(low)[2:] return s def massage_result(rawResult): """Convert raw encrypted result to digital pathways form.""" result = '' for c in chars2hex(rawResult)[:8]: if c in ['a', 'b', 'c']: result = result + '2' elif c in ['d', 'e', 'f']: result = result + '3' else: result = result + c return result if __name__ == '__main__': kf = get_key_file(keyFile) if not kf: create_key_file() kf = get_key_file(keyFile) if not kf: raise error, 'failed to establish key file' # xxx> key = get_key(kf) chal = get_challenge() # get challenge as char data o = des.new(key, des.ECB) print massage_result(o.encrypt(chal))
movies = { "Monty Python and the Holy Grail": "Great", "Monty Python's Life of Brian": "Good", "Monty Python's Meaning of Life": "Okay" } print movies.items() """Call the appropriate method on movies such that it will print out all the items in the dictionary, each key and each value."""
to_21 = range(1, 22) odds = to_21[::2] middle_third = to_21[7:14] print to_21 print odds print middle_third """Create a list, to_21, that's just the numbers from 1 to 21, inclusive.Create a second list, odds, that contains only the odd numbers in the to_21 list (1, 3, 5, and so on). Use list slicing for this one instead of a list comprehension.Finally, create a third list, middle_third, that's equal to the middle third of to_21, from 8 to 14, inclusive"""
height = int(input('請輸入身高(cm):')) weight = input('請輸入體重(kg):') weight = int(weight) height = height / 100 #公尺轉換 bmi = weight / height ** 2 if bmi < 18.5: print('你的bmi值',bmi,'體重過輕') elif bmi >= 18.5 and bmi < 24: print('你的bmi值',bmi,'正常') elif bmi >= 24 and bmi < 27: print('你的bmi值',bmi,'稍重') elif bmi >= 27 and bmi < 30: print('你的bmi值',bmi,'輕度肥胖') elif bmi >= 18.5 and bmi < 35: print('你的bmi值',bmi,'中度肥胖') else: print('你的bmi值',bmi,'重度肥胖')
""" This module contains classes for creating refinement plans that can be optimized. """ from mystic import models class BasePlan(models.AbstractFunction): """ This class describes a refinement plan to optimize. Users should implement their own subclass of this class. There are several key functions to this class. The ``BasePlan.initialize`` is a function that is executed once when an instance of the class is initialized. This is useful for doing things that require a one-time setup. For example, reading data files, phase files, or setting up directories. The ``BasePlan.compute`` should implement the cost function to be minimized. It should return a single ``float`` that is used by the solver to find the mimima. Attributes ---------- idxs : dict A ``dict`` with key parameter and value index of parameter. E.g. ``{"x" : 1, "y" : 2}``. This corresponds to the index of the parameter given in ``names``. _p : list A list of the latest parameters sent to the optimized function. The list should be indexed by ``idxs``. Parameters ---------- names : list A ``list`` of parameter names. E.g. ``["x", "y"]``. """ def __init__(self, names, initialize=True): super().__init__(ndim=len(names)) # store map to parameters self.idxs = {name : i for i, name in enumerate(names)} self._p = None # setup initial porition of refinement plan if initialize: self.initialize() def initialize(self): """ Function called once before optimization. """ pass def function(self, p): """ Function used by Mystic for optimization. Parameters ---------- p : list A `list` of the floating-point values. Returns ------- float The value of the evaluated cost function. """ self._p = p return self.compute() def compute(self): """ Function to be optimized. Returns ------- float The value of the evaluated cost function. """ raise NotImplementedError("Plan does not have a compute function!") def constraint(self, p): """ Applies constraints. Parameters ---------- p : list A `list` of the floating-point values. Returns ------- p : list A `list` of the floating-point values. """ return p def get(self, name): """ Helper function for returning the value of the variable. Parameters ---------- p : list A `list` of the floating-point values. name : str Name of the parameter to query. Returns ------- float The floating-point value for the variable. """ return self._p[self.idxs[name]]
"""Kaprekar Numbers, by Al Sweigart al@inventwithpython.com Kaprekar Numbers are numbers whose square in that base can be split into 2 parts that add up to the original number. For example: 45^2 = 2025 -> 20 + 25 = 45 More info at: https://en.wikipedia.org/wiki/Kaprekar_number This and other games are available at https://nostarch.com/XX Tags: tiny, math, scrolling""" __version__ = 0 import sys print("""Kaprekar Numbers, by Al Sweigart al@inventwithpython.com Kaprekar Numbers are numbers whose square can be split into 2 parts that add up to the original number. For example: 45^2 = 2025 -> 20 + 25 = 45""") print('What number do you wish to start searching from? (min. 4)') while True: # Keep looping until the user enters a number > 3. response = input('> ') if response.isdecimal() and int(response) > 3: break print('Please enter a number 4 or greater.') number = int(response) - 1 print('Ctrl-C will stop the program.') input('Press Enter to begin...') print('Calculating Kraprekar numbers...') foundKraprekarNumbers = [] try: while True: # Main program loop. number += 1 square = str(number * number) # Split the square into two parts: firstPart = square[0:len(square) // 2] secondPart = square[len(square) // 2:] # Check if their sum is the original number: if int(firstPart) + int(secondPart) == number: foundKraprekarNumbers.append(number) print(str(number) + '^2 =', square, '->', firstPart, '+', secondPart, '=', str(number)) continue if len(square) % 2 == 0: continue # Split the square into two parts: firstPart = square[0:len(square) // 2 + 1] secondPart = square[len(square) // 2 + 1:] # Check if their sum is the original number: if int(firstPart) + int(secondPart) == number: foundKraprekarNumbers.append(number) print(str(number) + '^2 =', square, '->', firstPart, '+', secondPart, '=', str(number)) continue except KeyboardInterrupt: sys.exit() # When Ctrl-C is pressed, end the program.
#!/usr/bin/env python3 import csv from tkinter import * ########################### # CSV data extraction ########################### suburbList = [] streetList = [] with open('/Users/madurasenadeera/github/BCC_waste_collection_days/data/Waste Collection Days.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) for values in csv_reader: suburbList.append(values[8]) # compiles column of suburbs into one list streetList.append(values[5]) suburbs = list(dict.fromkeys(suburbList)) # removes duplicate suburbs streets = list(dict.fromkeys(streetList)) lista = suburbs # IMPORTING SUBURBS listb = streets ########################### # FINDING ADDRESS ########################### def searchProperty(): # importing csv information, 'r' denotes the reading of the file with open('/Users/madurasenadeera/github/BCC_waste_collection_days/data/Waste Collection Days.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) number = numberEntry.get() # pulling information from GUI entry boxes street = streetEntry.get() suburb = suburbEntry.get() for line in csv_reader: # for-loop to filter through data from CSV file # line[8]: # comparing entered info with data if ((line[3] == number) and (line[5] == street.upper()) and (line[8] == suburb.upper())): searchLabel["text"] = line[1] # print out bin day info else: #searchLabel["text"] = "Invalid Address" pass # need to add functionality to tell user that the address is not valid ########################### # TEXT AUTOCOMPLETE FUNCTION ########################### class AutocompleteEntry(Entry): def __init__(self, lista, *args, **kwargs): Entry.__init__(self, *args, **kwargs) self.lista = lista self.var = self["textvariable"] if self.var == '': self.var = self["textvariable"] = StringVar() self.var.trace('w', self.changed) self.bind("<Right>", self.selection) self.bind("<Up>", self.up) self.bind("<Down>", self.down) self.lb_up = False def changed(self, name, index, mode): if self.var.get() == '': self.lb.destroy() self.lb_up = False else: words = self.comparison() if words: if not self.lb_up: self.lb = Listbox() self.lb.bind("<Double-Button-1>", self.selection) self.lb.bind("<Right>", self.selection) self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height()) self.lb_up = True self.lb.delete(0, END) for w in words: self.lb.insert(END, w) else: if self.lb_up: self.lb.destroy() self.lb_up = False def selection(self, event): if self.lb_up: self.var.set(self.lb.get(ACTIVE)) self.lb.destroy() self.lb_up = False self.icursor(END) def up(self, event): if self.lb_up: if self.lb.curselection() == (): index = '0' else: index = self.lb.curselection()[0] if index != '0': self.lb.selection_clear(first=index) index = str(int(index)-1) self.lb.selection_set(first=index) self.lb.activate(index) def down(self, event): if self.lb_up: if self.lb.curselection() == (): index = '0' else: index = self.lb.curselection()[0] if index != END: self.lb.selection_clear(first=index) index = str(int(index)+1) self.lb.selection_set(first=index) self.lb.activate(index) def comparison(self): test = self.var.get() # retreives user inputted information from textbox pattern = re.compile('.*' + test.upper() + '.*') # comparing upper case value return [w for w in self.lista if re.match(pattern, w)] ########################### # TKINTER GUI ########################### window = Tk() window.title("BCC Waste Collection") label = Label(window, text="Waste Collection Day").pack() # GUI title # suburb entry box suburbLabel = Label(window, text="Suburb").pack() suburbEntry = AutocompleteEntry(lista, window) suburbEntry.pack() # street name entry box streetLabel = Label(window, text="Street").pack() streetEntry = AutocompleteEntry(listb, window) streetEntry.pack() # street number entry box numberLabel = Label(window, text="House number").pack() numberEntry = Entry(window) numberEntry.pack() # search button searchButton = Button(window, text="Search", command=searchProperty).pack() # entry space to displace bin day searchLabel = Label(window) searchLabel.pack() frame = Frame(window) frame.pack() window.mainloop()
# default parameter only make at the end of the function # for example :-> def reet(name,last,age=23) def reet(FirstName,LastNAme,Age): # normal parameter passing in function print(f"your first name is {FirstName}") print(f"your last name is {LastNAme}") print(f"your age is {Age}") reet("tanmay","bansal",21) def neet(FirstName1,LastNAme1,Age1=20): # default parameter passing in function in which 21 is overwrite on 20 print(f"your first name is {FirstName1}") print(f"your last name is {LastNAme1}") print(f"your age is {Age1}") neet("tanmay","bansal",21) def reet2(FirstName2,LastNAme2,Age2=None): # default parameter passing in function in which age can not contain value print(f"your first name is {FirstName2}") print(f"your last name is {LastNAme2}") print(f"your age is {Age2}") reet2("tanmay","bansal",) #def reet3(FirstName3,LastNAme3=None,Age3): # wronge it through the error we can't use a value containe parameter after none or default parameter #print(f"your first name is {FirstName3}") #print(f"your last name is {LastNAme3}") #print(f"your age is {Age3}") #reet3("tanmay",21) def reet4(FirstName4,LastNAme4=None,Age4=None): # it is right it can't through the error we use default after default print(f"your first name is {FirstName4}") print(f"your last name is {LastNAme4}") print(f"your age is {Age4}") reet4("tanmay")
# break for i in range(1,11): if i==5: break print(i) # continue for j in range(1,11): if j==5: continue print(j)
# string are immutable string = "string" print(string[1]) # normal and its works in all lang. #string[1] = "T" # mutable and its can not works in all lang. python is immutable so it can not use this so we use replace method print(string.replace("t","T")) # in this replace method is use and output can be generated by create new veriable of string. # for example new_string = string.replace("s","T") print(new_string)
import pygame import random WIDTH = 1000 HEIGHT = 600 FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) running = True class Player(pygame.sprite.Sprite): #sprite for the Player, also the player's paddle def __init__(self, playerNum): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25,125)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.rect.centery = HEIGHT / 2 self.speedx = 0 self.speedy = 0 self.playerNum = playerNum buffer = 10 if self.playerNum == 1: # player 1 (left paddle) self.rect.left = 0 + buffer else: # player 2 (right paddle) self.rect.right = WIDTH - buffer def update(self): self.speedx = 0 #makes the paddle only move when the key is pressed down self.speedy = 0 #fiddle around with things like this to get different motion effects keystate = pygame.key.get_pressed() if self.playerNum == 1: if keystate[pygame.K_w]: self.speedy = -5 if keystate[pygame.K_s]: self.speedy = 5 else: if keystate[pygame.K_UP]: self.speedy = -5 if keystate[pygame.K_DOWN]: self.speedy = 5 self.rect.x += self.speedx self.rect.y += self.speedy if self.rect.top < 0: self.rect.top = 0 if self.rect.bottom > HEIGHT: self.rect.bottom = HEIGHT class Ball(pygame.sprite.Sprite): # sprite for the Player, also the player's paddle def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25, 25)) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.center = (WIDTH / 2, HEIGHT / 2) self.speedx = 4 self.speedy = -6 def update(self): self.rect.y += self.speedy self.rect.x += self.speedx if self.rect.top < 0: self.rect.top = 0 self.speedy = -self.speedy if self.rect.bottom > HEIGHT: self.rect.bottom = HEIGHT self.speedy = -self.speedy if self.rect.right > WIDTH: self.rect.right = WIDTH self.speedx = -self.speedx if self.rect.left <= 0 or self.rect.right >= WIDTH: pygame.quit() #exits the game def bounce(self): self.speedx = -self.speedx # initialize pygame and create window pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("My Game") clock = pygame.time.Clock() all_sprites = pygame.sprite.Group() ball = Ball() all_sprites.add(ball) player_sprites = pygame.sprite.Group() player1 = Player(1) all_sprites.add(player1) player_sprites.add(player1) player2 = Player(2) all_sprites.add(player2) player_sprites.add(player2) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # Process input (events) for event in pygame.event.get(): # check for closing window if event.type == pygame.QUIT: running = False # Update all_sprites.update() # check to see if a mob hit the player hits = pygame.sprite.spritecollide(ball, player_sprites, False) # checks paddle1 hit the ball and the bool dtermines if the hit object should be deleted, also stores a list of all the mobs that hit that object if hits: print("connection") ball.bounce() # Draw / render screen.fill(BLACK) all_sprites.draw(screen) # after drawing everything, flip the display pygame.display.flip() pygame.quit()
# # # # -*- coding: utf-8 -*- # Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: # # Integers in each row are sorted in ascending from left to right. # Integers in each column are sorted in ascending from top to bottom. # For example, # # Consider the following matrix: # # [ # [1, 4, 7, 11, 15], # [2, 5, 8, 12, 19], # [3, 6, 9, 16, 22], # [10, 13, 14, 17, 24], # [18, 21, 23, 26, 30] # ] # Given target = 5, return true. # # Given target = 20, return false. class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ m = len(matrix) n = len(matrix[0]) # Get the first column values in matrix firstColValues = [matrix[i][0] for i in xrange(m)] # Search in first column flag, row_location = self.binarySearch(firstColValues, target, 0, m-1) # If target value is not in first column values, then we move onto row search if flag: return True else: searchRange = m-1 if row_location+1 > m else row_location+1 for i in range(searchRange): flag, col_location = self.binarySearch(matrix[i], target, 0, n-1) if flag: return True return False def binarySearch(self, array, target, start, end): """ :type array: List :type target: int :type start: int :type end: int :rtype: bool """ mid = (start + end)/2 while start < end: mid = (start + end)/2 if target == array[mid]: return True, mid elif target < array[mid]: end = mid elif target > array[mid]: start = mid + 1 mid = (start + end)/2 if array[mid] == target: return True, mid # Note it is possible the target is out of bound, thus we need to consider the boundry situation if array[mid] < target: return False, mid return False, mid-1 if __name__ == '__main__': s = Solution() matrix = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] #matrix = [[1,3],[23,50]] target = 0 print s.searchMatrix(matrix,target)
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # Algorithm: from the last index (on the right hand side) to the left, when nums[index] > nums[index-1], # if index reaches to the left (0) but no swap is done yet, reorder all elements from smallest to biggest for index in xrange(len(nums)-1, 0, -1): # Pay attention to the end point! it should be nums[1], or otherwise when # it reaches to nums[0] the if condition below will be nums[-1] if nums[index] > nums[index-1]: # Then nums[index:] is descending; thus we should swap the nums[index-1] with number that in nums[i:] who # is just bigger than nums[index-1] # Example: [3,'2',4,'3',2,1] -> [3,'3',4,'2',2,1] for search in xrange(len(nums)-1, index-1, -1): if nums[search] > nums[index-1]: nums[search], nums[index-1] = nums[index-1], nums[search] break # Then we should reorder nums[i:] # [3,'3',4,'2',2,1] -> [3,3,1,2,2,4] start = index end = len(nums) - 1 while start < end: nums[start], nums[end] = nums[end], nums[start] start += 1 end -= 1 print nums return start = 0 end = len(nums) - 1 while start < end: nums[start], nums[end] = nums[end], nums[start] start += 1 end -= 1 print nums return if __name__ == '__main__': s = Solution() nums = [1,2,3] nums = [3,2,1] nums = [3,3,2,2] nums = [3,2,3,2] nums = [1,3,2] nums = [3,2,4,3,2,1] s.nextPermutation(nums)
# -*- coding: utf-8 -*- def shortestMazePath(maze, source, destination): """ Given a MxN matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1. Expected time complexity is O(MN). For example – Input: mat[ROW][COL] = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, {1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, {1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, {0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, {1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, {1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, {1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, {1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; Source = {0, 0}; Destination = {3, 4}; Output: Shortest Path is 11 """ if len(maze) == 0: return 0 elif len(maze[0]) == 0: return 0 possible_move =[ [-1,0], # up [0,-1], # left [0,1], # right [1,0] # down ] x_min = y_min = 0 x_max = len(maze) y_max = len(maze[0]) visited = [[0 for _ in range(y_max)] for _ in range(x_max)] visited[0][0] = 1 queue = [] queue.append(source+[0]) # contains the point and distance, e.g. [1,1,2] while len(queue) > 0: current_point = queue[0] if current_point[0] == destination[0] and current_point[1] == destination[1]: return current_point[2] queue.pop(0) for i in range(0,4): next_x = current_point[0] + possible_move[i][0] next_y = current_point[1] + possible_move[i][1] if next_x >= 0 and next_y >= 0 and next_x < x_max and next_y < y_max: if maze[next_x][next_y] and not visited[next_x][next_y]: visited[next_x][next_y]=1 # putting each adjacent node into queue, meaning this is BFS queue.append([next_x, next_y, current_point[2]+1]) return 0 if __name__ == '__main__': maze = [ [1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [1, 0, 1, 0, 1, 1, 1, 0, 1, 1], [1, 1, 1, 0, 1, 1, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 1, 0, 1, 0], [1, 0, 1, 1, 1, 1, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 0, 0, 0, 0, 1, 0, 0, 1] ] source = [0, 0] destination = [3, 4] print(shortestMazePath(maze, source, destination))
# # # # -*- coding: utf-8 -*- # Given a non-negative number represented as an array of digits, plus one to the number. # The digits are stored such that the most significant digit is at the head of the list. # 注意如何反转一个list! list.reverse() 的返回值是None class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ def toNum(x,y): return x*10+y num = reduce(toNum,digits) + 1 temp = [] while num != 0: digit = num % 10 temp.append(digit) num /= 10 # print temp[::-1] # print temp.reverse() # print temp return temp[::-1] if __name__ == '__main__': s = Solution() digits = [9,9,9] print s.plusOne(digits)
# # # # -*- coding: utf-8 -*- def topKFrequentWords(words, k): # write your code here result = [] temp = {} for w in words: if w not in temp: temp[w] = 0 temp[w] += 1 temp = sorted(temp.iteritems(), key=lambda x: x[0]) temp = sorted(temp, key=lambda x: x[1], reverse=True) for i in range(k): result.append(temp[i][0]) return result words = [ "yes", "lint", "code", "yes", "code", "baby", "you", "baby", "chrome", "safari", "lint", "code", "body", "lint", "code" ] k = 3 print topKFrequentWords(words, k)
def findSubtree(root): s = Solution() s.findSubtree2(root) return s.node class Solution: # @param {TreeNode} root the root of binary tree # @return {TreeNode} the root of the maximum average of subtree average, node = 0, None def findSubtree2(self, root): # Write your code here self.helper(root) return self.node def helper(self, root): if root is None: return 0, 0 sum = root.val size = 1 for c in root.children: temp_sum, temp_size = self.helper(c) sum += temp_sum size += temp_size if len(root.children) > 0: if self.node is None or sum * 1.0 / size > self.average: self.node = root self.average = sum * 1.0 / size return sum, size class NaryTreeNode: def __init__(self, val=None, children=None): self.val = val if not children: self.children = [] else: self.children = children[:] if __name__ == '__main__': NaryTreeNode_110 = NaryTreeNode(110) NaryTreeNode_20 = NaryTreeNode(20) NaryTreeNode_30 = NaryTreeNode(30) NaryTreeNode_120 = NaryTreeNode(120, [NaryTreeNode_110, NaryTreeNode_20, NaryTreeNode_30]) NaryTreeNode_150 = NaryTreeNode(150) NaryTreeNode_80 = NaryTreeNode(80) NaryTreeNode_180 = NaryTreeNode(180, [NaryTreeNode_150, NaryTreeNode_80]) NaryTreeNode_200 = NaryTreeNode(200, [NaryTreeNode_120, NaryTreeNode_180]) findSubtree(NaryTreeNode_200)
# # # # -*- coding: utf-8 -*- class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ if len(height) <= 2: return 0 water_result = 0 max_left = [] max_val = 0 # 对height来说,维护每个元素(不包含当前元素)左边最大的值 for i in range(0,len(height)): max_left.insert(i,max_val) max_val = max(height[i],max_val) max_val = 0 for i in range(len(height)-1,-1,-1): max_val = max(height[i],max_val) # lowest_left_right = min(max_left[i],max_val) water_result += lowest_left_right - height[i] if lowest_left_right > height[i] else 0 #print max_left return water_result if __name__ == '__main__': s = Solution() height = [0,1,0,2,1,0,1,3,2,1,2,1] print s.trap(height)
# # # # -*- coding: utf-8 -*- """ zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压),看下面的例子就明白了: # >>> a = [1,2,3] # >>> b = [4,5,6] # >>> c = [4,5,6,7,8] # >>> zipped = zip(a,b) # [(1, 4), (2, 5), (3, 6)] # >>> zip(a,c) # [(1, 4), (2, 5), (3, 6)] # >>> zip(*zipped) # [(1, 2, 3), (4, 5, 6)] """ if __name__ == '__main__': quality = [10, 20, 5] wage = [70, 50, 30] temp = [(w, q) for w, q in zip(wage, quality)] print(temp) workers = sorted([float(w) / q, q] for w, q in zip(wage, quality)) print(workers)
# # # # -*- coding: utf-8 -*- """ Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. Example: Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. Input: word1 = “coding”, word2 = “practice” Output: 3 Input: word1 = "makes", word2 = "coding" Output: 1 """ """ 我们其实需要遍历一次数组就可以了,我们用两个变量p1,p2初始化为-1, 然后我们遍历数组,遇到单词1,就将其位置存在p1里,若遇到单词2, 就将其位置存在p2里,如果此时p1, p2都不为-1了,那么我们更新结果 """ class Solution: def shortestWordDistance(self, words, word1, word2): import sys p1, p2 = -1, -1 minimum_distance = sys.maxint for i in range(len(words)): if words[i] == word1: if p1 == -1: p1 = i else: if minimum_distance > abs(p1-p2): p1 = i minimum_distance = abs(p1-p2) elif words[i] == word2: if p2 == -1: p2 = i else: if minimum_distance > abs(p1-p2): p2 = i minimum_distance = abs(p1-p2) return min(minimum_distance, abs(p1-p2)) if __name__ == '__main__': s = Solution() words = ["practice", "makes", "perfect", "coding", "makes"] word1 = "coding" word2 = "practice" assert s.shortestWordDistance(words, word1, word2) == 3 word1 = "makes" word2 = "coding" assert s.shortestWordDistance(words, word1, word2) == 1
# # # # -*- coding: utf-8 -*- """ Given a string and a number k. Find all sub strings of size k with k distinct characters. Example: input: abcdkeewrf and 4 [0], [9] output: abcd, bcdk, cdke,ewrf """ def substringWithKDistinct(str, k): result = [] for i in range(0, len(str)-k+1): size_k_substring = str[i:i+k] if checkDistinctCharNum(size_k_substring, k): result.append(size_k_substring) return result def checkDistinctCharNum(str, k): temp = {} for c in str: if c not in temp: temp[c] = 0 temp[c] += 1 if temp[c] > 1: return False return True if __name__ == '__main__': str = "abcdkeewrf" size = 4 print(substringWithKDistinct(str, size)) # substring whose size is k
# # # # -*- coding: utf-8 -*- class Solution: def longestPalindrome(self, s): res = "" for i in range(len(s)): # odd case, like "aba" tmp = self.helper(s, i, i) if len(tmp) > len(res): res = tmp # even case, like "abba" tmp = self.helper(s, i, i+1) if len(tmp) > len(res): res = tmp return res # get the longest palindrome, l, r are the middle indexes # from inner to outer def helper(self, s, l, r): while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return s[l+1:r] if __name__ == '__main__': s = Solution() """ Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" """ # str = "babad" # print(s.longestPalindrome(str)) str = "cbbbd" print(s.longestPalindrome(str)) # Time complexity is O(n*n) because for each character it's possible to go all the way to the start/end
""" 1 - Codificar a mensagem + converter a mensagem em binário + pegar pixels da imagem + modificar cada LSB pixal da imagem com a mensagem 2 - Salvar a imagem codificada 3 - Descodificar Desenvolvido por: Jackson Sousa, Leonaldo Faleiro e Jodson Rompão """ import cv2 import numpy as np def to_bin(data): if isinstance(data, str): return ''.join([format(ord(letra), '08b') for letra in data]) if isinstance(data, bytes) or isinstance(data, np.ndarray): return [format(byte, '08b') for byte in data] if isinstance(data, int) or isinstance(data, np.uint8): return format(data, "08b") else: raise TypeError("Type not supported.") def ler_ficheiro(ficheiro): """Ler ficheiro do tipo txt.""" with open(ficheiro) as texto: return texto.read() def gravar_texto(novo_ficheiro, texto): """Guardar texto num ficheiro do tipo txt. :param novo_ficheiro: nome do ficheiro a guardar o texto texto: o texto a ser guardado no ficheiro :return: None """ with open(novo_ficheiro, 'w') as ficheio: ficheio.write(texto) def encode(nome_imagem, mensagem): """ Pega numa mensagem e numa imagem e esconde a mensagem dentro dela. :param nome_imagem: imagem que é usada para esconder a mensagem :param mensagem: mensagem a ser enscondida na imagem :return: uma nova imagem com a mensagem escondida """ imagem = cv2.imread(nome_imagem) mensagem += '=====' msg_bin = to_bin(mensagem) data_index = 0 data_len = len(msg_bin) for row in imagem: for pixel in row: r, g, b = to_bin(pixel) # mudar o ultimo bit do vermelho if data_index < data_len: pixel[0] = int(r[:-1] + msg_bin[data_index], 2) # [1] somar os bits e converer para inteiro data_index += 1 # mudar o ultimo bit do verde if data_index < data_len: pixel[1] = int(g[:-1] + msg_bin[data_index], 2) # [1] data_index += 1 # mudar o ultimo bit do azul if data_index < data_len: pixel[2] = int(b[:-1] + msg_bin[data_index], 2) # [1] data_index += 1 # parar loop se i index é maior que o tamnaho da mensagem a guardar if data_index >= data_len: break return imagem def decode(encode_imagem): """ Pega num imagem com a mensagem escondida e retira a menasgem escondida. :param encode_imagem: imagem com a mensagem escondida :return: (string) menagem descodificada """ image = cv2.imread(encode_imagem) mensagem_codificada = "" for row in image: for pixel in row: r, g, b = to_bin(pixel) mensagem_codificada += r[-1] mensagem_codificada += g[-1] mensagem_codificada += b[-1] # separar os bits em 1 byte (8 bits) all_bytes = [mensagem_codificada[i: i + 8] for i in range(0, len(mensagem_codificada), 8)] mensagem = "" for byte in all_bytes: mensagem += chr(int(byte, 2)) if mensagem[-5:] == "=====": break return mensagem[:-5] def menu(): print( """ Escolha, qual operação queres efetuar. [1] Codificar mensagem na imagem. [2] Descodifcar a mensagem na imagem [3] Para terminar a operação. """ ) opcao = int(input("O que queres fazer? ")) if opcao == 1: print("[*] Codificar mensagem...\n") imagem = input("Imagem para guardar a mensagem [png/jpg]: ") # mensagem = input("Mensagem para enconder na mensagem: ") mensagem = ler_ficheiro('data/auto-da-barca-2.txt') output_imagem = input("Nome da nova imagem a ser salvo [png/jpg]: ") or 'encoded_imagem.png' encoded_imgem = encode(imagem, mensagem) cv2.imwrite(output_imagem, encoded_imgem) print("\n[*] Mensagem Codificada.") elif opcao == 2: print("[*] Descodificar mensagem...\n") imagem = input("Imagem para retirar a mensagem codificada [png/jpg]: ") decoded_mensagem = decode(imagem) gravar_texto('data/mensagem-descodificada.txt', decoded_mensagem) print("\n[*] Mensagem codificada:", decoded_mensagem) else: print("Obrigado pela visita. Vejo-te mais logo. ;)") if __name__ == '__main__': menu()