text
stringlengths
37
1.41M
# 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 isSameTree(self, p, q): if p and q: return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) else: return p == q #可能p和q都为None,则返回True,或者其中一方为None,则返回False def isSameTree2(self, p, q): stack = [(p, q)]#将两个节点保存为元组,更加方便 while stack: n1, n2 = stack.pop() if not n1 and not n2: continue if not n1 or not n2: return n1 == n2 if n1.val != n2.val: return False stack.append((n1.right, n2.right)) stack.append((n1.left, n2.left)) return True def isSameTree3(self, p, q): queue = collections.deque([(p, q)]) while queue: n1, n2 = queue.popleft() if not n1 and not n2: continue if not n1 or not n2: return n1 == n2 if n1.val != n2.val: return False queue.append((n1.left, n2.left)) queue.append((n1.right, n2.right)) return True a1 = TreeNode(1) b1 = TreeNode(2) c1 = TreeNode(3) a1.left = b1 a1.right = c1 a2 = TreeNode(1) b2 = TreeNode(2) c2 = TreeNode(3) a2.left = b2 a2.right = c2 q = Solution() print(q.isSameTree(a1,a2))
def climbStairs(n): """ :type n: int :rtype: int """ steps = [1, 2] s = [0] * (n + 1) s[0] = 1 for i in range(1,n + 1): for j in [c for c in steps if c <= i]: s[i] += s[i-j] return s[n] def climbStairs2(n): if n == 1: return 1 res = [0 for i in range(n)] res[0], res[1] = 1, 2 for i in range(2, n): res[i] = res[i-1] + res[i-2] return res[-1] def climbStairs3(n): a, b = 1, 1 for _ in range(n): a, b = b, a + b return a print(climbStairs3(5))
from sys import argv script ,filename = argv print "we are going ton erase %r" %filename print "if you dnt want that hit CTRL-C(^C)." print"if you do want that,hit RETURN" raw_input("?") print "opening the file: " target =open(filename,'w') print "truncating the file.goodbye" target.truncate() print "now type 3 lines as following" line1 = raw_input("line1:") line2 = raw_input("line2:") line3 = raw_input("line3:") print "Im going to write these line in the file." target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print"and finally close it" target.close()
import pandas as pd heights=[59,20,62,65,63,65,64] data={'heights':heights,'sex':'M'} results = pd.DataFrame(data) print(results) results.index=['A','B','C','D','E','F','G'] print(results) dict = {"country":["brazil","russia","India","China","South Africa"], "capital":["Brasilia","Moscow","New delhi","Beijing","Pretoria"], "area":[8.523,17.78,3.289,9.879,1.23], "population":[200.4,143.5,1252,1357,52.98]} brics= pd.DataFrame(dict) print(brics) brics.index=['1','2','3','4','5'] print(brics) cars = pd.read_csv('cars.csv') print(cars)
people =20 cats = 30 dogs = 15 if people < cats : print "too many cats" if people > cats: print "not many cats" if people < dogs: print "too many dogs" if people > dogs: print "not many dogs" dogs+=5 if people >=dogs: print "people are greater than or equal to dogs" if people <=dogs: print "people are less than or equal" if people == dogs: print "people are dogs"
class person: def __init__(self,f,l): self.fname=f self.lname=l def name(self): return self.fname+ " " +self.lname class emp(person): def __init__(self,f,l,no): person.__init__(self,f,l) self.sno= no def getemp(self): return self.name() + "," + self.sno x= person("karan","simpson") y = emp("siran","gupta","1009") print(x.name()) print(y.getemp())
def add(a,b): print "add %d + %d" %(a,b) return a+b def sub(a,b): print "sub %d - %d" %(a,b) return a-b def mul(a,b): print "mul %d * %d" %(a,b) return a*b def div(a,b): print"div %d / %d" %(a,b) return a/b print "lets do something fun" age= add(20,2) hg= sub(78,4) wg =mul(90,3) iq=div(100,2) print "age: %d,hg: %d,wg:%d,iq:%d" %(age,hg,wg,iq) print"heres a puzzle" what = add(age,sub(hg,mul(wg,div(iq,2)))) print "that becomes",what,"can you do it by hand?"
a=2 print 'id(a)=',id(a) a=a+1 print 'id(a)=',id(a) print 'id(3)=',id(3) b=2 print'id(2)=',id(2) def hi(): print "HELLO" a= hi() a class Myclass: "this is my first class" a=10 def fun(self): print "HELLO" ob= Myclass() print(Myclass.a) print(Myclass.fun) ob.fun() print(Myclass.__doc__)
''' for i in range(ord('a'),ord('z')+1): print chr(i) print "********************" print "enter 10 numbers:" a=[0]*10 for i in range(0,10): a[i]= int(raw_input(">>")) for i in range (0,10): if a[i]%7 ==0: print a[i] ''' print "enter two values:" a = int(raw_input("a>>")) b = int (raw_input("b>>")) sum =0 for i in range(a,b): if i%5 ==0 and i%7==0 : print i sum = sum +i print "sum",sum
print "enter a number:" no=int(raw_input(">>")) i=1 while i!=11: print no,"*",i,"=",i*no i=i+1 for i in range(1,11): print(no,'x',i,'=',no*i)
def sum(items): no=0 for x in items: no+=x return no print sum([1,2,3,4,5,6,7,8])
import math ''' a = int(raw_input("a>>")) b = int(raw_input("b>>")) c = int(raw_input("c>>")) d = (b**2) - (4*a*c) if d>0: r1 = (-b + math.sqrt(d))/(2*a) r2 = (-b - math.sqrt(d))/(2*a) elif d==0: r = (-b)/(2*a) print "ROOTS ARE EQUAL" else: print "IMAGINARY ROOTS" no = int(raw_input(">>")) d = math.sqrt(no) if d*d == no and no in range(2,78): print "PERFECT" else: print "NO" '''
import tkinter from PIL import Image, ImageTk import random root = tkinter.Tk() root.geometry("600x600") root.title("Simple Rolling Dice Game") BlankLine = tkinter.Label(root, text="") BlankLine.pack() HeadingLabel = tkinter.Label(root, text="This is a simulation", fg="light green", bg="dark green", font="Helvetica 18 bold italic") HeadingLabel.pack() dice = ['1.png','two.png','3.png','4.jpg','five.png','six.png'] DiceImage = ImageTk.PhotoImage(Image.open(random.choice(dice))) ImageLabel = tkinter.Label(root, image = DiceImage) ImageLabel.pack(expand=True) DiceImage1 = ImageTk.PhotoImage(Image.open(random.choice(dice))) ImageLabel1 = tkinter.Label(root, image = DiceImage1) ImageLabel1.pack(expand=True) def rolling(): DiceImage = ImageTk.PhotoImage(Image.open(random.choice(dice))) ImageLabel.configure(image=DiceImage) ImageLabel.image = DiceImage DiceImage1 = ImageTk.PhotoImage(Image.open(random.choice(dice))) ImageLabel1.configure(image=DiceImage1) ImageLabel1.image = DiceImage1 button = tkinter.Button(root, text="Roll the Dice!", fg="blue", command=rolling) button.pack(expand=True) root.mainloop()
""" Implement a frame to track the human descriptors and notes on each data column. """ from typing import Union import pandas as pd from .exceptions import OverlapException from .frame_to_word import frame_to_word from .word2reference.read_word import WordReader class DescriptionFrame: """ Parameters ---------- data: pandas.DataFrame A data frame containing 'Description' and 'Notes' columns. Each row is a different column. """ def __init__(self, data: pd.DataFrame): self.default_columns = ["Description", "Notes"] assert all(i in data.columns for i in self.default_columns) self.data = data @classmethod def from_file(cls, file_path: str, sheet_name=0): """ Generate DescriptionFrame from excel Parameters ---------- file_path: str Path to an excel file. sheet_name: str [optional] The sheet on which the DescriptionFrame is stored. Returns ------- DescriptionFrame """ data = pd.read_excel(file_path, sheet_name=sheet_name) return cls(data) @classmethod def blank_from_index(cls, index): """ Generate a blank DescriptionFrame from a list of column names. Parameters ---------- index: List[str] list of column names to use as the index. Returns ------- DescriptionFrame """ data = pd.DataFrame(columns=["Description", "Notes"], index=index) return cls(data) @classmethod def via_concat(cls, frame1: pd.DataFrame, frame2: pd.DataFrame): """ Generate a DescriptionFrame by concatenating two data frames. Parameters ---------- frame1: pd.DataFrame A pandas DataFrame with columns=["Description", "Notes"] frame2: pd.DataFrame A pandas DataFrame with columns=["Description", "Notes"] Returns ------- DescriptionFrame """ data = pd.concat([frame1, frame2]) return cls(data) @classmethod def from_word(cls, file: str): """ Generate a DescriptionFrame from word. Looks for h2 headings for the index, and h3 headings for the columns. Parameters ---------- file: str The path to the word file. Returns ------- DescriptionFrame """ reader = WordReader(file) data = reader.parse_document() data = pd.DataFrame(data).T return cls(data) def to_excel(self, file_path: str, sheet_name=1): """ Save the frame to excel format. Parameters ---------- file_path: str Path to save the file at. sheet_name: str [optional] Name for the sheet in excel. Returns ------- None """ self.data.to_excel(file_path, sheet_name=sheet_name) def to_word(self, file): """ Save the frame to word - writes each index as: index [h2] Description [h3] ... Notes [h3] ... next_index... Parameters ---------- file: str file path to write the word doc at. Returns ------- None """ frame_to_word(self.data, file) def add_rows(self, new_items: Union[list, str], overlap="unique") -> None: """ Update the index of the DescriptionFrame with new value(s). Parameters ---------- new_items: Union[str, list] either an item to add to the index or a list of items to add to the index. overlap: str [one of "unique"/ "error"/ "force"] method choice for dealing with overlap between 'new_items' and the existing index values. unique: Add only the values in 'new_items' that are not already in index. error: Raise an error if any value in 'new_items' is in index. force: force all values in 'new_items' into the index (may cause duplicates) """ assert overlap in ["unique", "error", "force"] if isinstance(new_items, str): new_items = [new_items] overlap_function = self._overlap_functions(overlap) new_items = overlap_function(new_items) self._force_add_rows(new_items) def _overlap_functions(self, key: str): overlap_dict = { "unique": self._overlap_unique, "error": self._overlap_error, "force": lambda new_items: new_items } if key not in overlap_dict: raise Exception(f"{key} not one of \"unique\", \"error\", or \"force\". " f"Check your code and try again.") return overlap_dict[key] def _overlap_error(self, new_items): overlap = [i for i in new_items if i in self.data.index] if overlap: raise OverlapException( f"Columns already exists in DescriptionFrame ({overlap})" ) return new_items def _overlap_unique(self, new_items): new_items = [i for i in new_items if i not in self.data.index] return new_items def _force_add_rows(self, new_items): if isinstance(new_items, str): new_items = [new_items] new_rows = pd.DataFrame( columns=self.data.columns, index=new_items ) self.data = pd.concat([self.data, new_rows]) def __getitem__(self, item): return self.data.loc[item] @property def index(self): """ Returns ------- list """ return self.data.index @property def columns(self): """ Returns ------- list """ return self.data.columns @property def shape(self): """ Returns ------- tuple """ return self.data.shape
# Внешний вид игрового поля field = [ [' ', '0', '1', '2'], ['0', '-', '-', '-'], ['1', '-', '-', '-'], ['2', '-', '-', '-']] move = "O" # Переменная, которая отвечает за то, чей сейчас ход, первые всегда ходят крестики Flag = False # Флаг, который будет меняться после выполнения условий в бесконечном цикле counter = 0 # Счётчик, который будет считать количество ходов, если он будет равняться 9, то будет ничья # Вывод в консоль игрового поля def field_form(): for x in field: print(x[0], x[1], x[2], x[3]) # Ход def token_input(): i = input("Введите номер столбца: ") j = input("Введите номер строки: ") print() if (i in "012") and (j in "012"): # Если значения не выходят из допустимого предела, выполнится код ниже if (field[int(j) + 1][int(i) + 1] == "-"): field[int(j) + 1][int(i) + 1] = move else: print("Клетка занята", "Попробуйте ещё раз", sep="\n") token_input() else: # Если значения выходят из допустимого предела, выполнится код ниже, который предложит игроку попробовать снова print("Вы ввели несуществующий номер поля", "Попробуйте ещё раз", sep="\n") token_input() # бесконечный цикл, который прервётся только в случае победы или ничьи field_form() # Генерация игрового поля while True: if move == "O": move = "X" else: move = "O" if (Flag == False): print() if (counter == 9): print("Ничья") break print() counter += 1 print(f"Сейчас ходит {move}") token_input() field_form() elif (Flag == True): if move == "O": # тут какая-то путаница короче, пусть будет вот такой костыль move = "X" else: move = "O" print(f"Выиграл {move}") break # условия для победы if field[1][1] == field[1][2] == field[1][3] == move: # вся первая строка по горизонтали Flag = True elif field[2][1] == field[2][2] == field[2][3] == move: # вся вторая строка по горизонтали Flag = True elif field[3][1] == field[3][2] == field[3][3] == move: # вся третья строка по горизонтали Flag = True elif field[1][1] == field[2][1] == field[3][1] == move: # вся первая строка по вертикали Flag = True elif field[1][2] == field[2][2] == field[3][2] == move: # вся вторая строка по вертикали Flag = True elif field[1][3] == field[2][3] == field[3][3] == move: # вся третья строка по вертикали Flag = True elif field[1][1] == field[2][2] == field[3][3] == move: # по диагонали с левого верхнего в правый нижний Flag = True elif field[3][1] == field[2][2] == field[1][3] == move: # по диагонли с левого нижнего в правый верхний Flag = True
#!/usr/bin/env python # encoding: utf-8 # [email protected] class Solution(object): def sortList(self, head): if not head: return head res = head while res: while True: if not head.next.next: break cur_node = head.next.next if cur_node.val < head.next.val: head.next, cur = head. if __name__ == '__main__' : node1 = ListNode(2) node2 = ListNode(1) node3 = ListNode(3) head = node1 node1.next = node2 node2.next = node3 solution = Solution() head = solution.sortList(head) while True: if not head: break print head.val head = head.next
#!/usr/bin/env python #-*- coding=utf-8 -*- ######################## def f(target): if target == 1: return 1 elif target > 1: return str(f(target-1))+str(target) else: raise ValueError('bad args') #################################### print f(3)
#!/usr/bin/env python #-*- coding=utf-8 -*- ######################## def f(target): if target == 0 or target == 1: return 1 else: return f(target-1) + f(target -2) print f(3)
#!/usr/bin/env python #-*- coding=utf-8 -*- num = 1 for i in range(1,121): num = num * i print num num = str(num) list_1 = list(num) list_1.sort() num = "".join(list_1) print num
class User: def __init__(self, name, email): self.name = name self.email = email # self.account_balance = 0 self.account = BankAccount('Checking') def make_withdrawal(self, amount): # if self.account.balance < 0: # charge overdraft fee # pass # 1 # The user subtracts from the account balance # self.account.balance -= amount # 2 # The user calls the withdraw method of the bank account self.account.withdraw(amount) print(f"{self.name} took out {amount} from their bank acount") return self def make_deposit(self, amount): self.account_balance += amount print(f"{self.name} deposited {amount} into thier bank acount") return self class BankAccount(object): def __init__(self, name, int_rate=0.01, balance=0): self.name = name self.int_rate = int_rate self.balance = balance def show_balance(self): print("%s's account. Balance:$%.2f" % (self.name, self.balance)) return self def deposit(self, amount): if amount <= 0: print("You have no money") else: print("Amount deposited: $%.2f" % amount) self.balance += amount return self def withdraw(self, amount): if amount > self.balance: print(" You can't do that") else: print("Withdrawing: %.2f" % (amount)) self.balance -= amount return self
myfile = open("Files/fruits.txt") content = myfile.read() print(myfile.read()) print(myfile.read()) print(content) print(content) myfile.close() #print(myfile.read()) # New way to code this file open and it will close file object in memory # so no need to explicitly mention close clause. with open("Files/fruits.txt") as myfile: content = myfile.read() print("By new method to print file content") print(content)
""" Contains a selection of tree and graph related algorithms """ from enum import Enum from itertools import izip_longest from Queue import Queue from random import randint from algorithms import permutations from linked_list_algorithms import Node class BinaryNode(object): """ A node that's part of a binary tree """ def __init__(self, value, left=None, right=None): """ :type value: int :type left: BinaryNode :type right: BinaryNode """ self.value = value self.left = left self.right = right class BinaryNodeWithParent(object): """ A node that's part of a binary tree that can also have a link back to its parent node """ def __init__(self, value, left=None, right=None, parent=None): self.value = value self.left = left self.right = right self.parent = parent class BinaryNodeWithDirections(object): """ A node that's part of a binary tree that can also have a pointer to describe the location of two other nodes in the tree """ def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right self.first_direction = None # type: NodeDirection self.second_direction = None # type: NodeDirection class NodeDirection(Enum): """ Describes the location of a child node relative to the current node """ left = 1 right = 2 here = 3 def traverse_binary_tree(tree): """ Iterates through and yields binary tree values in order :param BinaryNode tree: The root node of the tree :return: Values of each node :rtype: collections.Iterable[int] """ if not tree: return for n in traverse_binary_tree(tree.left): yield n yield tree.value for n in traverse_binary_tree(tree.right): yield n def traverse_binary_tree_nodes(tree): """ Iterates through and yields binary tree nodes in order :param BinaryNode tree: The root node of the tree :return: The nodes in value order :rtype: collections.Iterable[BinaryNode] """ if not tree: return for n in traverse_binary_tree_nodes(tree.left): yield n yield tree for n in traverse_binary_tree_nodes(tree.right): yield n def traverse_binary_tree_pre_order(tree): """ Iterates through and yields binary tree values, yielding the value of the current node visited first :param BinaryNode tree: The root node of the tree :return: Values of each node :rtype: collections.Iterable[int] """ if not tree: return yield tree.value for n in traverse_binary_tree_pre_order(tree.left): yield n for n in traverse_binary_tree_pre_order(tree.right): yield n def traverse_binary_tree_post_order(tree): """ Iterates through and yields binary tree values, yielding the value of the current node visited last :param BinaryNode tree: The root node of the tree :return: Values of each node :rtype: collections.Iterable[int] """ if not tree: return for n in traverse_binary_tree_post_order(tree.left): yield n for n in traverse_binary_tree_post_order(tree.right): yield n yield tree.value class GraphVertex(object): def __init__(self, value, vertices=None): """ Represents a single vertex in a graph :param int value: The value of the vertex :param list[GraphVertex] vertices: A collection of other vertices that are accessible from this vertex by an edge """ self.value = value self.vertices = vertices if vertices else [] def depth_first_search(vertex, value, visited=None): """ Perform a depth first search through a directed graph :param GraphVertex vertex: The start vertex in the graph :param int value: The value to search for :param list[int] visited: A collection of previous values visited :return: A boolean describing whether the vertex was found, the vertex itself, and the number of nodes visited to find the specified node :rtype: tuple[boolean, GraphVertex, int] """ if vertex.value == value: nodes_visited = len(visited) + 1 if visited else 1 return True, vertex, nodes_visited if visited is None: visited = [] for v in vertex.vertices: if v.value in visited: continue updated_visited = [vertex.value] updated_visited.extend(visited) found, found_vertex, nodes_visited = depth_first_search(v, value, updated_visited) if found: return found, found_vertex, nodes_visited return False, None, len(visited) def breadth_first_search(vertex, value): """ Perform a breadth first search through a directed graph :param GraphVertex vertex: The start vertex in the graph :param int value: The value to search for :return: A boolean describing whether the vertex was found, the vertex itself, and the number of nodes traversed to find the specified node :rtype: tuple[boolean, GraphVertex, int] """ queue = Queue() queue.put((vertex, [])) while not queue.empty(): vertex, visited = queue.get() if vertex.value in visited: continue elif vertex.value == value: return True, vertex, len(visited) + 1 visited.append(vertex.value) for v in vertex.vertices: queue.put((v, visited)) return False, None, None def route_exists(first, second): """ Checks if a route exists between two vertices in a directed graph :param GraphVertex first: The first vertex :param GraphVertex second: The second vertex :return: A flag indicating whether a route could be found :rtype: bool """ first_queue = Queue() first_queue.put(first) second_queue = Queue() second_queue.put(second) first_visited = [first.value] second_visited = [second.value] while not first_queue.empty() or not second_queue.empty(): vertices = first_queue.get_nowait().vertices if not first_queue.empty() else [] for v in vertices: if v.value in second_visited: return True elif v.value in first_visited: continue else: first_visited.append(v.value) first_queue.put(v) vertices = second_queue.get_nowait().vertices if not second_queue.empty() else [] for v in vertices: if v.value in first_visited: return True elif v.value in second_visited: continue else: second_visited.append(v.value) second_queue.put(v) return False def create_binary_tree(values): """ Creates a minimal-height binary-tree from a list of sorted integer elements :param list[int] values: A sorted collection of integer values :return: The root node of the binary tree :rtype: BinaryNode """ if not values or len(values) == 0: return midpoint = len(values) / 2 root = BinaryNode(values[midpoint]) root.left = create_binary_tree(values[:midpoint]) root.right = create_binary_tree(values[midpoint + 1:]) return root def create_list_of_depths(tree): """ Creates a set of linked-lists, each of which contain all the nodes in a single layer of a binary-tree :param BinaryNode tree: The root node of the tree :return: A lookup table, mapping the layer ID to its corresponding linked-list :rtype: dict[int, Node] """ if tree is None: return {} depths = {0: Node(tree.value)} further_depths = create_list_of_depths(tree.left) for key, value in further_depths.items(): depths[key + 1] = value further_depths = create_list_of_depths(tree.right) for key, value in further_depths.items(): if key + 1 in depths: # Add node to the end of the linked-list node = depths[key + 1] while node.child: node = node.child node.child = value else: depths[key + 1] = value return depths def get_max_depth(tree): """ Get's the maximum depth of a binary search tree :param BinaryNode tree: The root of a binary tree :return: The number of layers in the tree :rtype: int """ return 0 if not tree else 1 + max(get_max_depth(tree.left), get_max_depth(tree.right)) def is_balanced(tree): """ Checks if a binary tree is balanced :param BinaryNode tree: A binary tree :return: True if the binary tree is balanced, else False :rtype: bool """ if not tree: return True left_depth = get_max_depth(tree.left) right_depth = get_max_depth(tree.right) if abs(left_depth - right_depth) > 1: return False return True if is_balanced(tree.left) and is_balanced(tree.right) else False def find_max_values(tree): """ Iterate through the values in the provided binary tree structure and incrementally report the maximum value found. We don't assume that the provided tree is a binary-search tree i.e. the tree isn't guaranteed to present values in order. :param BinaryNode tree: The root of a binary tree :return: The latest maximum values as the algorithm iterates through the tree :rtype: collections.Iterable[int] """ if not tree: raise ValueError("No binary tree provided") maximum = tree.value yield maximum for branch in tree.left, tree.right: try: for v in find_max_values(branch): if v > maximum: maximum = v yield maximum except ValueError: pass def find_min_values(tree): """ Iterate through the values in the provided binary tree structure and incrementally report the minimum value found. We don't assume that the provided tree is a binary-search tree i.e. the tree isn't guaranteed to present values in order. :param BinaryNode tree: The root of a binary tree :return: The latest minimum values as the algorithm iterates through the tree :rtype: collections.Iterable[int] """ if not tree: raise ValueError("No binary tree provided") minimum = tree.value yield minimum for branch in tree.left, tree.right: try: for v in find_min_values(branch): if v < minimum: minimum = v yield minimum except ValueError: pass def validate_binary_search_tree(tree): """ Checks if a binary tree is a valid binary-search tree i.e. all values to the left of the root node are smaller in value and all values to the right of the root node are equal or larger in value. :param BinaryNode tree: The root binary node in the tree :return: True if the tree is a valid binary search tree, False otherwise :rtype: bool """ if not tree: return False for v in find_max_values(tree.left): if v >= tree.value: return False for v in find_min_values(tree.right): if v < tree.value: return False return True def find_successor(current): """ For a binary-search tree, find the next node in sequence after the current :param BinaryNodeWithParent current: The current node :return: The next node in sequence :rtype: BinaryNodeWithParent """ if current.right: node = current.right while node.left: node = node.left return node else: node = current.parent while node.value <= current.value: if not node.parent: raise ValueError("No successor node. Have been provided " "with the last node in the sequence.") node = node.parent return node def find_build_order(projects, dependencies): """ Finds a valid build order for the provided projects, given a list of project dependencies :param list[str] projects: The project names :param list[tuple[str, str]] dependencies: A collection of project dependencies. The first project name is dependent on the second project being built :return: Whether we build the project successfully and the build order :rtype: tuple[boolean, list[str]] """ class Project(object): """ Represents a single project to be built """ def __init__(self, name, children=None, parents=None): """ :type name: str :type children: list[Project] :type parents: list[Project] """ self.name = name self.children = children or [] self.parents = parents or [] self.built = False # Set up a project graph with dependency links project_vertices = {p: Project(p) for p in projects} for child, parent in dependencies: project_vertices[child].parents.append(project_vertices[parent]) project_vertices[parent].children.append(project_vertices[child]) # First add projects to the queue that don't have any dependencies stack = [] for p in project_vertices.values(): if not p.parents: stack.append(p) # Now try build the remaining projects in an allowable order build_order = [] while stack: current = stack.pop(-1) parents_built = not any([p for p in current.parents if p.built is False]) if not parents_built: continue current.built = True build_order.append(current.name) for child in current.children: stack.append(child) # Check if all the projects have been build successfully success = not any([p for p in project_vertices.values() if p.built is False]) return success, build_order def find_common_ancestor(first, second): """ Finds the first common ancestor between two nodes To calculate the runtime of this algorithm, we define the number of parents before reaching a common ancestor for the first and second nodes to be 'a' and 'b' respectively. * This implementation's runtime is O(ab) * Its space complexity is O(1) :param BinaryNodeWithParent first: The first node :param BinaryNodeWithParent second: The second node :return: The first common ancestor. If one of the node's in an ancestor of the other, return that instead. :rtype: BinaryNodeWithParent """ while True: current = second while True: if first is current: return first elif not current.parent: break else: current = current.parent if first.parent: first = first.parent else: break raise ValueError("Unable to find common ancestor for provided nodes") def find_common_ancestor_without_parents(first, second, tree): """ Finds the first common ancestor between two nodes in a tree structure where nodes have no links back to their respective parents * This implementation's runtime is O(n) * Its space complexity is O(n) :param BinaryNode first: The first node :param BinaryNode second: The second node :param BinaryNode tree: The root of a binary tree containing the provided nodes :return: The first common ancestor. If one of the node's in an ancestor of the other, return that instead. :rtype: BinaryNode """ first_left, second_left = False, False first_right, second_right = False, False if first is tree or second is tree: return tree for value in traverse_binary_tree_pre_order(tree.left): if value == first.value: first_left = True elif value == second.value: second_left = True for value in traverse_binary_tree_pre_order(tree.right): if value == first.value: first_right = True elif value == second.value: second_right = True if first_left and second_left: return find_common_ancestor_without_parents(first, second, tree.left) elif first_right and second_right: return find_common_ancestor_without_parents(first, second, tree.right) elif not (first_left or first_right) or not (second_left or second_right): raise ValueError("Unable to find both of the nodes in the provided tree") else: return tree def find_common_ancestor_with_directions(first, second, tree): """ Finds the first common ancestor between two nodes in a tree structure where nodes have no links back to their respective parents. Instead, we populate nodes in the tree with directions to the specified nodes and use those to locate the first common ancestor. :param BinaryNodeWithDirections first: The first node :param BinaryNodeWithDirections second: The second node :param BinaryNodeWithDirections tree: The root of a binary tree containing the provided nodes :return: The first common ancestor. If one of the node's is an ancestor of the other, return that instead. :rtype: BinaryNodeWithDirections """ first_available, second_available = populate_tree_directions(first, second, tree) if not first_available and second_available: raise ValueError("Unable to find both of the nodes in the provided tree") node = tree while node.first_direction == node.second_direction: if node.first_direction == NodeDirection.left: node = node.left elif node.first_direction == NodeDirection.right: node = node.right elif node.first_direction == NodeDirection.here: break else: raise ValueError("Got unexpected direction instruction." "Check the binary tree was populated correctly.") return node def populate_tree_directions(first, second, tree): """ Populate nodes in the tree with directions to the provided first and second nodes :param BinaryNodeWithDirections first: The first node :param BinaryNodeWithDirections second: The second node :param BinaryNodeWithDirections tree: The root of the binary tree :return: Two booleans indicating whether the respective first and second nodes are available in the current tree :rtype: tuple[boolean, boolean] """ # Reset the directions on each node if it's not the one we want tree.first_direction = NodeDirection.here if tree is first else None tree.second_direction = NodeDirection.here if tree is second else None if tree.first_direction is tree.second_direction is NodeDirection.here: return True, True for branch, direction in (tree.left, NodeDirection.left), (tree.right, NodeDirection.right): if not branch: continue first_found, second_found = populate_tree_directions(first, second, branch) if first_found: tree.first_direction = direction if second_found: tree.second_direction = direction first_found, second_found = tree.first_direction is not None, tree.second_direction is not None return first_found, second_found def get_tree_levels(tree): """ Attempts to flatten a binary search tree into its individual component levels e.g. Input ----- 4 <--- 1st level / \ 2 6 <--- 2nd level /\ /\ 1 3 5 7 <--- 3rd level ... Output ------ [[4], [2, 6], [1, 3, 5, 7] ...] :param BinaryNode tree: The root node of a binary search tree :return: A collection of layers :rtype: list[list[int]] """ if not tree: return [] levels = [[tree.value]] further_levels = get_tree_levels(tree.left) for l in further_levels: levels.append(l) further_levels = get_tree_levels(tree.right) for i, l in enumerate(further_levels, start=1): if i >= len(levels): levels.append(l) else: levels[i].extend(l) return levels def get_tree_creation_values(tree): """ Gets all possible combinations of ordered values that can be used to create a binary search tree :param BinaryNode tree: The root node of a binary search tree :return: All possible permutations of input values that can create the provided binary tree when traversed in order e.g. Input ----- 4 <--- 1st level / \ 2 6 <--- 2nd level / 1 <--- 3rd level ... Output ------ [(4, 2, 6, 1), (4, 6, 2, 1), (4, 2, 1, 6), (4, 2, 6, 1)] The parent values of a node, must appear before their respective child nodes in the list """ nodes = [n for n in traverse_binary_tree_nodes(tree)] dependencies = create_parent_dependencies(tree) for p in permutations(nodes): inserted = {n: False for n in nodes} valid = True for node in p: inserted[node] = True parent = dependencies[node] if parent is None: continue elif inserted[parent] is False: valid = False break if valid: yield tuple([node.value for node in p]) def create_parent_dependencies(tree, parent=None): """ Creates a lookup table linking a current node in a binary tree to its respective parent node :param BinaryNode tree: The root node of the binary tree :param BinaryNode parent: The parent node of the provided tree :return: A lookup table to find the parent node for any given child :rtype: dict[BinaryNode, BinaryNode] """ dependencies = {} if not tree: return dependencies dependencies[tree] = parent for branch in tree.left, tree.right: further = create_parent_dependencies(branch, tree) for k, v in further.items(): dependencies[k] = v return dependencies def is_subtree(tree, subtree): """ Checks if a provided subtree is part of the provided tree :param BinaryNode tree: The root node of the main tree :param BinaryNode subtree: The root node of the subtree :return: True if the subtree is part of the main tree, False otherwise :rtype: bool """ first = traverse_binary_tree_nodes(tree) for n in first: if n.value != subtree.value: continue st1 = traverse_binary_tree_nodes(n) second = traverse_binary_tree_nodes(subtree) matched = True for n1, n2 in izip_longest(st1, second): if n1.value != n2.value: matched = False break if matched: return True return False class BinaryTree(object): """ Models a binary search tree with basic functionality """ def __init__(self): self._root = None # type: BinaryNode def insert(self, value): """ Inserts a specific value into the binary tree :param int value: The value to insert """ node = BinaryNode(value) self._insert(node) def insert_node(self, node): """ Inserts a specific node into the binary tree :param BinaryNode node: The node to insert """ self._insert(node) def _insert(self, node): """ Inserts a new node into the binary tree :param BinaryNode node: A value to insert into the tree """ if self._root is None: self._root = node return current = self._root while True: if node.value < current.value: if current.left: current = current.left else: current.left = node break elif node.value >= current.value: if current.right: current = current.right else: current.right = node break def find(self, value): """ Tries to find the provided value in the binary tree using a depth-first search approach :param int value: A value to find in the tree :return: True and the node if the value exists in the binary tree, False and None otherwise :rtype: tuple[bool, BinaryNode] """ stack = [self._root] while stack: current = stack.pop() if current.value == value: return True, current if current.right and value >= current.value: stack.append(current.right) if current.left and value < current.value: stack.append(current.left) return False, None def find_parent(self, value): """ Tries to find the parent node of the provided value in the binary tree using a depth-first search approach :param int value: A value to find in the tree :return: True and the parent node if the value exists in the binary tree, False and None otherwise :rtype: tuple[bool, BinaryNode] """ stack = [self._root] while stack: current = stack.pop() if current.left and current.left.value == value: return True, current if current.right and current.right.value == value: return True, current if current.right and value >= current.value: stack.append(current.right) if current.left and value < current.value: stack.append(current.left) return False, None def delete(self, value): """ Deletes the first discovered node in the tree with the provided value :param int value: The value of a node to remove """ if value == self._root.value: removed = self._root self._root = self._root.left if self._root.left else self._root.right if self._root.left: self.insert_node(removed.left) if self._root.right: self.insert_node(removed.right) return found, node = self.find_parent(value) if not found: return if node.left and node.left.value == value: removed = node.left node.left = None for n in traverse_binary_tree(removed.left): self.insert(n) for n in traverse_binary_tree(removed.right): self.insert(n) elif node.right and node.right.value == value: removed = node.right node.right = None for n in traverse_binary_tree(removed.left): self.insert(n) for n in traverse_binary_tree(removed.right): self.insert(n) def balance(self): """ Balances a binary tree so it's depth does not vary across the tree by more than one """ values = traverse_binary_tree(self._root) self._root = create_binary_tree(list(values)) def get_random(self): """ Gets a random value from the binary tree :return: A random value :rtype: int """ entries = 0 for _ in traverse_binary_tree(self._root): entries += 1 random_number = randint(0, entries) entries = 0 for value in traverse_binary_tree(self._root): entries += 1 if entries >= random_number: return value def count_paths_with_sum(node, required, sum_so_far=0): """ Counts the number of paths branching from a given node that have cumulative totals that equal the required value :param BinaryNode node: The binary tree node :param int required: The required value :param int sum_so_far: The current cumulative total from previous branches :return: The number of paths with the cumulative sum :rtype: int """ total = 0 new_sum = sum_so_far + node.value if new_sum == required: total += 1 if node.left: total += count_paths_with_sum(node.left, required, new_sum) if node.right: total += count_paths_with_sum(node.right, required, new_sum) return total
import unittest from sorting_and_searching_algorithms import merge_two_sorted_lists,\ sort_by_anagram,\ search_in_rotated_array class TestSortingAndSearchingAlgorithms(unittest.TestCase): def test_merge_two_sorted_lists(self): """ Checks we can merge one list into another """ a = [0, 2, 3, None, None, None, None] b = [0, 1, 2, 4] expected = [0, 0, 1, 2, 2, 3, 4] result = merge_two_sorted_lists(a, b) self.assertListEqual(expected, result) def test_sort_by_anagram(self): """ Checks we correctly sort and group a list by strings that are anagrams of each other """ unsorted = ["a", "b"] expected = ["a", "b"] self.assertListEqual(sort_by_anagram(unsorted), expected) unsorted = ["c", "b", "a"] expected = ["c", "b", "a"] self.assertListEqual(sort_by_anagram(unsorted), expected) unsorted = ["ab", "c", "ba"] expected = ["ab", "ba", "c"] self.assertListEqual(sort_by_anagram(unsorted), expected) unsorted = ["cabde", "c", "ebadc"] expected = ["cabde", "ebadc", "c"] self.assertListEqual(sort_by_anagram(unsorted), expected) unsorted = ["xyz", "xyw", "yzx"] expected = ["xyz", "yzx", "xyw"] self.assertListEqual(sort_by_anagram(unsorted), expected) unsorted = ["xyz", "yyy", "xzx", "yxz", "jef", "xyz"] expected = ["xyz", "yxz", "xyz", "yyy", "jef", "xzx"] self.assertListEqual(sort_by_anagram(unsorted), expected) unsorted = ["xyz", "yyy", "xzx", "yxz", "yyy", "xyz", "yyy"] expected = ["xyz", "yxz", "xyz", "yyy", "yyy", "yyy", "xzx"] self.assertListEqual(sort_by_anagram(unsorted), expected) def test_search_in_rotated_array(self): array = [1, 2, 3, 4, 5, 6] search_value = 1 expected_index = 0 actual_index = search_in_rotated_array(array, search_value) self.assertEqual(expected_index, actual_index) array = [1, 2, 3, 4, 5, 6] search_value = 5 expected_index = 4 actual_index = search_in_rotated_array(array, search_value) self.assertEqual(expected_index, actual_index) rotated_array = [4, 5, 6, 1, 2, 3] search_value = 5 expected_index = 1 actual_index = search_in_rotated_array(rotated_array, search_value) self.assertEqual(expected_index, actual_index) rotated_array = [4, 5, 6, 1, 2, 3] search_value = 3 expected_index = 5 actual_index = search_in_rotated_array(rotated_array, search_value) self.assertEqual(expected_index, actual_index) rotated_array = [6, 1, 2, 3, 4, 5] search_value = 6 expected_index = 0 actual_index = search_in_rotated_array(rotated_array, search_value) self.assertEqual(expected_index, actual_index)
import tkinter as tk """classe de la startpage : incluant des variables ou des fonctions qui permettent de definir un objet, ici tout ce qui compose la start page c'est a dire le menu principale ou l'on decide de jouer ou consulter les regles du jeu cette page est reliée a la page 1 et 2. """ class StartPage(tk.Frame): """constructeur de la classe: fonction appelé à l'initialisation d'un objet de cette classe""" def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Menu que desirez vous faire", font=controller.title_font) label.pack(side="top", fill="x", pady=10) """initialisation des boutons pour lancer le jeu et les regles du jeu puis affichage des boutons""" button1 = tk.Button(self, text="Lancer le jeu", command=lambda: controller.show_frame("PageOne")) button2 = tk.Button(self, text="Règles du jeu", command=lambda: controller.show_frame("PageTwo")) button1.pack() button2.pack() """ class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="This is the start page", font=(controller.title_font, 30),bg='#FF775A',foreground='white') label.pack(side="top", fill="x", pady=10, expand=YES) cadre = Frame(self) cadre.pack(expand=NO) button1 = tk.Button(cadre, text="Lancer le jeu",font=('Arrial',20),bg='#FF775A', command=lambda: controller.show_frame("PageOne")) button2 = tk.Button(self, text="Règles du jeu",font=('Arrial',10),bg='#FF775A', command=lambda: controller.show_frame("PageTwo")) button1.config( height = 3, width = 10,relief=FLAT) button2.config( height = 1, width = 10,relief=FLAT) button1.pack(pady=10) button2.pack(pady=60) """
''' Facebook_Easy 10.2 8:37pm 从1开始 1 11 21 1211 111221 循环比递归快 从空间复杂度和时间复杂度分析 ''' # 循环 class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ laststr = '1' i = 1 while i < n: s = str() v = laststr[0] j = 1 count = 1 while j < len(laststr): if laststr[j] != v: s = s + str(count) + v count = 1 v = laststr[j] else: count += 1 j += 1 laststr = s + str(count) + v i += 1 return laststr # 递归 class Solution: def countAndSay(self, n): """ :type n: int :rtype: str """ if n ==1 : return '1' ret = self.countAndSay(n-1) s = '' i = 0 while i < len(ret): j = 1 while i+j < len(ret) and ret[j+i] == ret[i]: j+=1 s = s + str(j) + str(ret[i]) i+=j return s
''' 按照一个方向走,撞到墙才能改方向 要求找到能不能最后停到destination的位置 思路: BFS Time complexity : O(mn)O(mn). Complete traversal of maze will be done in the worst case. Here, mm and nn refers to the number of rows and coloumns of the maze. Space complexity : O(mn)O(mn). visitedvisited array of size m*nm∗n is used and queuequeue size can grow upto m*nm∗n in worst case. ''' class Solution: def hasPath(self, maze, start, destination): # 队列 Q = [start] n = len(maze) m = len(maze[0]) # 四个方向 dirs = ((0, 1), (0, -1), (1, 0), (-1, 0)) while Q: # Use Q.pop() as DFS or Q.popleft() with deque from collections library for better performance. Kudos to @whglamrock i, j = Q.pop(0) # 标识走到过 maze[i][j] = 2 if i == destination[0] and j == destination[1]: return True for x, y in dirs: row = i + x col = j + y # 当合理且不是墙,沿这个方向一直走 while 0 <= row < n and 0 <= col < m and maze[row][col] != 1: row += x col += y row -= x col -= y # 不是墙 if maze[row][col] == 0: Q.append([row, col]) return False
def median(A, B): # A和B的长度 m, n = len(A), len(B) # 如果 A比B长,交换AB,保证j大于0 if m > n: A, B, m, n = B, A, n, m if n == 0: raise ValueError # 中位数左边的长度,可以包括中位数 imin, imax, half_len = 0, m, (m + n + 1) // 2 while imin <= imax: # 将A砍半 i = (imin + imax) // 2 # 获得对应的在B的坐标,是的A的left和B的left长度加起来是一半 j = half_len - i # 如果是B的left的最后一个值大于A的right的第一个值,说明要右移 if i < m and B[j - 1] > A[i]: # i is too small, must increase it imin = i + 1 # 否则左移 elif i > 0 and A[i - 1] > B[j]: # i is too big, must decrease it imax = i - 1 else: # i is perfect # 找到left的最大值 if i == 0: max_of_left = B[j - 1] elif j == 0: max_of_left = A[i - 1] else: max_of_left = max(A[i - 1], B[j - 1]) # 如果m和n加起来是奇数,返回这个max_of_left if (m + n) % 2 == 1: return max_of_left # 找到right的最小值 if i == m: min_of_right = B[j] elif j == n: min_of_right = A[i] else: min_of_right = min(A[i], B[j]) # 返回 return (max_of_left + min_of_right) / 2.0
class Solution: def reverseWords(self, str): """ :type str: List[str] :rtype: void Do not return anything, modify str in-place instead. """ # 先把整个str翻转 self.reverse(str, 0, len(str) - 1) i = 0 j = 0 # 再把每个单词翻转 while i < len(str): if str[i] == ' ': self.reverse(str, j, i - 1) j = i + 1 i += 1 # 最后还要翻转了最后一个word self.reverse(str, j, i - 1) def reverse(self, str, i, j): while i < j: str[i], str[j] = str[j], str[i] i += 1 j -= 1
''' LinkedIn_Easy 10.12 11:33am ''' import math class Solution(object): def judgeSquareSum(self, c): """ :type c: int :rtype: bool """ i = c // 2 j = c - i (square_i, value1) = self.isSquare(i) (square_j, value2) = self.isSquare(j) if square_i and square_j: return True while value1 >= 0: if value1 ** 2 + value2 ** 2 == c: return True elif value1 ** 2 + value2 ** 2 > c: value1 -= 1 else: value2 += 1 return False def isSquare(self, n): if n == 0 or n == 1: return True, n if n == 2 or n == 3: return False, 1 if n == 4: return True, 2 begin = 2 end = n // 2 while end - begin > 1: middle = (end + begin) // 2 middle_square = middle ** 2 if middle_square == n: return True, middle elif middle_square < n: begin = middle else: end = middle return False, begin
''' Uber_Medium 10.29 6:34pm ''' class Solution(object): def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ if not dict: return sentence root = Trie() for v in dict: trie = root for v1 in v: if v1 not in trie.d: trie.d[v1] = Trie() trie = trie.d[v1] trie.isRoot = True ret = '' i = 0 l = sentence.split(' ') for v in l: ret += ' ' trie = root i = 0 add_value = '' find = False while i < len(v): if v[i] in trie.d: # add_value += v[i] if trie.d[v[i]].isRoot: # ret += add_value find = True break trie = trie.d[v[i]] else: break i += 1 if not find: ret += v else: ret += v[:i + 1] return ret[1:] class Trie(object): def __init__(self): self.isRoot = False self.d = dict()
''' 题意: 给一组string 要求判断这个String matrix的每行每列是否相同 思路: 不能用zip 因为会有这种情况 Input: [ "abcd", "bnrt", "crm", "dt" ] Output: true ''' class Solution: def validWordSquare(self, words): """ :type words: List[str] :rtype: bool """ # 先判断words中最长的word的长度是否和word的总个数相等 max_len = 0 for v in words: max_len = max(max_len, len(v)) if len(words) != max_len: return False i = 0 while i < len(words): j = i+1 while j < len(words): # 对应的位置都为空或者对应位置的字符相同 if (j >= len(words[i]) and i >= len(words[j])) or (j < len(words[i]) and i < len(words[j]) and words[i][j] == words[j][i]): j+=1 else: return False i+=1 return True
# 不需要相对位置 def move_zeros(l): i = 0 j = len(l)-1 while i < j: if l[i] == 0 and l[j] != 0: l[i] = l[j] l[j] = 0 if l[i] != 0: i+=1 if l[j] == 0: j-=1 print(l) # 需要相对位置 def move_zeros_origin(l): i = 0 j = 0 while i < len(l) and l[i]: i+=1 j = i while i < len(l): if l[i]: l[j] = l[i] j+=1 i+=1 while j < len(l): l[j] = 0 j+=1 print(l) if __name__ == '__main__': move_zeros([0,1,0,1,3]) move_zeros_origin([0,1,0,1,3])
''' LinkedIn_Medium 10.14 6:27pm ''' # 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 findLeaves(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ l_ret = [] if not root: return l_ret l_left = self.findLeaves(root.left) l_right = self.findLeaves(root.right) i = 0 while i < len(l_left) and i < len(l_right): l_ret.append(l_left[i] + l_right[i]) i+=1 if i < len(l_right): l_ret += l_right[i:] if i < len(l_left): l_ret += l_left[i:] l_ret.append([root.val]) # print(l_ret) return l_ret
from collections import OrderedDict class LRUCache(object): def __init__(self, capacity): self.array = OrderedDict() self.capacity = capacity def get(self, key): if key in self.array: value = self.array[key] del self.array[key] self.array[key] = value return value else: return -1 def put(self, key, value): if key in self.array: # Delete existing key before refreshing it # del self.array[key] self.array.pop(key) elif len(self.array) >= self.capacity: # Delete oldest self.array.popitem(last=False) //这个相当于把要删除的放在dict的首位 # self.array.pop(k) self.array[key] = value
class TreeNode(object): def __init__(self, val): self.val = val self.neighbor = [] def solution(A, E): # write your code in Python 3.6 if not A: return 0 nodes = [TreeNode(v) for v in A] def same_value_path(node, val): if node.val == val: same_sub = 0 for n in node.neighbor: same_sub = max(same_sub, same_value_path(n, val)) return same_sub + 1 else: return 0 def longest_path(node): sub = 0 for n in node.neighbor: sub = max(sub, longest_path(n)) same_sub = 0 for n in node.neighbor: same_sub += same_value_path(n, node.val) return max(same_sub, sub) store = [n for n in nodes] i = 0 while i < len(E): n1 = nodes[E[i] - 1] n2 = nodes[E[i + 1] - 1] if n2 not in store: n2.neighbor.append(n1) store.pop(n1) elif n1 not in store: n1.neighbor.append(n2) store.pop(n2) else: n1.neighbor.append(n2) store.pop(n2) i += 2 return longest_path(store[0]) if __name__ == '__main__': solution([1,1,1,2,2],[1,2,3,1,2,4,2,5])
''' 通过函数构建层级图。第一个函数是set(雇员a,雇员b)意思是令ab为同一直接manager的下属。 第二个函数是set(雇员a 经理m)意思是令m成为a的直接上属。 还有一个get(a)是要求你返回从a往上所有的管理关系链直到顶层。 沟通了输入输出,刚开始有点误解,小哥说没有input,后来搞了半天input是一堆构建图的query, 就是set函数。相当于你一般构建图 一边根据已有的图返回管理链。自己定义了类,开始实现。 复杂的地方在:如果ab同级 bc同级 cd同级,这时候get a没有一个链可以返回。但是这时候设置d的直接经理是m 那么abc都要更新。 思路: 相当于构件图 用一个employee的类存储员工的经理和同事 ''' class Employee(object): def __init__(self,num): self.manager = None self.colleague = [] self.number = num class Relationship(object): def __init__(self): self.record = dict() def setM(self, e, m): if e not in self.record: self.record[e] = Employee(e) if m not in self.record: self.record[m] = Employee(m) self.record[e].manager = self.record[m] for v in self.record[e].colleague: self.record[v].manager = self.record[m] def setC(self,e1,e2): if e1 not in self.record: self.record[e1] = Employee(e1) if e2 not in self.record: self.record[e2] = Employee(e2) self.record[e1].colleague.append(self.record[e2]) self.record[e2].colleague.append(self.record[e1]) def get(self, e): ret = [] if e in self.record: m = self.record[e] while m: ret.append(m.number) e,m = m,m.manager return ret else: return [e]
''' Facebook_Medium 11.9 11:24pm ''' class Solution: def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ if len(nums) < 2: return False if k < 0: k = -k if k == 0: for i in range(1, len(nums)): if nums[i] == 0 and nums[i - 1] == 0: return True return False if k == 1: return True record = dict() record[nums[0] % k] = [] record[nums[0] % k].append(0) for i in range(1, len(nums)): nums[i] += nums[i - 1] if not nums[i] % k: return True remain = nums[i] % k if remain in record: if record[remain][0] < i - 1: return True else: record[remain].append(i) else: record[remain] = [i] return False if __name__ == '__main__': s = Solution() print(s.checkSubarraySum([-2, -2, 8],6))
''' 题意:看nums中有没有的3个递增的sequence ''' class Solution: def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ # 记录first和second数的index a = -1 b = -1 for i, v in enumerate(nums): # 如果没有a,或者v比a对应的位置小 if a == -1 or v < nums[a]: a = i # 如果v大于a的位置且b没有或者v比b位置小 elif v > nums[a] and (b == -1 or v < nums[b]): b = i # b存在且v大于b elif b != -1 and v > nums[b]: return True return False
''' 题意: 找到BST中和target最接近的数字 注意这个target是float类型的 本质是遍历BST ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def closestValue(self, root, target): """ :type root: TreeNode :type target: float :rtype: int """ sub = float('inf') last_val = 0 while root: if root.val < target: if target - root.val < sub: last_val = root.val sub = target-root.val root = root.right elif root.val > target: if root.val- target < sub: last_val = root.val sub = root.val-target root = root.left else: return root.val return last_val
''' 假设有一条高速公路,路面上有n辆车,每辆车有不同的整数速度, 但是都在1-n范围内。现在给你一个数组,代表每辆车的速度。 车辆出发顺序即数组顺序,问最后可以形成几个集群,每个集群的size是多少? 可以理解为,虽然车辆速度不同,但是即使后面的车比前面的车速度快,因为不能超车, 最后肯定只能以前车的速度行驶,这就形成了一个集群。 比如[2,4,1,3],最后[2,4]是一个集群,[1,3]是一个集群。 follow-up: 假设想再加入一辆车,这个车的速度比其他车都大,但是不确定这个车的出发顺序, 让输出最后所有可能的每个集群的大小(List of List) 这辆车可以放在最前面出发,集群数目就是1+前面的结果,一个size 为1的集群+各个其余的size不变, ''' def colls(speeds): ret = [] i = 0 while i < len(speeds): j = i+1 # 找递增序列 while j < len(speeds) and speeds[j] >= speeds[i]: j+=1 ret.append(speeds[i:j]) i = j return ret if __name__ == '__main__': print(colls(speeds=[2,4,1,3]))
''' 题意:有一个时间HH:MM;要求用之前时间里面出现的数字组成另一个时间,且这个时间在当前时间的后面,也可以是下一天 Input: "19:34" Output: "19:39" Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later. Input: "23:59" Output: "22:22" Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller than the input time numerically. ''' class Solution: def nextClosestTime(self, time): """ :type time: str :rtype: str """ hs = list() ms = list() l = list(time) l = list(set(l[:2] + l[3:])) # 排序时间中的数字;然后排列组合肯定就是从小到大了且没有重复 l.sort() h = int(time[:2]) m = int(time[3:]) for i in l: for j in l: t = int(i + j) if t < 24: hs.append(t) if t < 60: ms.append(t) # 分钟时钟都是最大的 if max(hs) <= h and max(ms) <= m: return str(min(hs)).zfill(2) + ':' + str(min(ms)).zfill(2) # 分钟最大 elif max(ms) <= m: # hs.sort() return str(hs[hs.index(h) + 1]).zfill(2) + ':' + str(min(ms)).zfill(2) # 其他,改分钟就行了 else: # ms.sort() return str(h).zfill(2) + ':' + str(ms[ms.index(m) + 1]).zfill(2)
''' Facebook_Easy 11.05 11:05pm ''' class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if not num1: return num2 if not num2: return num1 ret = '' i = -1 j = -1 carrying = 0 while i > -1 - len(num1) and j > -1 - len(num2): s = int(num1[i]) + int(num2[j]) + carrying ret = str(s % 10) + ret carrying = s // 10 i -= 1 j -= 1 if i == -1 - len(num1) and j == -1 - len(num2): if carrying: return '1' + ret else: return ret elif i == -1 - len(num1): while j > -1 - len(num2): if not carrying: return num2[:j + 1] + ret s = int(num2[j]) + carrying ret = str(s % 10) + ret carrying = s // 10 j -= 1 else: while i > -1 - len(num1): if not carrying: return num1[:i + 1] + ret s = int(num1[i]) + carrying ret = str(s % 10) + ret carrying = s // 10 i -= 1 if carrying: return '1' + ret else: return ret
def mul(a,b): l_a = [] l_b = [] res = 0 for i in range(len(a)): if a[i]: l_a.append((i,a[i])) if b[i]: l_b.append((i,b[i])) def find_in_b(loc): start = 0 end = len(l_b) while start<=end: mid = (start+end)//2 if l_b[mid][0] == loc: return l_b[mid][1] elif l_b[mid][0] < loc: start = mid+1 else: end = mid-1 return 0 for v in l_a: res += find_in_b(v[0]) * v[1] return res if __name__ == '__main__': print(mul([0,0,0,0,1,2,0,4],[1,7,0,2,0,0,3,1]))
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ # 如果k=1,直接返回head if k <= 1: return head # 设置一个dummy head在原本的head之前 psydu = ListNode(0) psydu.next = head # n1是上一次reverse返回的尾节点,连接着下一次reverse开始的点 n1 = psydu n2 = head count = 0 while n2: n2 = n2.next count += 1 # 当count=k的时候已经获得了k个可以reverse的点 if count == k: # 把这k个点reverse ret = self.reverse(n1.next, k) # 返回值的第一个是reverse后新的head n1.next = ret[0] # 返回值的第二个是下一次reverse开始的点 n2 = ret[1] # 返回值的第三个是这次reverse的尾节点 n1 = ret[2] count = 0 return psydu.next def reverse(self, node, count): # 这个begin记录了当前的开头,也就是reverse结束后的结尾 begin = node n1 = node n2 = node.next while count > 1: count -= 1 n3 = n2.next n2.next = n1 n1 = n2 n2 = n3 # 这个n2就是下一次reverse的开头,先和begin连起来 begin.next = n2 return (n1, n2, begin)
''' LinkedIn_Medium 10.12 3:08pm ''' class Solution(object): def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ i = 0 while i < len(flowerbed) and n: if flowerbed[i] == 1: i+=2 else: if i == len(flowerbed)-1: n-=1 break if flowerbed[i+1] == 1: i += 3 else: n-=1 i+=2 if n: return False return True
''' 看过去5min内发生过多少hit 思路: binary search ''' class HitCounter(object): def __init__(self): """ Initialize your data structure here. """ self.record = [] def hit(self, timestamp): """ Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: void """ self.record.append(timestamp) def getHits(self, timestamp): """ Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: int """ # 找到开始的时间,不包括 time = timestamp - 300 # 如果小于0,怎返回record的长度 if time <= 0: return len(self.record) # 通过bs找到该时间点是介于哪两个时间之间的,上届肯定比改时间大 begin = 0 end = len(self.record) - 1 while begin <= end: mid = (begin + end) // 2 if self.record[mid] <= time: begin = mid + 1 else: end = mid - 1 # begin是上届,end是下届,减去begin return len(self.record) - begin # Your HitCounter object will be instantiated and called as such: # obj = HitCounter() # obj.hit(timestamp) # param_2 = obj.getHits(timestamp)
class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.subtrie = dict() self.isWord = False self.val = '' def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ if not word: self.isWord = True return if word[0] not in self.subtrie: t = Trie() t.val = word[0] self.subtrie[word[0]] = t self.subtrie[word[0]].insert(word[1:]) def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ t = self for v in word: if v in t.subtrie: t = t.subtrie[v] else: return False return t.isWord def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ t = self for v in prefix: if v in t.subtrie: t = t.subtrie[v] else: return False return True # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
''' 题意: Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] Return 16 The two words can be "abcw", "xtfn" 要求这两个word中的字符不能有重复 思路: bit_manipulation 与运算 把每一个word转换为bit 注意一个word钟有重复字符的情况,要用set去重 ''' class Solution(object): def maxProduct(self, words): """ :type words: List[str] :rtype: int """ l = [] max_p = 0 for i in range(len(words)): l.append(len(words[i])) # 去重 words[i] = set(words[i]) n = 0 # 转换为数字 for v in words[i]: n += 2 ** (ord(v) - ord('a')) words[i] = n for i in range(len(words)): for j in range(i + 1, len(words)): if not words[i] & words[j]: max_p = max(max_p, l[i] * l[j]) return max_p class Solution(object): def maxProduct(self, words): """ :type words: List[str] :rtype: int """ d = {} for word in words: mask = 0 for c in set(word): # 右移 mask |= (1 << (ord(c) - ord('a'))) d[mask] = max(d.get(mask,0), len(word)) return max([d[x]* d[y] for x in d for y in d if not x & y] or [0])
class stack: def __init__(self): self.items = list() # Empty list for stack def push(self,item): self.items.insert(0,item) def pop(self): self.items.pop(0) def printstack(self): for each in self.items: print(each) stk = stack() # object of class stack ! stk.push(10) # call method push() to add something to the stack stk.push(20) stk.push(30) stk.push(40) stk.push(50) stk.push(60) print('==============** On pushing to stack **====================') stk.printstack() print() stk.pop() stk.pop() print('================** After Deletion **==================') stk.printstack()
# zahlenraten import random zufallszahl = random.randint(1,2) anzahlDerVersuche = 0 title = "Willkommen beim Zahlenraten!" text = "bitte geben sie eine zahl ein die zahl ist zwischen 1-100" eingabeText = "DeinVersuch: " print(title) print(text) fertig = False while fertig == False: zahl = int(input(eingabeText)) anzahlDerVersuche = anzahlDerVersuche + 1 if(zahl == zufallszahl): print("gewonnen") fertig = True elif(zahl < zufallszahl): print("die gesuchte Zahl ist größer") else: (zahl > zufallszahl) print("die gesuchte Zahl ist kleiner") print("super du hast nur ", anzahlDerVersuche, " benötigt") print("ende")
"""Bubble Sort Algorithm """ counter = 0 def sort(array): """Sorts an array.""" global counter for i in range(0, len(array) - 1): counter += 1 for j in range(i + 1, len(array)): counter += 1 if array[j] < array[i]: counter += 1 _swap(array, j, i) return array def _swap(array, a, b): array[a], array[b] = array[b], array[a]
""" One-Time-Pad Coder Encrypts and decrypts a text using the one-time-pad algorithm. """ from random import choice from string import ascii_letters, digits, punctuation from itertools import chain from operator import add, sub PAD = list(chain(ascii_letters, digits, punctuation, [' '])) def generate_key(text): return [choice(PAD) for _ in range(len(text))] def encrypt(text, key): return one_time_pad(text, key, add) def decrypt(text, key): return one_time_pad(text, key, sub) def one_time_pad(text, key, operation): return "".join([modular_operation(ch1, ch2, len(PAD), operation) for ch1, ch2 in list(zip(text, key))]) def modular_operation(char1, char2, size, operation): return to_character(operation(to_number_code(char1), to_number_code(char2)) % size) def to_number_code(char): return PAD.index(char) def to_character(num): return PAD[num]
""" Heap Sort Algorithm """ from math import log2 from operator import gt, lt def sort(array): for i in range(len(array), 0, -1): heapify(array, i, min_heap=False) array[0], array[i - 1] = array[i - 1], array[0] def heapify(heap, limit=None, min_heap=True): """Inserts the elements in the heap.""" def _sift_down(index): pos = index parent = parent_position(pos) while parent >= 0 and oper(heap[pos], heap[parent]): heap[parent], heap[pos] = heap[pos], heap[parent] pos = parent parent = parent_position(parent) if not heap: return heap oper = lt if min_heap else gt _ = [_sift_down(index) for index in range(limit if limit else len(heap))] return heap def parent_position(pos): """Calculates the parent position given the current one, pos. Adds an error epsilon, so floating point precision is addressed by calculations. """ epsilon = 0.001 if pos == 0: return pos return round(2 ** (log2(pos) - 1) - 1 + epsilon)
#Escribir un programa que almacene el diccionario con los creditos de las asignaturas de un curso {'Matematicas': 6, 'Fisica': 4, 'Quimica': 5} y despues muestre por pantalla los creditos de cada asignatura en el formato <asignatura> tiene <creditos> creditos, # donde <asignatura> es cada una de las asignaturas del curso, y <creditos> son sus creditos. Al final debe mostrar tambien el numero total de creditos del curso. diccionarioAsignaturas = {"Matematicas": 6 , "Fisica": 4, "Quimica": 7, "Fisolofia": 5, "Ingles": 4, "Historia": 8} total_creditos = 0 for i in diccionarioAsignaturas.keys(): print "La asignatura "+i+" tiene "+str(diccionarioAsignaturas.get(i))+" creditos" total_creditos += diccionarioAsignaturas.get(i) print "Total creditos curso "+str(total_creditos)
#Escribir un programa que muestre el eco de lo que el usuario introduzca hasta que el usuario escriba 'salir' que terminara palabra = "" while(palabra != "salir"): palabra = input("Escribe una palabra: ") print palabra
#Escribir un programa que pregunte al usuario su nombre, edad, direccion y telefono y lo guarde en un diccionario. Despues debe mostrar por pantalla el mensaje <nombre> tiene <edad> annos, vive en <direccion> y su numero de telefono es <telefono>. diccionarioPersona = {} nombre = str(input("Introduce tu nombre: ")) edad = int(input("Introduce tu edad: ")) direccion = str(input("Introduce tu direccion: ")) telefono = int(input("Introduce tu telefono: ")) actualizar_diccionario = {"nombre": nombre, "edad": edad, "direccion": direccion, "telefono": telefono} diccionarioPersona.update(actualizar_diccionario) print diccionarioPersona
#Escribir un programa que pregunte al usuario una cantidad a invertir, el interes anual y el numero de anno, y muestre por pantalla el capital obtenido en la inversion cada anno que dira la inversion cantidad_invertir = int(input("Introduce una cantidad para invertir: ")) interes_anual = float(input("Introduce el interes anual: ")) annos_inversion = int(input("Introduce el numero de annos que va a durar la inversion: ")) #TODO hacer este ejercicio
#Ejercicio 9 txt = str(input("Write a text string ")) txt_low= txt.lower() def no_str(txt): if txt_low[0:2] == str("no"): print(txt) else: print(str("No ") + txt) no_str(txt)
from __future__ import print_function class Game2048Logic: # The board is simply a list of integers representing the cells # First element is top-left and so on left-to-right and then # top-to-bottom as a raster # Board cells contain a string which represents the tile # number or " " if the tile is empty or "X" if it could not # be determined (assumed empty) def getCellVal(self, cellStr): try: return int(cellStr) except ValueError: return 0 def pickAMove(self, boardCells): origBoard = [] for cell in boardCells: origBoard.append(self.getCellVal(cell)) print(origBoard) dirns = ['left','up','down','right'] bestDir = "" bestCombines = 0 bestCombineSum = 0 bestMoveCount = 0 bestBoard = [] for dir in dirns: cellMap = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] if dir == 'left': cellMap = [12,8,4,0,13,9,5,1,14,10,6,2,15,11,7,3] elif dir == 'down': cellMap = [15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0] elif dir == 'right': cellMap = [3,7,11,15,2,6,10,14,1,5,9,13,0,4,8,12] newBoard = origBoard[:] combines = 0 combineSum = 0 moveCount = 0 movesMade = True while(movesMade): movesMade = False for cellIdx in range(12): if newBoard[cellMap[cellIdx]] == 0: for idx in range(3 - cellIdx/4): if newBoard[cellMap[cellIdx+4+idx*4]] != 0: newBoard[cellMap[cellIdx+idx*4]] = newBoard[cellMap[cellIdx+4+idx*4]] newBoard[cellMap[cellIdx+4+idx*4]] = 0 movesMade = True moveCount += 1 for cellIdx in range(12): if newBoard[cellMap[cellIdx]] != 0 and newBoard[cellMap[cellIdx]] == newBoard[cellMap[cellIdx+4]]: combines += 1 combineSum += origBoard[cellMap[cellIdx]] * 2 newBoard[cellMap[cellIdx]] *= 2 newBoard[cellMap[cellIdx+4]] = 0 for idx in range(2 - cellIdx/4): newBoard[cellMap[cellIdx+4+idx*4]] = newBoard[cellMap[cellIdx+8+idx*4]] newBoard[cellMap[cellIdx+8+idx*4]] = 0 print(dir,"num combines", combines, "Sum", combineSum,"MoveCount", moveCount) if (bestCombines + bestMoveCount == 0 and combines + moveCount > 0) or \ (bestCombineSum < combineSum) or \ (bestMoveCount < moveCount and combineSum == bestCombineSum): bestCombines = combines bestDir = dir bestCombineSum = combineSum bestMoveCount = moveCount bestBoard = newBoard[:] print("Best Dir", bestDir) for i in range(len(bestBoard)): print('{:>6}'.format(bestBoard[i]),end='') if i % 4 == 3: print() return bestBoard, bestDir
import math """ 1. Crear una lista usando la función constructora `list(...)`. Imprimir en consola la lista """ # Usando la función constructora sería MyList = list(1,5,3,28,9) MyList = [1, 5, 3, 28, 9] print("Tarea 1.1.") print(MyList) print("\n") """ Tarea 1.2. 2. Crear una lista e imprimir en consola el tamaño de la lista. """ MyList = [1, 5, 3, 28, 9] print("Tarea 1.2") print(len(MyList)) print("\n") """ Tarea 1.3. 3. Crear una lista desordena y utilice el método sort para ordenarlo. """ MyList = sorted([1, 5, 3, 28, 9]) # Usando el método sort seria MyList.sort() print("Tarea 1.3") print(MyList) print("\n") """ Tarea 1.4. 4. Crear una lista desordenada, creer una función de ordenamiento y ordene la lista usando la función. """ # La idea de esta tarea es ordenar una lista de forma personalizada MyList = [1, 5, 3, 28, 9] def Ordenar(): MyList.sort() print("Tarea 1.4") Ordenar() print(MyList) print("\n") """ Tarea 1.5. 5. Crear una lista desordenada y ordene de forma inversa """ MyList = [1, 5, 3, 28, 9] MyList.sort(reverse=True) print("Tarea 1.5") print(MyList) print("\n") """ Tarea 2. (NUMEROS) Tarea 2.1. 1. Crear una variable que contenga un numero entero. Imprimir en consola el número y el tipo de dato. """ MyVar = 4 print("Tarea 2.1") print(MyVar, type(MyVar), "\n") """ 2. Crear una variable que contenga la operación de la multiplicación de dos números enteros. Ej: suma = 15*1235. Imprima en consola el resultado y el tipo de datos. """ MyProd = 458 * 6 print("Tarea 2.2") print(MyProd, type(MyProd)) print("\n") """ 3. Crear una variable que contenga la operación de división de dos números enteros. Ej: división = 10/2. Imprima en consola el resultado y el tipo de datos. """ MyDiv = int(878 / 2) print("Tarea 2.3") print(MyDiv, type(MyDiv)) print("\n") # Nota: Si a MyDiv no le coloco "int", el resultado de la división de dos enteros, # resulta en un número tipo "float"... ¿? """ 4. Crear un entero usando la función creadora `int(...)` a partir de un numero decimal. Imprimir en consola el número y el tipo de datos """ MyInt = int(math.pi) print("Tarea 2.4") print(MyInt, type(MyInt)) print("\n") # Nota: # Encontré en internet la forma de usar el número pi. Es a través de "import", me hablaste # algo de esto, pero no lo recuerdo. El sábado me refrescas esto, por favor. """ 5. Crear un entero usando la función creadora `int(...)` a partir de un texto. Imprimir en consola el número y el tipo de datos. """ MyInt = int("45") print("Tarea 2.5") print(MyInt, type(MyInt), "\n") """ 6. Crear un `float` usando la función creadora `float(...)` a partir de un número entero. Imprimir en consola el número y el tipo de datos. """ MyFloat = float(29) print("Tarea 2.6") print(MyFloat, type(MyFloat), "\n") """ 7. Crear un `float`usando la función creadora `float(...)` a partir de un texto. Imprimir en consola el número y el tipo de datos. """ MyFloat = float("3.23") print("Tarea 2.7") print(MyFloat, type(MyFloat), "\n") """ 3. (STRINGS) 1. Crear un texto usando la función constructora `str(...)`. Imprimir en consola el texto y el tipo de datos. """ MyText = str(2021) print("Tarea 3.1") print("Año: ", MyText) print(MyText, type(MyText), "\n") """ 2. Crear un texto de multiples líneas e imprimir en consola.""" MyText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n" MyText2 = "Integer non elit elit. Donec viverra nisi facilisis tellus fringilla ultrices.\n" MyText3 = MyText + MyText2 + \ "Ut porttitor ac lorem faucibus rhoncus. Aenean vel velit ex.\n" print("Tarea 3.2.") print(MyText3) # Otra forma: usando triple dobles comillas. MyText = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer non elit elit. Donec viverra nisi facilisis tellus fringilla ultrices. Ut porttitor ac lorem faucibus rhoncus. Aenean vel velit ex.""" print("Tarea 3.2.b.") print(MyText, "\n") """3. Crear un texto e imprimir en consola su longitud.""" MyText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit." print("Tarea 3.3.") print(len(MyText), "\n") """ 4. Crear un texto e imprimir en consola la primera y ultima letra en consola.""" MyText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" print("Tarea 3.4.") print(MyText[0], MyText[-1], "\n") """ 5. Crear un texto e imprimir una sección del texto que inicie con el texto hasta la mitad del mismo.""" MyText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" print("Tarea 3.") print(MyText[0:int((len(MyText)) / 2)], "\n") """ 6. Crear un texto e imprimir una sección del texto que inicie en la mitad del texto hasta el final.""" MyText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" print("Tarea 3.6") print(MyText[int((len(MyText)) / 2):], "\n") """ 7. Crear un texto de multiples palabras. Imprimir el texto en mayúsculas.""" MyText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" print("Tarea 3.7.") print(MyText.upper(), "\n") """ 8. Crear un texto de multiples palabras. Imprimir el texto en minúsculas.""" MyText = "LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT" print("Tarea 3.8.") print(MyText.lower(), "\n") """ 9. Crear un texto de multiples palabras. Remplazar la ultima palabra por otra e imprimir ambos textos""" # Debería usarse el método replace. MyText.replace(...) MyText = ["manzana", "mango", "patilla", "cambur"] print("Tarea 3.9") print(MyText) MyText2 = MyText[0:len(MyText) - 1] MyText2.append("mango") print(MyText2, "\n") # ¿Cómo hacer para que al imprimir una lista no aparezcan los corchetes? """10. Crear un texto de multiples palabras. Dividir el texto entre cada palabra. Ej: text = "Hola mundo" # output: ["Hola", "mundo"] """ MyText = "Germán Montero Alcalá" print("Tarea 3.10") MyText2 = MyText.split() print(MyText2, "\n") """ 11. Crear un texto plantilla y usa el método format para incluir texto dentro de la plantilla. """ # No recuerdo qué es un "texto plantilla", hice el ejercicio con lo que encontré # en internet. print("Tarea 3.11") MyText = "Nombre: {nombre}" print(MyText.format(nombre="Germán"), "\n") """ 12. Crear un texto plantilla con 3 espacios disponibles. Usa el método format para incluir textos dentro de la plantilla. """ MyText = "Fruta 1: {}, Fruta 2: {}, Fruta 3: {}" print("Tarea 3.12.") print(MyText.format("Mango", "Uva", "Níspero"), "\n") """ 13. Crear un texto y contar la cantidad de veces que se repite una letra.""" # No me acuerdo cuál fue el método del curso, # busqué en internet "Character counting in Python". print("Tarea 3.13") MyText = "Maracaibo, la tierra del sol amada" print(MyText) MyLetter = "a" print("Cantidad de:", '"', MyLetter, '":', MyText.count(MyLetter), "\n")
from math import sqrt from itertools import permutations def square_root_int(x): return int(sqrt(x)) def prime(number): if number == 1: return False upper_bound = square_root_int(number) + 1 for x in range(2, upper_bound): if x == number: next if number % x == 0: return False return True def permutations_list(number): ps = [] permutations_ = permutations(str(number)) for permutation in permutations_: num = '' for n in permutation: num += n ps.append(int(num)) return ps def circular_prime(x): permutationsl = permutations_list(x) print(permutationsl) for n in permutationsl: if prime(n): next return False return True def solve(): return sum(1 for x in range(1, 101) if circular_prime(x)) if __name__ == '__main__': result = solve() print(result)
def prime(n): if n == 2 or n == 3: return True if n % 2 == 0 or n < 2: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def factors(n): f, s = 2, set() while n > 1: if n % f == 0: n = int(n / f) s.add(f) else: f += 1 return s print(max([n for n in factors(600851475143) if prime(n)]))
# Восстановление траектории шахматного коня # 64 вершины letters = 'abcdefgh' numbers = '12345678' graph = dict() # создаём 64 именованные вершины (8×8) for l in letters: for n in numbers: graph[l+n] = set() def add_edge(v1, v2): graph[v1].add(v2) graph[v2].add(v1) # ходим конём (1, 2) по клеткам, добавляем если такие клетки существуют на поле ( for i in range(8): for j in range(8): v1 = letters[i] + numbers[j] if 0 <= i + 2 < 8 and 0 <= j + 1 < 8: v2 = letters[i+2] + numbers[j+1] add_edge(v1, v2) if 0 <= i - 2 < 8 and 0 <= j + 1 < 8: v2 = letters[i-2] + numbers[j+1] add_edge(v1, v2) if 0 <= i + 1 < 8 and 0 <= j + 2 < 8: v2 = letters[i+1] + numbers[j+2] add_edge(v1, v2) if 0 <= i - 1 < 8 and 0 <= j + 2 < 8: v2 = letters[i-1] + numbers[j+2] add_edge(v1, v2) # не перебрали варианты для j-1 и j-2 для v1, # потому что они наверняка будут перебраны из v2 по ходу прохождения по доске from collections import deque distances = {v: None for v in graph} parents = {v: None for v in graph} start_vertex = 'd4' end_vertex = 'f7' distances[start_vertex] = 0 queue = deque([start_vertex]) while queue: cur_v = queue.popleft() for neigh_v in graph[cur_v]: if distances[neigh_v] is None: distances[neigh_v] = distances[cur_v] + 1 queue.append(neigh_v) path = [end_vertex] parent = parents[end_vertex] while not parent is None: path.append(parent) parents = parents[parent]
A = set('bqlpzlkwehrlulsdhfliuywemrlkjhsdlfjhlzxcovt') B = set('zmxcvnboaiyerjhbziuxdytvasenbriutsdvinjhgik') # for x in A: # if x not in B: # print(x) print({x for x in A if x not in B}) # ================================== A = set('0123456789') B = set('02468') C = set('12345') D = set('56789') E = A.difference(B).intersection(C.difference(D)).union(D.difference(A).intersection(B.difference(C))) print(E) F = A.difference(B) G = C.difference(D) H = D.difference(A) I = B.difference(C) J = F.intersection(G) K = H.intersection(I) E = J.union(K) print(E)
# Хранение графа в памяти # возьмём простейший граф: # A -- B -- C -- D # 1 список вершин + список рёбер V = {"A", "B", "C", "D"} # N — порядок графа E = {("A", "B"), ("B", "C") ("C", "D")} # M — размер графа # Быстро проверяем наличие вершины, ребра — О(1) # Перебор всех соседей вершины — О(N) # 2 матрица смежности # подходит для простых графов V = ["A", "B", "C", "D"] # для быстрого доступа к индексам вершин index = {V[i]: i for i in range(len(V))} # dict comprehention # матрица смежности: # A B C D # A 0 1 0 0 # B 1 0 1 0 # C 0 1 0 1 # D 0 0 1 0 # матрица квадратная # все петли находятся на главной диагонали (здесь одни нули) # если граф неориентированный, то матрица симметрична относительно главной диагонали (так) # сумма всех единичек равна удовенному M # сумма единиц в столбце или строке показывает степень вершины # храним как список списков A = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]] # факт проверки наличия ребра — О(1) + О(1) # перебор всех соседей — О(M) # главный плюс — простота реализации на любом сколь угодно убогом языке # 3 Списки смежности # для каждой вершины — множество соседей # А: B # B: A, C # C: B, D # D: C G = {"A": {"B"}, "B": {"A", "C"}, "C": {"B", "D"}, "D": {"C"}} # факт проверки ребро или не ребро: ищем являются ли вершины соседями — О(1) # перебор соседей: for neighbour in G[v]: pass # — O(число соседей) # Чаще всего граф подают списком рёбер либо списком вершин # Как мысленно разделять номера вершин и индексы # 1. каждый раз считать +1 или -1 # 2. добавить фиктивную пустую вершину с индексом 0
# # подключение библиотеки под синонимом gr # import graphics as gr # # Инициализация окна с названием "Russian game" и размером 100х100 пикселей # window = gr.GraphWin("Russian Game", 100, 100) # # Инициализация окна с названием "Russian game" и размером 100х100 пикселей # # window.close() # # Создание круга с радиусом 10 и координатами центра (50, 50) # my_circle = gr.Circle(gr.Point(50, 50), 10) # # Создание отрезка с концами в точках (2, 4) и (4, 8) # my_line = gr.Line(gr.Point(2, 4), gr.Point(4, 8)) # # Создание прямоугольника у которого диагональ — отрезок с концами в точках (2, 4) и (4, 8) # my_rect = gr.Rectangle(gr.Point(2, 4), gr.Point(4, 8)) # # Отрисовка примитивов в окне window # my_circle.draw(window) # my_line.draw(window) # my_rect.draw(window) # # Ожидание нажатия кнопки мыши по окну. # window.getMouse() # # После того как мы выполнили все нужные операции, окно следует закрыть. # window.close() import graphics as gr window = gr.GraphWin("Lab_4", 788, 584) def draw_sky(): sky = gr.Rectangle(gr.Point(0, 0), gr.Point(788, 320)) sky.setFill(gr.color_rgb(66, 139, 216)) sky.setWidth(0) sky.draw(window) def draw_land(): land = gr.Rectangle(gr.Point(0, 320), gr.Point(788, 584)) land.setFill(gr.color_rgb(163, 247, 181)) land.setWidth(0) land.draw(window) def draw_house(): house_body = gr.Rectangle(gr.Point(200, 220), gr.Point(400, 420)) house_body.setFill(gr.color_rgb(200, 180, 140)) house_body.setOutline(gr.color_rgb(160, 140, 100)) house_body.setWidth(5) house_body.draw(window) house_roof = gr.Polygon(gr.Point(190, 220), gr.Point(300, 110), gr.Point(410, 220)) house_roof.setFill(gr.color_rgb(140, 25, 30)) house_roof.setOutline(gr.color_rgb(100, 5, 10)) house_roof.setWidth(5) house_roof.draw(window) house_window = gr.Rectangle(gr.Point(250, 260), gr.Point(350, 360)) house_window.setFill(gr.color_rgb(132, 205, 255)) house_window.setWidth(5) house_window.draw(window) line1 = gr.Line(gr.Point(300, 260), gr.Point(300, 360)) line2 = gr.Line(gr.Point(250, 310), gr.Point(350, 310)) line1.setWidth(5) line2.setWidth(5) line1.draw(window) line2.draw(window) def draw_cloud(): pass def draw_sun(): sun = gr.Circle(gr.Point(700,100), 40) sun.setFill('yellow') sun.setOutline('orange') sun.setWidth(10) sun.draw(window) def draw_tree(): tree_1 = gr.Polygon(gr.Point(525, 450), gr.Point(625, 350), gr.Point(725, 450)) tree_2 = gr.Polygon(gr.Point(525, 400), gr.Point(625, 300), gr.Point(725, 400)) tree_3 = gr.Polygon(gr.Point(525, 350), gr.Point(625, 250), gr.Point(725, 350)) tree_1.setFill(gr.color_rgb(60, 200, 160)) tree_2.setFill(gr.color_rgb(60, 200, 160)) tree_3.setFill(gr.color_rgb(60, 200, 160)) tree_1.setOutline(gr.color_rgb(50, 160, 150)) tree_2.setOutline(gr.color_rgb(50, 160, 150)) tree_3.setOutline(gr.color_rgb(50, 160, 150)) tree_1.setWidth(5) tree_2.setWidth(5) tree_3.setWidth(5) tree_leg = gr.Rectangle(gr.Point(600, 450), gr.Point(650, 525)) tree_leg.setFill(gr.color_rgb(100, 65, 70)) tree_leg.setOutline(gr.color_rgb(80, 55, 50)) tree_leg.setWidth(5) tree_leg.draw(window) tree_1.draw(window) tree_2.draw(window) tree_3.draw(window) def draw_picture(): draw_sky() draw_cloud() draw_sun() draw_land() draw_house() draw_tree() draw_picture() window.getMouse() window.close()
# === именованный кортеж === # точка в 3D пространстве: A = (1, 0, 3) # например найти расстояние от центра координат r = math.sqrt(A[0]**2 + A[1]**2 + A[2]**2) # не говорящие названия, не удобно использовать # хочется A.x, A.y, A.z # можно создать класс, но много возни, можно проще from collections import namedtuple # создаём тип точки Point = namedtuple("Point", "x y z") A = Point(1, 0, 3) print(A.x) # именованный кортеж тоже не изменяемый
""" Topic to be Covered - Multivariate Linear Regression @author: aly """ ''' #Step 1 - Import the necessary libraries and the dataset #Step 2 - Plot the Seaborn Pairplot #Step 3 - Plot the Seaborn Heatmap #Step 4 - Extract the Features and Labels #Step 5 - Cross Validation (train_test_split) #Step 6 - Create the Linear Model (LinearRegression) #Step 7 - Interpreting the Coefficient and the Intercept #Step 8 - Predict the output #Step 9 - Predict the Score (% Accuracy) #Step 10- Verification of the Predicted Value #Step 11- Calculate the MSE and RMSE ''' ''' y = m*x + c y = b0*x0 + b1*x1 + b2*x2 + b3*x3 + ... + bn*xn y = b0 + b1*x1 + b2*x2 + b3*x3 + ... + bn*xn Price per week Population of city Monthly income of riders Average parking rates per month Number of weekly riders ''' #Step 1 - Import the necessary libraries and the dataset import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('taxi.csv') #Step 2 - Plot the Seaborn Pairplot sns.pairplot(df) #Step 3 - Plot the Seaborn Heatmap sns.heatmap(df.corr(),linewidth = 0.2, vmax=1.0, square=True, linecolor='red',annot=True) #Step 4 - Extract the Features and Labels features = df.iloc[:,0:-1].values labels = df.iloc[:,-1].values #Step 5 - Cross Validation (train_test_split) from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(features,labels,test_size=0.3,random_state=0) #Step 6 - Create the Linear Model (LinearRegression) from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train,y_train) #Step 7 - Interpreting the Coefficient and the Intercept y_pred = regressor.predict(X_test) #Step 8 - Interpreting the Coefficient and the Intercept print(regressor.coef_) print(regressor.intercept_) #Step 9 - Predict the Score (% Accuracy) print('Train Score :', regressor.score(X_train,y_train)) print('Test Score:', regressor.score(X_test,y_test)) #Step 10- Verification of the Predicted Value #y = b0 + b1*x1 + b2*x2 + b3*x3 + ... + bn*xn y_output0 = regressor.intercept_ + regressor.coef_[0]*X_test[0][0] + regressor.coef_[1]*X_test[0][1] + regressor.coef_[2]*X_test[0][2] + regressor.coef_[3]*X_test[0][3] y_output1 = regressor.intercept_ + regressor.coef_[0]*X_test[1][0] + regressor.coef_[1]*X_test[1][1] + regressor.coef_[2]*X_test[1][2] + regressor.coef_[3]*X_test[1][3] #Step 11- Calculate the MSE and RMSE from sklearn import metrics print('MSE :', metrics.mean_squared_error(y_test,y_pred)) print('RMSE :', np.sqrt(metrics.mean_squared_error(y_test,y_pred))) ############################################################################### X1 = [[80, 1770000, 6000, 85]] out1 = regressor.predict(X1)
# -*- coding:utf-8 -*- # author: pekwjw # date: 2019-01-28 class Car(object): def __init__(self,car_name = "suv"): self.name = car_name def create(self): print "create one {0}.".format(str(self.name)) class tank(Car): def __init__(self,car_name): Car.__init__(self,car_name) def create(self): print "Create one {0}".format(str(self.name)) def wheel(self): print "{0}'s wheel is made of caterpillar.".format(str(self.name)) class suv(Car): def __init__(self,car_name): #Car.__init__(self,car_name) super(suv,self).__init__(car_name) def create(self): print "Create one {0}".format(str(self.name)) def usage(self): print "{0} is used for cross_country.".format(str(self.name)) class bus(Car): def __init__(self,car_name): Car.__init__(self,car_name) def usage(self): print "{0} is used for transportation in big cities.".format(str(self.name)) def car_factory(car_name): if "tank" == car_name: car_instance = tank(car_name) return car_instance elif "suv" == car_name: car_instance = suv(car_name) return car_instance elif "bus" == car_name: car_instance = bus(car_name) return car_instance else: return None def test_client(): t = car_factory("tank") s = car_factory("suv") b = car_factory("bus") t.create() t.wheel() s.create() s.usage() b.create() b.usage() del t,s,b def main(): test_client() if __name__ == "__main__": main()
#Author: Jasffer T. Padigdig #Date: October 14, 2020 #Assignment: Phonebook code #Description: The code is executes the CRUD using hashing #References: def linearprobing(A, location): counter = 0 #if the counter is greater than the length of the list then it means the phone book is already full while counter < len(A): val = (location + 1)%len(A) if A[val] == None: return val #increase the location by 1 until we reach an empty location location += 1 counter += 1 #return false since it's already full return False def create(A): account = [] #getting the user info userid = int(input('input user ID: ')) account.append(userid) name = input('input user name: ') account.append(name) tel = int(input('input telephone number: ')) account.append(tel) #hashing the location of the information location = tel%len(A) #if hashed location isn't empty insert the user information if A[location] == None: A[location] = account print('data has been added.') #if location isn't empty, check if the telephone number matches with the input else: if A[location][2] == tel: print('That telephone number already exists!') return else: checker = linearprobing(A, location) if checker: A[checker] = account print('data has been added') else: print('The phonebook is already full!') return A def read(A): print('') print('1 - you want to read the whole phonebook 2 - read a specific part of the phonebook') choice = input('>>>> ') if choice == '1': print('') print('ID Name Telephone') for i in range(len(A)): if A[i] != None: print(f'{A[i][0]} {A[i][1]} {A[i][2]}') elif choice == '2': print('') i = int(input('what is the telephone number you want to search for? ')) location = i%(len(A)) if A[location] != None and A[location][2] == i: print(f'ID: {A[location][0]} Username: {A[location][1]} Telephone: {A[location][2]}') else: counter = 0 while counter < len(A): checker = (location + 1)%len(A) if A[checker] != None and A[checker][2] == i: print(f'ID: {A[checker][0]} Username: {A[checker][1]} Telephone: {A[checker][2]}') return location += 1 counter += 1 print('the value does not exist!') else: print('invalid syntax') return def update(A): print('') i = int(input('what is the telephone number you want to update? ')) location = i%(len(A)) if A[location] != None and A[location][2] == i: update = [] #getting the user info userid = int(input('input user ID: ')) update.append(userid) name = input('input user name: ') update.append(name) tel = int(input('input telephone number: ')) update.append(tel) A[location] = update print('') print('user has been updated, new values:') print(f'ID: {A[location][0]} Username: {A[location][1]} Telephone: {A[location][2]}') else: counter = 0 while counter < len(A): checker = (location + 1)%len(A) if A[checker] != None and A[checker][2] == i: update = [] #getting the user info userid = int(input('input user ID: ')) update.append(userid) name = input('input user name: ') update.append(name) tel = int(input('input telephone number: ')) update.append(tel) A[checker] = update print('') print('user has been updated, new values:') print(f'ID: {A[checker][0]} Username: {A[checker][1]} Telephone: {A[checker][2]}') return location += 1 counter += 1 print('data does not exist!') def delete(A): print('') i = int(input('what is the telephone number you want to delete? ')) location = i%(len(A)) if A[location] != None and A[location][2] == i: A[location] = None else: counter = 0 while counter < len(A): checker = (location + 1)%len(A) if A[checker] != None and A[checker][2] == i: A[checker] = None print('The data has been deleted.') return location += 1 counter += 1 print('data does not exist!') A = [None] * 10 end = True while end: print('what do you want to do?') print('1 - Create new Account 2 - Read an account') print('3 - Update existing account 4 - delete existing account') print('') choice = input('>>>> ') if choice == '1': create(A) elif choice == '2': read(A) elif choice == '3': update(A) elif choice == '4': delete(A) else: end = False print('') print('the program has ended') print('') print('final phonebook:') print('ID Name Telephone') for i in range(len(A)): if A[i] != None: print(f'{A[i][0]} {A[i][1]} {A[i][2]}')
import random print("UP / DOWN 게임을 시작합니다.") rm = random.randrange(1,100) answer = 0 while (answer != rm) : answer = int(input("1~100중에서 숫자를 입력해주세요 : ")) if(answer > rm) : print("Down") elif(answer < rm) : print("Up") else : print("정답") break
height = float(input("키를 입력하세요 : ")) standardweight = (height - 100) * 0.9 print("당신의 표준체중은 {:.1f}".format(standardweight))
x=3 #Penulisan For Looping dalam Phyton for i in [0,1,2]: print(i) print() listAngka = [0,1,2,3] for i in listAngka: print(i) print() for huruf in "Komsi": print(huruf) print() kalimat = "For Phyton" for huruf in kalimat: print(huruf) print() for i in range( 1, 9, 2): print(i)
import ConfigSpace import numpy as np import typing def is_integer_hyperparameter(hyperparameter: ConfigSpace.hyperparameters.Hyperparameter) -> bool: """ Checks whether hyperparameter is one of the following: Integer hyperparameter, Constant Hyperparameter with integer value, Unparameterized Hyperparameter with integer value or CategoricalHyperparameter with only integer options. Parameters ---------- hyperparameter: ConfigSpace.hyperparameters.Hyperparameter The hyperparameter to check Returns ------- bool True iff the hyperparameter complies with the definition above, false otherwise """ if isinstance(hyperparameter, ConfigSpace.hyperparameters.IntegerHyperparameter): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.Constant) \ and isinstance(hyperparameter.value, int): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.UnParametrizedHyperparameter) \ and isinstance(hyperparameter.value, int): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.CategoricalHyperparameter) \ and np.all([isinstance(choice, int) for choice in hyperparameter.choices]): return True return False def is_boolean_hyperparameter(hyperparameter: ConfigSpace.hyperparameters.Hyperparameter) -> bool: """ Checks whether hyperparameter is one of the following: Categorical hyperparameter with only boolean values, Constant Hyperparameter with boolean value or Unparameterized Hyperparameter with boolean value Parameters ---------- hyperparameter: ConfigSpace.hyperparameters.Hyperparameter The hyperparameter to check Returns ------- bool True iff the hyperparameter complies with the definition above, false otherwise """ if isinstance(hyperparameter, ConfigSpace.hyperparameters.CategoricalHyperparameter) \ and np.all([isinstance(choice, bool) for choice in hyperparameter.choices]): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.Constant) \ and isinstance(hyperparameter.value, bool): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.UnParametrizedHyperparameter) \ and isinstance(hyperparameter.value, bool): return True return False def is_float_hyperparameter(hyperparameter: ConfigSpace.hyperparameters.Hyperparameter) -> bool: """ Checks whether hyperparameter is one of the following: Float hyperparameter, Constant Hyperparameter with float value, Unparameterized Hyperparameter with float value or CategoricalHyperparameter with only integer options. Parameters ---------- hyperparameter: ConfigSpace.hyperparameters.Hyperparameter The hyperparameter to check Returns ------- bool True iff the hyperparameter complies with the definition above, false otherwise """ if isinstance(hyperparameter, ConfigSpace.hyperparameters.FloatHyperparameter): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.Constant) \ and isinstance(hyperparameter.value, float): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.UnParametrizedHyperparameter) \ and isinstance(hyperparameter.value, float): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.CategoricalHyperparameter) \ and np.all([isinstance(choice, float) for choice in hyperparameter.choices]): return True return False def is_string_hyperparameter(hyperparameter: ConfigSpace.hyperparameters.Hyperparameter) -> bool: """ Checks whether hyperparameter is one of the following: Categorical hyperparameter with only string values, Constant Hyperparameter with string value or Unparameterized Hyperparameter with string value Parameters ---------- hyperparameter: ConfigSpace.hyperparameters.Hyperparameter The hyperparameter to check Returns ------- bool True iff the hyperparameter complies with the definition above, false otherwise """ if isinstance(hyperparameter, ConfigSpace.hyperparameters.CategoricalHyperparameter) \ and np.all([isinstance(choice, str) for choice in hyperparameter.choices]): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.Constant) \ and isinstance(hyperparameter.value, str): return True elif isinstance(hyperparameter, ConfigSpace.hyperparameters.UnParametrizedHyperparameter) \ and isinstance(hyperparameter.value, str): return True return False def get_hyperparameter_datatype(hyperparameter: ConfigSpace.hyperparameters.Hyperparameter) -> typing.Callable: """ Identifies and returns the datatype that a hyperparameter adhires to. TODO: Mixed types are currently badly supported. Parameters ---------- hyperparameter: ConfigSpace.hyperparameters.Hyperparameter The hyperparameter to check Returns ------- Callable A Callable to cast the hyperparameter to the correct type """ if is_boolean_hyperparameter(hyperparameter): return bool elif is_integer_hyperparameter(hyperparameter): return int elif is_float_hyperparameter(hyperparameter): return float elif is_string_hyperparameter(hyperparameter): return str else: raise ValueError('Hyperparameter type not determined yet. Please extend' 'this function. Hyperparameter: %s' % hyperparameter.name)
"""Contains the functions for making sentiment analysis.""" from detect_lang import LanguageDetector from nltk.tokenize import RegexpTokenizer import numpy as np import codecs import os def wordlist_to_dict(): """Create a dictionary from a wordlist.""" path = os.getcwd() # Runs from web app folder word_list = codecs.open(path + "\\app\\FINN-wordlist.txt", "r", encoding='utf8') def parse_line(line): word, sentiment = line.split('\t') return word, int(sentiment) word_dict = dict([parse_line(line) for line in word_list]) word_list.close() return word_dict def sentiment(words, word_dict): """Calculalte the sentiment score. Calculates the sentiment score for each word from a tokenized sentence and stores them in a list. """ sent_values = [word_dict[word] for word in words if word in word_dict] if not sent_values: sent_values = -1 return sent_values def sentiment_analysis(commentlist, wordlist): """Calculate the mean sentiment of each comment. Keyword arguments: commentlist -- a list of lists of comments """ # total_sentiment = 0 tokenizer = RegexpTokenizer(r'[a-z]+') all_sentiment = [] all_unknown = [] ld = LanguageDetector() for video in commentlist: video_sentiment = [] neutral = [] for comment in video: if ((ld.get_language(comment) == 'english') and (type(comment) is str)): comment = comment.lower() comment = " ".join([word for word in comment.split() if "http" not in word]) words = tokenizer.tokenize(comment) sentiment_score = sentiment(words, wordlist) if sentiment_score == -1: neutral.append(sentiment_score) else: # video_sentiment is a list of sentiments for each video. video_sentiment.append(np.mean(sentiment_score)) # all_sentiment is a list of sentiment scores for all the videos. all_unknown.append(neutral) all_sentiment.append(video_sentiment) return all_sentiment, all_unknown
print "" print "Comparisons" print "" print "4 > 3 is " + str( 4 > 3 ) # 4 greater than 3 print "4 < 3 is " + str( 4 < 3 ) # 4 less than 3 print "4 == 3 is " + str( 4 == 3 ) # 4 equal to 3 print "4 >= 3 is " + str( 4 >= 3 ) # 4 greater than or equal to 3 print "4 <= 3 is " + str( 4 <= 3 ) # 4 less than or equal to 3 print "4 != 3 is " + str( 4 != 3 ) # 4 not equal to 3 print "" print "Boolean Operators - not, and, or" print "" print "not True is " + str( not True ) print "not False is " + str( not False ) print "" print "True and True is " + str( True and True ) print "True and False is " + str( True and False ) print "False and False is " + str( False and False ) print "" print "True or True is " + str( True or True ) print "True or False is " + str( True or False ) print "False or False is " + str( False or False ) print "" print "not ( False or (False and True) ) is " + str( not ( False or (False and True) ) )
from tkinter import * from verticalScrollFrame import* fontStyle = "Times New Roman" class StartPage(Frame): #A frame containing widgets is created in the constructor of this class #pseudoPar and passPar are variables we would use in storing # specific numbers based on the user's input and passing it to another class def __init__(self, parent, controller): #The class inherents the frame class from the tkinter module ''' We inhereted the frame class so that the StartPage frame (and other frames) can exist as an independent frame object without opening another tkinter window ''' #A frame with width of 750 and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 650, width = 700) self.controller = controller #Label for heading heading=Label(self,text="Ashesi Info",bg="white",fg="maroon",font=("Times New Roman",60)) heading.place(relx=.5, rely=0.2, anchor="center") #Label with ashesi logo self.img = PhotoImage(file = "ashesilogo.gif") logo = Label(self, image=self.img) logo.place(relx=.5, rely=.4, anchor="center") #Sign in Button button1 = Button(self,text="Sign In", bg = 'maroon', fg = "white",font=("Times New Roman",25), command = lambda: controller.show_SignInPageFrame("StartPage")) button1.place(relx=0.6, rely=0.8 ,anchor="center") #Sign up button button2 = Button(self,text="Sign Up", bg = "maroon", fg = "white",font=("Times New Roman",25), command = lambda: controller.show_SignUpPageFrame("StartPage")) button2.place(relx=0.4, rely=0.8 ,anchor="center") class SignUpPage(Frame): #A frame containing widgets is created in the constructor of this class #pseudoPar and passPar are variables we would use in storing # specific numbers based on the user's input and passing it to another class def __init__(self, parent, controller): #The class inherents the frame class from the tkinter module ''' We inhereted the frame class so that the StartPage frame (and other frames) can exist as an independent frame object without opening another tkinter window ''' #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 650, width = 700) self.controller = controller #Label for heading heading=Label(self,text="Ashesi Info",bg="white",fg="maroon",font=("Times New Roman",60)) heading.place(relx=.5, rely=0.2, anchor="center") #Label with ashesi logo self.img = PhotoImage(file = "ashesilogo.gif") logo = Label(self, image=self.img) logo.place(relx=.5, rely=.4, anchor="center") # Sign as student Button button1 = Button(self,text="Sign Up as student", bg = 'maroon',fg="white", font=("Times New Roman",25), command = lambda: controller.show_SignUpStdPageFrame("SignUpPage")) button1.place(relx=0.5, rely=0.65 ,anchor="center") # Sign Up as alumni Button button2 = Button(self,text="Sign Up as alumni", bg = 'maroon', fg="white", font=("Times New Roman",25), command = lambda: controller.show_SignUpAlumPageFrame("SignUpPage")) button2.place(relx=0.5, rely=0.8 ,anchor="center") # Back to Start Page Button button = Button(self, text = "Back to Start Page", bg = "maroon", fg = "white", font = ('Times New Roman', 13), command = lambda: controller.show_frame("StartPage")) button.place(relx=0.5, rely=0.94 ,anchor="center") class SignInPage(Frame): #A frame containing widgets is created in the constructor of this class #pseudoPar and passPar are variables we would use in storing # specific numbers based on the user's input and passing it to another class def __init__(self, parent, controller): #The class inherents the frame class from the tkinter module ''' We inhereted the frame class so that the StartPage frame (and other frames) can exist as an independent frame object without opening another tkinter window ''' #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 650, width = 700) self.controller = controller #Label for heading heading=Label(self,text="Ashesi Info",bg="white",fg="maroon",font=("Times New Roman",60)) heading.place(relx=.5, rely=0.2, anchor="center") #Label with ashesi logo self.img = PhotoImage(file = "ashesilogo.gif") logo = Label(self, image=self.img) logo.place(relx=.5, rely=.4, anchor="center") # Sign In as student Button button1 = Button(self,text="Sign In as student", bg = 'maroon', fg="white", font=("Times New Roman",25), command = lambda: controller.show_SignInStdPageFrame("SignInPage")) button1.place(relx=0.5, rely=0.65 ,anchor="center") # Sign In as alumni Button button2 = Button(self,text="Sign In as alumini", bg = 'maroon', fg="white", font=("Times New Roman",25), command = lambda: controller.show_SignInAlumPageFrame("SignInPage")) button2.place(relx=0.5, rely=0.8 ,anchor="center") # Back to Start Page Button button = Button(self, text = "Back to Start Page", bg = "maroon", fg = "white", font = ('Times New Roman', 13), command = lambda: controller.show_frame("StartPage")) button.place(relx=0.5, rely=0.94 ,anchor="center") class StdSignInPage(Frame): #A frame containing widgets is created in the constructor of this class #pseudoPar and passPar are variables we would use in storing # specific numbers based on the user's input and passing it to another class def __init__(self, parent, controller): #The class inherents the frame class from the tkinter module ''' We inhereted the frame class so that the StartPage frame (and other frames) can exist as an independent frame object without opening another tkinter window ''' #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 600, width = 600) self.controller = controller #Label with ashesi logo self.img = PhotoImage(file = "ashesilogo.gif") logo = Label(self, image=self.img) logo.place(relx=.5, rely=.13, anchor="center") #Label for heading labelUsrname = Label(self, text = "Sign In ", bg = "white", fg = "maroon", font = (fontStyle,45)) labelUsrname.place(relx = 0.5 , rely = 0.35, anchor = "center") #Label and text entry for student username labelUsrname = Label(self, text = "Student Name: ", bg = "white", fg = "maroon", font = (fontStyle,12)) labelUsrname.place(relx = 0.2 , rely = 0.51, anchor = "center") Usrentry = Entry(self, bg = "white", selectforeground = "black", selectbackground = "maroon", width = 50) Usrentry.place(relx = 0.3,rely = 0.5) #Label and text entry for student username labelUsrpasswrd = Label(self, text = "Password: ", bg = "white", fg = "maroon", font = (fontStyle,12)) labelUsrpasswrd.place(relx = 0.2 , rely = 0.59, anchor = "center") Passentry = Entry(self, bg = "white", selectforeground = "black", selectbackground = "maroon", width = 25) Passentry.place(relx = 0.3,rely = 0.58) #button for student signin buttonSignIn = Button(self, text = "Submit", bg = "maroon", fg = "white", font = (fontStyle,12), command = lambda: controller.show_HomeFromSignInFrame("StdSignInPage",Usrentry,Passentry)) buttonSignIn.place(relx = 0.5,rely = 0.68, anchor = "center") # Back to Sign In Page Button button = Button(self, text = "Back to Sign In page",bg = "maroon", fg = "white", font = ('Times New Roman', 13), command = lambda: controller.show_SignInPageFrame("StartPage")) button.place(relx=0.5, rely=0.94 ,anchor="center") class AlumSignInPage(Frame): #A frame containing widgets is created in the constructor of this class #pseudoPar and passPar are variables we would use in storing # specific numbers based on the user's input and passing it to another class def __init__(self, parent, controller): #The class inherents the frame class from the tkinter module ''' We inhereted the frame class so that the StartPage frame (and other frames) can exist as an independent frame object without opening another tkinter window ''' #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 600, width = 600) self.controller = controller #Label with ashesi logo self.img = PhotoImage(file = "ashesilogo.gif") logo = Label(self, image=self.img) logo.place(relx=.5, rely=.13, anchor="center") #Label for heading labelUsr = Label(self, text = "Sign In ", bg = "white", fg = "maroon", font = (fontStyle,45)) labelUsr.place(relx = 0.5 , rely = 0.35, anchor = "center") #Label and text entry for student username labelUsrname = Label(self, text = "Alumni Name: ", bg = "white", fg = "maroon", font = (fontStyle,12)) labelUsrname.place(relx = 0.2 , rely = 0.51, anchor = "center") Usrentry = Entry(self, bg = "white", selectforeground = "black", selectbackground = "maroon", width = 50) Usrentry.place(relx = 0.3,rely = 0.5) #Label and text entry for student username labelUsrpasswrd = Label(self, text = "Password: ", bg = "white", fg = "maroon", font = (fontStyle,12)) labelUsrpasswrd.place(relx = 0.2 , rely = 0.59, anchor = "center") Passentry = Entry(self, bg = "white", selectforeground = "black", selectbackground = "maroon", width = 25) Passentry.place(relx = 0.3,rely = 0.58) #button for student signin buttonSignIn = Button(self, text = "Submit", bg = "maroon", fg = "white", font = (fontStyle,12), command = lambda: controller.show_HomeFromSignInFrame("AlumSignInPage",Usrentry,Passentry)) buttonSignIn.place(relx = 0.5,rely = 0.68, anchor = "center") # Back to Sign In Page Button button = Button(self, text = "Back to Sign In page",bg = "maroon", fg = "white", font = ('Times New Roman', 13), command = lambda: controller.show_SignInPageFrame("StartPage")) button.place(relx=0.5, rely=0.94 ,anchor="center") class NoResultsPage(Frame): #A frame containing widgets is created in the constructor of this class #pseudoPar and passPar are variables we would use in storing # specific numbers based on the user's input and passing it to another class def __init__(self, parent, controller, pseudoPar): #The class inherents the frame class from the tkinter module ''' We inhereted the frame class so that the StartPage frame (and other frames) can exist as an independent frame object without opening another tkinter window ''' #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 600, width = 600) self.controller = controller self.oldHomePage = 0 #Label for heading labelNoRlts = Label(self, text = "No Results", bg = "white", fg = "maroon", font = (fontStyle,45)) labelNoRlts.place(relx = 0.5 , rely = 0.13, anchor = "center") #Labels containing error message and hint for user labelTips = Label(self, text = "Hints: ", bg = "white", fg = "maroon", font = (fontStyle,25)) labelTips.place(relx = 0.3 , rely = 0.3, anchor = "center") labelTips = Label(self, text = "Check your spelling", bg = "white", fg = "maroon", font = (fontStyle,11)) labelTips.place(relx = 0.5 , rely = 0.35, anchor = "center") labelTips = Label(self, text = "User is probably not a Student or Alumni of Ashesi", bg = "white", fg = "maroon", font = (fontStyle,11)) labelTips.place(relx = 0.5 , rely = 0.4, anchor = "center") #button for going back to homepage button = Button(self, text = "Back to Home Page", font = ('Helvetica', 13), command = lambda: controller.show_ShowHomeFromSearchResults("SearchResultPage", self.oldHomePage)) button.place(relx=0.5, rely=0.94 ,anchor="center") class StudentSignUp(Frame): def __init__(self, parent, controller): #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 650, width = 700) self.controller = controller #Label with heading "Student Sign Up" heading = Label(self, text = "Student Sign Up", bg = "white", fg = "maroon", font = ('Times New Roman', 20)) heading.place(relx = .5, rely = .05, anchor = "center") #Label and entry widget for student's full name nameLabel = Label(self, text = "Full Name:", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) nameLabel.place(relx = .2, rely = .13, anchor = "center") nameEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") nameEntry.place(relx = .46, rely = .13, anchor = "center") #Label and entry widget for student's password passwordLabel = Label(self, text = "Password:", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) passwordLabel.place(relx = .2, rely = .22, anchor = "center") passwordEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") passwordEntry.place(relx = .46, rely = .22, anchor = "center") #Label and entry widget for student's year group classLabel = Label(self, text = "Year Group: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) classLabel.place(relx = .2, rely = .31, anchor = "center") classEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") classEntry.place(relx = .46, rely = .31, anchor = "center") #Label and entry widget for student's Id idLabel = Label(self, text = "Student ID: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) idLabel.place(relx = .2, rely = .4, anchor = "center") idEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") idEntry.place(relx = .46, rely = .4, anchor = "center") #Label and entry widget for student's interests interestsLabel = Label(self, text = "Interests: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) interestsLabel.place(relx = .2, rely = .49, anchor = "center") interestsEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon", width = 15) interestsEntry.place(relx = .46, rely = .49, anchor = "center") #Label and entry widget for student's major majorLabel = Label(self, text = "Major: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) majorLabel.place(relx = .2, rely = .58, anchor = "center") majorEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") majorEntry.place(relx = .46, rely = .58, anchor = "center") #Label and entry widget for student's phone number phoneLabel = Label(self, text = "Phone: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) phoneLabel.place(relx = .2, rely = .67, anchor = "center") phoneEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") phoneEntry.place(relx = .46, rely = .67, anchor = "center") #Label and entry widget for student's email address emailLabel = Label(self, text = "email: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) emailLabel.place(relx = .2, rely = .76, anchor = "center") emailEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") emailEntry.place(relx = .46, rely = .76, anchor = "center") #Button to show the next frame button = Button(self, text = "Sign Up", command = lambda: controller.show_HomeFromStdSignUpFrame("StudentSignUp",nameEntry, passwordEntry,classEntry,idEntry, interestsEntry,majorEntry,phoneEntry,emailEntry)) button.place(relx=0.5, rely=0.94 ,anchor="center") #Button to go back to old frame button = Button(self, text = "Back to SignUp page",bg = "maroon", fg = "white", command = lambda: controller.show_SignUpPageFrame("StartPage")) button.place(relx=0.35, rely=0.94 ,anchor="center") class AlumniSignUp(Frame): def __init__(self, parent, controller): #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 650, width = 700) self.controller = controller #Label with heading "Alumni Sign Up" heading = Label(self, text = "Alumni Sign Up", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) heading.place(relx = .5, rely = .05, anchor = "center") #Label and entry widget for alumni's full name nameLabel = Label(self, text = "Full Name:", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) nameLabel.place(relx = .2, rely = .15, anchor = "center") nameEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") nameEntry.place(relx = .46, rely = .15, anchor = "center") #Label and entry widget for alumni's password passwordLabel = Label(self, text = "Password: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) passwordLabel.place(relx = .2, rely = .24, anchor = "center") passwordEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") passwordEntry.place(relx = .46, rely = .24, anchor = "center") #Label and entry widget for alumni's year group classLabel = Label(self, text = "Year Group: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) classLabel.place(relx = .2, rely = .33, anchor = "center") classEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") classEntry.place(relx = .46, rely = .33, anchor = "center") #Label and entry widget for alumni's interests interestsLabel = Label(self, text = "Interests: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) interestsLabel.place(relx = .2, rely = .42, anchor = "center") interestsEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") interestsEntry.place(relx = .46, rely = .42, anchor = "center") #Label and entry widget for alumni's career careerLabel = Label(self, text = "Career: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) careerLabel.place(relx = .2, rely = .51, anchor = "center") careerEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") careerEntry.place(relx = .46, rely = .51, anchor = "center") #Label and entry widget for alumni's phone number phoneLabel = Label(self, text = "Phone: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) phoneLabel.place(relx = .2, rely = .6, anchor = "center") phoneEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") phoneEntry.place(relx = .46, rely = .6, anchor = "center") #Label and entry widget for alumni's email address emailLabel = Label(self, text = "email: ", bg = "white", fg = "maroon", font = ('Times New Roman', 15)) emailLabel.place(relx = .2, rely = .69, anchor = "center") emailEntry = Entry(self, bg = 'white', fg = "black", selectbackground = "white", selectforeground = "maroon") emailEntry.place(relx = .46, rely = .69, anchor = "center") #Button to show the next frame button = Button(self, text = "Sign Up", command = lambda: controller.show_HomeFromAlmSignUpFrame("AlumniSignUp",nameEntry, passwordEntry,classEntry,interestsEntry,careerEntry,phoneEntry,emailEntry)) button.place(relx=0.5, rely=0.94 ,anchor="center") #Button to go back to old frame button = Button(self, text = "Back to SignUp page",bg = "maroon", fg = "white", command = lambda: controller.show_SignUpPageFrame("StartPage")) button.place(relx=0.35, rely=0.94 ,anchor="center") class SearchResultPage(Frame): def __init__(self, parent, controller, pseudoPar): #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 650, width = 700) self.controller = controller self.oldHomePage = 0 #Label of the name of person that was searched for label = Label(self, text = pseudoPar["fullName"], bg = "white", fg = "maroon", font = (fontStyle,40)) label.place(relx = 0.5,rely = 0.13, anchor = "center") #Label of the year group of person that was searched for label2 = Label(self, text = "Member of " + pseudoPar["yearGroup"] + " Year Group", bg = "white", fg = "maroon", font = (fontStyle,20)) label2.place(relx = 0.5,rely = 0.3, anchor = "center") #Label of the career/major of person that was searched for labelStory = Label(self, text = "Career/Major: " + pseudoPar["career"], bg = "white", fg = "maroon", font = (fontStyle,18)) labelStory.place(relx = 0.4,rely = 0.45, anchor = "center") #Label of the interests of person that was searched for labelInterest = Label(self, text = "Interest: "+pseudoPar["interests"], bg = "white", fg = "maroon", font = (fontStyle,18)) labelInterest.place(relx = 0.4,rely = 0.6, anchor = "center") #Label of the number of person that was searched for labelNum = Label(self, text = pseudoPar["phone"], bg = "white", fg = "maroon", font = (fontStyle,18)) labelNum.place(relx = 0.5,rely = 0.8, anchor = "center") #Label of the email of person that was searched for labelMail = Label(self, text = pseudoPar["email"], bg = "white", fg = "maroon", font = (fontStyle,18)) labelMail.place(relx = 0.5, rely = 0.85 , anchor = "center") #Button to go back to old frame button = Button(self, text = "Back to Home Page", font = ('Helvetica', 13), command = lambda: controller.show_ShowHomeFromSearchResults("SearchResultPage", self.oldHomePage)) button.place(relx=0.5, rely=0.94 ,anchor="center") class HomePage(Frame): def __init__(self, parent, controller, pseudoPar): #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 650, width = 700) self.controller = controller # Entry acting as search bar entry = Entry(self, bg = "grey", selectforeground = "maroon", selectbackground = "white", width = 50) entry.place(relx = 0.5, rely = 0.1, anchor = "center") #Search button buttonSearch = Button(self, text = "Search", bg = "maroon", fg = "white", font = (fontStyle, 12), command = lambda: controller.show_SearchResultsFrame("HomePage", entry, pseudoPar)) buttonSearch.place(relx = 0.8, rely = 0.1, anchor = "center") #Label of the name of user label = Label(self, text = pseudoPar["fullName"], bg = "white", fg = "maroon", font = (fontStyle,30)) label.place(relx = 0.5,rely = 0.2, anchor = "center") #Label of the year group of user label2 = Label(self, text = "Member of " + pseudoPar["yearGroup"] + " Year Group", bg = "white", fg = "maroon", font = (fontStyle,20)) label2.place(relx = 0.5,rely = 0.34, anchor = "center") #Label of the career/major of user labelcareer = Label(self, text = "Career/Major: " + pseudoPar["career"], bg = "white", fg = "maroon", width = 50, font = (fontStyle,18)) labelcareer.place(relx = 0.4,rely = 0.45, anchor = "center") #Label of the interest of user labelInterest = Label(self, text = "Interest: "+ pseudoPar["interests"], bg = "white", fg = "maroon", font = (fontStyle,18)) labelInterest.place(relx = 0.4,rely = 0.6, anchor = "center") #Label of the phone of user labelphone = Label(self, text = pseudoPar["phone"], bg = "white", fg = "maroon", font = (fontStyle,18)) labelphone.place(relx = 0.5,rely = 0.8, anchor = "center") #Label of the email of user labelMail = Label(self, text = pseudoPar["email"], bg = "white", fg = "maroon", font = (fontStyle,18)) labelMail.place(relx = 0.5, rely = 0.85 , anchor = "center") #Log out button button = Button(self, text = "Log out", font = ('Helvetica', 13), command = lambda: controller.show_frame("StartPage")) button.place(relx=0.5, rely=0.94 ,anchor="center") class YearBookPage(Frame): def __init__(self, parent, controller,pseudoPar, passPar): #A frame with width and height of 600 pixels and a white background is created Frame.__init__(self, parent, bg = 'white', height = 650, width = 700) self.controller = controller #Instance variable to hold previous homepage frame self.oldHomePage = 0 #Object of VerticalScrolledFrame class which is placed in the yearbook frame self.frame = VerticalScrolledFrame(parent, controller) self.frame.place(relx = 0.5,rely = 0.7, anchor = "center") #Button to go back to home page button = Button(self, text = "Back to Home Page", font = ('Helvetica', 13), command = lambda: controller.show_ShowHomeFromSearchResults("SearchResultPage", self.oldHomePage)) button.place(relx=0.5, rely=0.13 ,anchor="center") #Label for heading label = Label(self, text = "Class List for year group", bg = "white", fg = "maroon", font = ('Times New Roman',20)) label.place(relx = 0.5,rely = 0.2, anchor = "center") #Place names of students of the year group in scroll frame. labels = [] if pseudoPar != 0: for i in range(len(pseudoPar)): labels.append(Label(self.frame.interior, text = pseudoPar[i], bg = "white", fg = "maroon", font = ('Times New Roman',15))) labels[-1].pack() class Graph: #Initialize graph def __init__(self): self.data = {} #Add vertices to graph def add(self, key, Vertices): self.data[key] = Vertices #Get vertices from graph def get(self, key): return self.data[key] # Special method to use python's get functionality def __getitem__(self,key): return self.get(key) # Special method to use python's get functionality def __setitem__(self,key,data): self.add(key,data)
x = 500 y = 600 answer = f"x={x} is greater than y={y}" if x > y else f"y={y} is greater than x={x}" print(answer)
#List comprehension examples # first one shows the matrix transposed example l=[[1,2,3],[11,22,33],[111,222,333]] l_transpose=[[a[i] for a in l ] for i in range(3)] print(l_transpose) #list comprehension example2 #this will show the list comprehension of multiple lists a=[1,2,3] b=["apple","banana","orange"] c=["India","america","Europe"] l=[[x,y,z] for x in a for y in b for z in c] print(l)
# While loop with else block executed n=0 while n<10: print("n is lesser than 10 and the current number is :", n) n+=1 else: print("n is greater than or equal to 10 ", n) #while loop without else block execute and break statement execute n= [1,2,3] i=0 while i <= len(n): print(n[i]) i+=1 if i == len(n): break else: print("I is equal to length of n")
import time import matplotlib.pyplot as plt def Line(a,b): x = [b, b] y = [0, a] plt.plot(x, y, marker = 'o') def Graph(t_n, pos_t_n, xlabel, ylabel, heading): plt.axhline(0, color = 'black') plt.axis([pos_t_n[0]-1, pos_t_n[len(pos_t_n)-1]+1, min(t_n)-1, max(t_n)+1]) plt.title(heading) plt.xlabel(xlabel) plt.ylabel(ylabel) for i in range(len(t_n)): Line(t_n[i], pos_t_n[i]) plt.show() def main(): print("Enter input signal x[n]") x = [int(i) for i in input().split()] print("Enter position of input signal") pos_x = [int(i) for i in input().split()] print("Enter signal h[n]") h = [int(i) for i in input().split()] print("Enter position of signal h[n]") pos_h = [int(i) for i in input().split()] pos_y=[] y=[] for i in range(len(x)): for j in range(len(h)): if pos_x[i]+pos_h[j] not in pos_y: pos_y.append(pos_x[i]+pos_h[j]) y.append(x[i]*h[j]) else: idx = pos_y.index(pos_x[i]+pos_h[j]) y[idx]+=(x[i]*h[j]) print("Output signal:") print("y[n]:",end='') print(y) print("n:",end='') print(pos_y) Graph(x,pos_x,"n","x[n]","Input signal for convolution" ) Graph(h,pos_h,"n","h[n]","Impulse response for convolution" ) Graph(y,pos_y,"n","y[n]","Output signal for convolution" ) if __name__ == '__main__': main()
# coding: utf-8 import time def tower(base, h, m): """Return base ** base ** ... ** base, where the height is h, modulo m. """ if m == 1: return 0 if base == 1: return 1 if h == 0: return 1 if h == 1: return base % m G, t = totient(m) if base in G: f = base for j in range(h-2): f = (base ** f) % t return (base ** f) % m return 100 pass def totient(m): G = set() G.add(1) d = set() for j in range(2, m): if j in d: continue if m % j == 0: d.add(j) jj = j while jj < m: jj += j d.add(jj) continue G.add(j) return G, len(G) t0 = time.time() G, t = totient(65519) print(t) print(time.time()-t0) print(tower(2, 5, 65519)) print(tower(3, 9, 4)) print(tower(7, 7, 9)) print(tower(7, 4, 8))
# code: utf-8 ''' The eccentric candy-maker, Billy Bonka, is building a new candy factory to produce his new 4-flavor sugar pops. The candy is made by placing a piece of candy base onto a conveyer belt which transports the candy through four separate processing stations in sequential order. Each station adds another layer of flavor. Due to an error in the factory blueprints, the four stations have been constructed in incorrect locations. It's too costly to disassemble the stations, so you've been called in. Arrange the directional path of the conveyer belt so that it passes through each of the stations in sequential order while also traveling the shortest distance possible. Input An array consisting of the locations of each station on the factory floor, in order. The factory floor is a `10` x `10` matrix (with `0` starting index). Output Your function should return the path of the conveyer belt as an array. If a valid configuration is not possible, return `null` or `None`. The position values in the input and output arrays will consist of integers in the range `0 - 99`, inclusive. These integers represent a position on the factory floor. For example, the position `[0,8]` is given as `8`, and `[4,6]` is given as `46` Technical Details The conveyer belt must run through each station once and in ascending order The conveyer belt must not intersect/overlap itself The distance covered by the conveyer belt must be the minimum necessary to complete the task Full Test Suite: `30` fixed tests, `100` random tests Inputs will always be valid and each test will have zero or more possible solutions.. ''' def four_pass(stations): print(stations) sdict = parse(stations) print(sdict) pass def parse(stations): sdict = dict() for j, s in enumerate(stations): sdict[(s//10, s % 10)] = j+1 return sdict def short_path(s1, s2): dist_dict = dict() dist_dict[s1] = 1 def mk_dist_dict(n=10): dist_dict = dict() for j in range(10): for k in range(10): dist_dict[(j, k)] = 0 return dist_dict example_tests = [ [1, 69, 95, 70], [0, 49, 40, 99], [37, 61, 92, 36], [51, 24, 75, 57], [92, 59, 88, 11]] four_pass(example_tests[0])
# code: utf-8 from copy import deepcopy import time def sudoku(puzzle): puzzle_dict = parse(puzzle) # for e in puzzle_dict.items(): # print(e[0], ':', e[1]) results = guess(puzzle_dict) solution = puzzle.copy() for it in results.items(): solution[it[0][0]][it[0][1]] = it[1].pop() return solution def guess(puzzle_dict): # pnt(puzzle_dict) for it in puzzle_dict.items(): if len(it[1]) == 0: return False if check(puzzle_dict): # print(puzzle_dict) return puzzle_dict sort_uncertain = sorted(puzzle_dict.items(), key=lambda d: len(d[1])) if len(sort_uncertain[-1][1]) == 1: return False for min_uncertain in sort_uncertain: if len(min_uncertain[1]) > 1: break j, k = min_uncertain[0] jj, kk = j//3*3, k//3*3 for c in min_uncertain[1]: force_continue = False new_puzzle_dict = puzzle_dict.copy() for x in range(9): if c in new_puzzle_dict[(x, k)]: new_puzzle_dict[(x, k)] = puzzle_dict[(x, k)].copy() - {c} if len(new_puzzle_dict[(x, k)]) == 0: force_continue = True break if force_continue: continue for y in range(9): if c in new_puzzle_dict[(j, y)]: new_puzzle_dict[(j, y)] = puzzle_dict[(j, y)].copy() - {c} if len(new_puzzle_dict[(j, y)]) == 0: force_continue = True break if force_continue: continue for x in range(3): for y in range(3): if c in new_puzzle_dict[(jj+x, kk+y)]: new_puzzle_dict[(jj+x, kk+y) ] = puzzle_dict[(jj+x, kk+y)].copy() - {c} if len(new_puzzle_dict[(jj+x, kk+y)]) == 0: force_continue = True break if force_continue: continue new_puzzle_dict[(j, k)] = {c} # print(j, k, jj, kk, c, new_puzzle_dict) x = guess(new_puzzle_dict) if not x: continue return x def pnt(puzzle_dict): puzzle = [['-' for _ in range(9)] for __ in range(9)] for it in puzzle_dict.items(): if len(it[1]) == 0: puzzle[it[0][0]][it[0][1]] = 'x' continue if len(it[1]) == 1: puzzle[it[0][0]][it[0][1]] = '%d' % it[1].copy().pop() continue puzzle[it[0][0]][it[0][1]] = '=' print('-'*60) for e in puzzle: print(' '.join(e)) def check(puzzle_dict): puzzle_dict = puzzle_dict.copy() for it in puzzle_dict.items(): if not len(it[1]) == 1: return False puzzle_dict[it[0]] = it[1].copy().pop() for j in range(9): for k in range(9): if not len(set(puzzle_dict[(x, k)] for x in range(9))) == 9: return False if not len(set(puzzle_dict[(j, y)] for y in range(9))) == 9: return False if not len(set(puzzle_dict[(j//3*3+x, k//3*3+y)] for x in range(3) for y in range(3))) == 9: return False return True def parse(puzzle): puzzle_dict = dict() for j in range(9): for k in range(9): if puzzle[j][k] == 0: all = set(range(1, 10)) sub1 = set(puzzle[x][k] for x in range(9)) sub2 = set(puzzle[j][y] for y in range(9)) sub3 = set(puzzle[j//3*3+x][k//3*3+y] for x in range(3) for y in range(3)) possible = all - sub1 - sub2 - sub3 puzzle_dict[(j, k)] = possible else: puzzle_dict[(j, k)] = {puzzle[j][k]} return puzzle_dict def ij2kl(ij): """Transform (row, col) to (square, tail). The inverse transformation is the same (just like magic!!!). """ i, j = ij k = i // 3 * 3 + j // 3 l = i % 3 * 3 + j % 3 return k, l class SudokuBoard(object): def __init__(self): self.board = [] for i in range(9): self.board.append([0]*9) self.row_col = {} # Set of possible numbers in the tile (row,col) self.unsure = set() # Unsure tiles (those with more than one possible numbers) for i in range(9): for j in range(9): self.row_col[(i, j)] = set(range(1, 10)) self.unsure.add((i, j)) self.row_num = {} # Set of possible column indices for (row, num) for i in range(9): for num in range(1, 10): self.row_num[(i, num)] = set(range(9)) # Set of possible row indices for (col, num) self.col_num = deepcopy(self.row_num) # Set of possible tail indices for (square, num) self.square_num = deepcopy(self.row_num) self.to_put = set() # Import queue keeping all confirmed putting moves (row, col, num) def add_to_put(self, triplet): """Add a triplet (row, col, num) to the queue `self.to_put`.""" if not triplet in self.to_put: self.to_put.add(triplet) def remove_and_infer(self, row, col, num): """Remove the possibility to put `(row,col,num)` on the board. Update info for inferring. When there is only one possibility left, add it to the queue `self.to_put`. """ square, tail = ij2kl((row, col)) numset = self.row_col[(row, col)] if num in numset: numset.remove(num) if len(numset) == 1: for n in numset: self.add_to_put((row, col, n)) rowset = self.col_num[(col, num)] if row in rowset: rowset.remove(row) if len(rowset) == 1: for r in rowset: self.add_to_put((r, col, num)) colset = self.row_num[(row, num)] if col in colset: colset.remove(col) if len(colset) == 1: for c in colset: self.add_to_put((row, c, num)) tailset = self.square_num[(square, num)] if tail in tailset: tailset.remove(tail) if len(tailset) == 1: for t in tailset: i, j = ij2kl((square, t)) self.add_to_put((i, j, num)) def put(self): """Put all numbers in the queue `self.to_put` on the board. Remove impossible cases by calling `self.remove_and_infer`. """ while self.to_put: row, col, num = self.to_put.pop() square, tail = ij2kl((row, col)) if not (num in self.row_col[(row, col)] and row in self.col_num[(col, num)] and col in self.row_num[(row, num)] and tail in self.square_num[(square, num)]): return False else: self.row_col[(row, col)] = {num} self.col_num[(col, num)] = {row} self.row_num[(row, num)] = {col} self.square_num[(square, num)] = {tail} for r in range(9): if r != row: self.remove_and_infer(r, col, num) for c in range(9): if c != col: self.remove_and_infer(row, c, num) for t in range(9): if t != tail: i, j = ij2kl((square, t)) self.remove_and_infer(i, j, num) for n in range(1, 10): if n != num: self.remove_and_infer(row, col, n) self.board[row][col] = num self.unsure.remove((row, col)) return True def solve(self): if not self.put(): return None if not self.unsure: return self.board else: unsure_list = sorted( list(self.unsure), key=lambda x: len(self.row_col[x])) # Choose the tile with fewest possibilities row, col = unsure_list[0] while len(self.row_col[(row, col)]) > 1: num = self.row_col[(row, col)].pop() self.row_col[(row, col)].add(num) new_self = deepcopy(self) new_self.add_to_put((row, col, num)) board = new_self.solve() if board: return board else: self.remove_and_infer(row, col, num) # now len(self.row_col[(row,col)]) == 1 and `self.to_put` is not empty if self.put(): return self.solve() else: return None def solve_fast(board): haha = SudokuBoard() for i in range(9): for j in range(9): num = board[i][j] if num > 0: haha.add_to_put((i, j, num)) res = haha.solve() return res def sudoku_fast(puzzle): block_27, block_list = mk_block() puzzle_list = mk_list(puzzle) results = [] def is_check(puzzle_list): # -2, means failed # -1, means good # j, means guess in j if [] in puzzle_list: return -2 lens = sorted(set(len(e) for e in puzzle_list)) if lens == [1]: for idx_9 in block_27: # if not sorted(puzzle_list[e][0] for e in idx_9) == list(range(1, 10)): if not len(set(puzzle_list[e][0] for e in idx_9)) == 9: return -2 return -1 for j, e in enumerate(puzzle_list): if len(e) == lens[1]: return j def solve_iter(puzzle_list): # pnt_list(puzzle_list) idx = is_check(puzzle_list) if idx == -2: return False if idx == -1: pnt_list(puzzle_list) results.append(puzzle_list) return True # print(idx, puzzle_list[idx]) for c in puzzle_list[idx]: new_puzzle_list = puzzle_list.copy() for neighbor_idx in block_list[idx]: if c in puzzle_list[neighbor_idx]: new_puzzle_list[neighbor_idx] = [ e for e in puzzle_list[neighbor_idx] if not e == c] if new_puzzle_list[neighbor_idx] == []: break new_puzzle_list[idx] = [c] if solve_iter(new_puzzle_list): return True return 0 solve_iter(puzzle_list) solution = puzzle.copy() for j in range(9): for k in range(9): solution[j][k] = results[0][sub2idx(j, k)][0] return solution def pnt_list(puzzle_list): board = [[0 for _ in range(9)] for __ in range(9)] for j in range(9): for k in range(9): idx = sub2idx(j, k) if len(puzzle_list[idx]) == 1: board[j][k] = '%d' % puzzle_list[idx][0] if len(puzzle_list[idx]) == 0: board[j][k] = 'x' if len(puzzle_list[idx]) > 1: board[j][k] = '=' print('-' * 60) for j, b in enumerate(board): print('%2d:' % (j*9), ' '.join(e for e in b)) def sub2idx(j, k): return j*9 + k def mk_block(): block_27 = [] for j in range(9): block_27.append(set(sub2idx(j, y) for y in range(9))) for k in range(9): block_27.append(set(sub2idx(x, k) for x in range(9))) for j in [0, 3, 6]: for k in [0, 3, 6]: block_27.append(set(sub2idx(j+x, k+y) for x in range(3) for y in range(3))) block_list = [] for j in range(9): for k in range(9): tmp = set() tmp = tmp.union(set(sub2idx(x, k) for x in range(9))) tmp = tmp.union(set(sub2idx(j, y) for y in range(9))) tmp = tmp.union(set(sub2idx(j//3*3+x, k//3*3+y) for x in range(3) for y in range(3))) block_list.append(tmp) return block_27, block_list def mk_list(puzzle): puzzle_list = [] for j in range(9): for k in range(9): if puzzle[j][k] == 0: all = set(range(1, 10)) sub1 = set(puzzle[x][k] for x in range(9)) sub2 = set(puzzle[j][y] for y in range(9)) sub3 = set(puzzle[j//3*3+x][k//3*3+y] for x in range(3) for y in range(3)) possible = all - sub1 - sub2 - sub3 puzzle_list.append([e for e in possible]) else: puzzle_list.append([puzzle[j][k]]) return puzzle_list puzzle1 = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] puzzle2 = [[9, 0, 6, 0, 7, 0, 4, 0, 3], [0, 0, 0, 4, 0, 0, 2, 0, 0], [0, 7, 0, 0, 2, 3, 0, 1, 0], [5, 0, 0, 0, 0, 0, 1, 0, 0], [0, 4, 0, 2, 0, 8, 0, 6, 0], [0, 0, 3, 0, 0, 0, 0, 0, 5], [0, 3, 0, 7, 0, 0, 0, 5, 0], [0, 0, 7, 0, 0, 5, 0, 0, 0], [4, 0, 5, 0, 1, 0, 7, 0, 8]] puzzle3 = [[0, 8, 0, 0, 0, 9, 7, 4, 3], [0, 5, 0, 0, 0, 8, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [8, 0, 0, 0, 0, 5, 0, 0, 0], [0, 0, 0, 8, 0, 4, 0, 0, 0], [0, 0, 0, 3, 0, 0, 0, 0, 6], [0, 0, 0, 0, 0, 0, 0, 7, 0], [0, 3, 0, 5, 0, 0, 0, 8, 0], [9, 7, 2, 4, 0, 0, 0, 5, 0]] puzzle4 = [[8, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 6, 0, 0, 0, 0, 0], [0, 7, 0, 0, 9, 0, 2, 0, 0], [0, 5, 0, 0, 0, 7, 0, 0, 0], [0, 0, 0, 0, 4, 5, 7, 0, 0], [0, 0, 0, 1, 0, 0, 0, 3, 0], [0, 0, 1, 0, 0, 0, 0, 6, 8], [0, 0, 8, 5, 0, 0, 0, 1, 0], [0, 9, 0, 0, 0, 0, 4, 0, 0]] solution = [[5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8], [1, 9, 8, 3, 4, 2, 5, 6, 7], [8, 5, 9, 7, 6, 1, 4, 2, 3], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 4, 5, 2, 8, 6, 1, 7, 9]] pp = [puzzle1, puzzle2, puzzle3, puzzle4] + \ [puzzle1, puzzle2, puzzle3, puzzle4] t = time.time() for j in range(4): print(solve_fast(pp.pop())) print(time.time() - t) t = time.time() for j in range(4): print(sudoku_fast(pp.pop())) print(time.time() - t) # t = time.time() # print(sudoku(pp.pop())) # print(time.time() - t)
# code: utf-8 import time class Sudoku: def __init__(self, puzzle): self.puzzle = puzzle self.solution = [] self.parse_puzzle() def solve(self): def solve_iter(fix_dict, possible_dict): # print state for each iter, largely slowdown the function # print(self.pnt(fix_dict)) # return True if all fixed if len(fix_dict) == 81: # get solution self.solution.append(self.pnt(fix_dict)) # assert finish assert(self.finish_check()) return False # sort possibles as uncertainty sorted_possible = sorted( possible_dict.items(), key=lambda d: len(d[1])) if len(sorted_possible[0][1]) == 0: return False # choose least uncertain as (j, k) least_uncertain = sorted_possible[0] j, k = least_uncertain[0] # collect 20 neighbors neighbor_set = set(self.fix_dict.get(xy, 0) for xy in self.neighbor_nodes[(j, k)]) # for each candidate in least uncertainties for candidate in least_uncertain[1]: # not choose if conflict with existing neighbors if candidate in neighbor_set: continue # make new_fix_dict, new_possible_dict new_possible_dict = possible_dict.copy() new_fix_dict = fix_dict.copy() # de-uncertainty of (j, k) new_possible_dict.pop((j, k)) # update neighbors if they are uncertain for neighbor in self.neighbor_nodes[(j, k)]: if candidate in new_possible_dict.get(neighbor, []): new_possible_dict[neighbor] = new_possible_dict[ neighbor] - {candidate} # stop update if possibles is empty # since it will stop in next iter anyway if len(new_possible_dict[neighbor]) == 0: break # add (j, k) as candidate in new_fix_dict new_fix_dict[(j, k)] = candidate # go, go, go if solve_iter(new_fix_dict, new_possible_dict): return True # all candidates failed return False # start iter solve_iter(self.fix_dict, self.possible_dict) assert(not self.solution == []) if len(self.solution) > 1: print('multi solution.') return self.solution return self.solution def finish_check(self): # check if finish # for each 27 blocks for block in self.block_27: all_set = set(self.solution[-1][e[0]][e[1]] for e in block) # return False, if not 1, 2, ..., 8, 9 if not all_set == set(range(1, 10)): return False # return True, if all checked return True def pnt(self, fix_dict): # print and return board # init board = [['=' for _ in range(9)] for __ in range(9)] # for all fix nodes, set as number for it in fix_dict.items(): board[it[0][0]][it[0][1]] = it[1] # print print('-' * 60) for j, b in enumerate(board): print('%02d:' % (j*9), ' '.join(str(e) for e in b)) # return board return board def parse_puzzle(self): # protect code assert(len(self.puzzle) == 9) assert(len(self.puzzle[0]) == 9) # init rules self.mk_rules() # fix nodes as input self.fix_dict = dict() # uncertain nodes as input self.possible_dict = dict() for j, k in self.all_nodes: # protect code assert(self.puzzle[j][k] in range(10)) # uncertain if self.puzzle[j][k] == 0: tmp = set(range(1, 10)) for neighbor in self.neighbor_nodes[(j, k)]: tmp -= {self.puzzle[neighbor[0]][neighbor[1]]} assert(len(tmp) > 0) if len(tmp) > 1: self.possible_dict[(j, k)] = tmp else: # if only one possible self.fix_dict[(j, k)] = tmp.pop() # fix else: self.fix_dict[(j, k)] = self.puzzle[j][k] def mk_rules(self): # there are 27 9-nodes blocks self.block_27 = [] for j in range(9): self.block_27.append(set((j, y) for y in range(9))) for k in range(9): self.block_27.append(set((x, k) for x in range(9))) for j in [0, 3, 6]: for k in [0, 3, 6]: self.block_27.append(set((j+x, k+y) for x in range(3) for y in range(3))) # table 20 neighbors for each node self.neighbor_nodes = dict() # all 81 nodes self.all_nodes = [] for j in range(9): for k in range(9): # add a node self.all_nodes.append((j, k)) # add neighbors tmp = set() tmp = tmp.union(set((x, k) for x in range(9))) tmp = tmp.union(set((j, y) for y in range(9))) tmp = tmp.union(set((j//3*3+x, k//3*3+y) for x in range(3) for y in range(3))) tmp -= {(j, k)} self.neighbor_nodes[(j, k)] = tmp def solve(puzzle): sudoku = Sudoku(puzzle) return sudoku.solve() puzzle1 = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] puzzle2 = [[9, 0, 6, 0, 7, 0, 4, 0, 3], [0, 0, 0, 4, 0, 0, 2, 0, 0], [0, 7, 0, 0, 2, 3, 0, 1, 0], [5, 0, 0, 0, 0, 0, 1, 0, 0], [0, 4, 0, 2, 0, 8, 0, 6, 0], [0, 0, 3, 0, 0, 0, 0, 0, 5], [0, 3, 0, 7, 0, 0, 0, 5, 0], [0, 0, 7, 0, 0, 5, 0, 0, 0], [4, 0, 5, 0, 1, 0, 7, 0, 8]] puzzle3 = [[0, 8, 0, 0, 0, 9, 7, 4, 3], [0, 5, 0, 0, 0, 8, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [8, 0, 0, 0, 0, 5, 0, 0, 0], [0, 0, 0, 8, 0, 4, 0, 0, 0], [0, 0, 0, 3, 0, 0, 0, 0, 6], [0, 0, 0, 0, 0, 0, 0, 7, 0], [0, 3, 0, 5, 0, 0, 0, 8, 0], [9, 7, 2, 4, 0, 0, 0, 5, 0]] puzzle4 = [[8, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 6, 0, 0, 0, 0, 0], [0, 7, 0, 0, 9, 0, 2, 0, 0], [0, 5, 0, 0, 0, 7, 0, 0, 0], [0, 0, 0, 0, 4, 5, 7, 0, 0], [0, 0, 0, 1, 0, 0, 0, 3, 0], [0, 0, 1, 0, 0, 0, 0, 6, 8], [0, 0, 8, 5, 0, 0, 0, 1, 0], [0, 9, 0, 0, 0, 0, 4, 0, 0]] ppp = [puzzle1, puzzle2, puzzle3, puzzle4] t = time.time() for pp in ppp: solution = solve(pp) print(solution) print(len(solution)) print(time.time() - t)
# code: utf-8 import itertools def closest_pair(points): points = sorted(points) print(len(points)) # if len(points) > 1000: # return ((0, 0), (0, 0)) # print(points[0:2000]) return find_closest(points, 0, len(points))[0] pass def find_closest(points, start, end): #print('finding:', [points[_] for _ in range(start, end)]) if end - start < 10: closest_pair = (points[start], points[end-1]) least_dist = dist(closest_pair) for j, k in itertools.combinations(range(start, end), 2): d = dist((points[j], points[k])) if d < least_dist: least_dist = d closest_pair = (points[j], points[k]) return closest_pair, least_dist medium = (start + end) // 2 left_closest_pair, least_dist_left = find_closest(points, start, medium) #print(left_closest_pair, least_dist_left) if least_dist_left == 0: return left_closest_pair, 0 right_closest_pair, least_dist_right = find_closest(points, medium, end) #print(right_closest_pair, least_dist_right) if least_dist_right == 0: return right_closest_pair, 0 min_left_right = min([least_dist_left, least_dist_right]) closest_pair = (points[start], points[end-1]) least_dist = dist(closest_pair) for j in range(medium-1, start-1, -1): left_point = points[j] if (left_point[0]-points[medium][0])**2 > min_left_right/4: break for k in range(medium, end): right_point = points[k] if (right_point[0]-points[medium-1][0])**2 > min_left_right/4: break d = dist((left_point, right_point)) if d < least_dist: least_dist = d closest_pair = (left_point, right_point) if least_dist < min_left_right: return closest_pair, least_dist if least_dist_left < least_dist_right: return left_closest_pair, least_dist_left return right_closest_pair, least_dist_right def dist(pair): return (pair[0][0]-pair[1][0]) ** 2 + (pair[0][1]-pair[1][1]) ** 2 points1 = ( (2, 2), # A (2, 8), # B (5, 5), # C (6, 3), # D (6, 7), # E (7, 4), # F (7, 9) # G ) points2 = ( (2, 2), # A (2, 8), # B (5, 5), # C (5, 5), # C (6, 3), # D (6, 7), # E (7, 4), # F (7, 9) # G ) closest_pair(points1) closest_pair([(2, 2), (6, 3)])
# main_matrix = [[1,2,3],[4,5,6],[7,8,9]] # def matrix(): # return main_matrix def magic(player_place_list, each_choice_list): main_matrix = [[1,2,3],[4,5,6],[7,8,9]] if not player_place_list: main_matrix = [[1,2,3],[4,5,6],[7,8,9]] else: for ind_1,i in enumerate(main_matrix): for ind_2,a in enumerate(i): if str(a) in player_place_list: ind_3 = player_place_list.index(str(a)) main_matrix[ind_1][ind_2] = each_choice_list[ind_3] else: main_matrix[ind_1][ind_2] = a return main_matrix def display_board(player_place_list, each_choice_list): board = '' for index,i in enumerate(magic(player_place_list, each_choice_list)): for n,a in enumerate(i): board += str(a)+'|' if n == len(i) - 1: board = board + '\n' break return board def player_selection(): player2 ='' while player2 == '': player1 =input('Player 1 please select between "x" or "o" begin the game: ').lower() if player1 in ('x','o'): if player1 == 'x': player2 = 'o' print(f'Player_1 has selected {player1} and Player_2 has selected {player2}') else: player2 = 'x' print(f'Player_1 has selected {player1} and Player_2 has selected {player2}') else: print('Please enter a valid selection to begin the game') player_selection = [player1,player2] return player_selection def player_place(each_choice_list,selection,player_place_list,player_place_selection): for i in [[1,2,3],[4,5,6],[7,8,9]]: if player_place_selection in str(i): if player_place_selection not in player_place_list: print(f'Great Job!!') player_place_list.append(player_place_selection) else: print(f'Position {player_place_selection} is already occupied. Please enter a valid number between 1-9 that is on the the board') player_turn(each_choice_list,selection,player_place_list) break else: print('Please enter a valid number between 1-9 that is on the the board') player_turn(each_choice_list,selection,player_place_list) def player_turn(each_choice_list,selection,player_place_list): if len(each_choice_list) == 0: player_place_selection = input(f'Player_1 please select where you want to insert your {selection[0]}: ') player_place(each_choice_list,selection,player_place_list,player_place_selection) return (selection[0]) else: if each_choice_list[-1] == selection[0]: player_place_selection = input(f'Player_2 please select where you want to insert your {selection[1]}: ') player_place(each_choice_list,selection,player_place_list,player_place_selection) return (selection[1]) else: player_place_selection = input(f'Player_1 please select where you want to insert your {selection[0]}: ') player_place(each_choice_list,selection,player_place_list,player_place_selection) return (selection[0]) def game_win(player_place_list, each_choice_list): main_matrix = magic(player_place_list, each_choice_list) winning_list = [['x','x','x'], ['o','o','o']] # game_win = None if [a for a in main_matrix for i in winning_list if a == i]: game_win = True elif [a for a in list(zip(main_matrix[0],main_matrix[1],main_matrix[2])) for i in winning_list if i ==list(a)]: game_win = True elif [a for a in winning_list if a == [main_matrix[0][0],main_matrix[1][1],main_matrix[2][2]]]: game_win = True elif [a for a in winning_list if a == [main_matrix[0][2],main_matrix[1][1],main_matrix[2][0]]]: game_win = True else: game_win = False return game_win def winner(player_place_list, each_choice_list,selection): if game_win(player_place_list, each_choice_list): if selection[0] == each_choice_list[-1]: print('Player1 has won the game') else: print('Player2 has won the game') return True elif (len(each_choice_list) == 9): print('Tie game!! Game Over!!') return True else: return False def each_choice(): start = True while start: game = True while game: selection = player_selection() print(selection) print(f'Player1 will start the game with: {selection[0]}') each_choice_list = [] player_place_list = [] while not winner(player_place_list, each_choice_list, selection): print(display_board(player_place_list, each_choice_list)) each_choice_list.append(player_turn(each_choice_list,selection,player_place_list)) display_board(player_place_list, each_choice_list) # winner(player_place_list, each_choice_list, selection) game = False start = replay() def replay(): replay = input('Do you want to play again: y or n: ') if replay == 'y': start = True else: start = False return start each_choice() # def final(): # game = True # while game: # each_choice()
import pandas as pd # create dictionary data city = {'id': [3, 2, 1, 1], 'city': ['Toronto', 'Oakville', 'Mississauga', 'Mississauga'], 'postal': ['1111', '2222', '3333', '4444']} # create dataframe manually from Dictionary/List dfc = pd.DataFrame(city) print(dfc) # order by ID ascending, postal descending order dfc = dfc.sort_values(by=['id', 'postal'], ascending=[True, False]) print(dfc) # do the above in 1 step dfc = pd.DataFrame(city).sort_values(by=['id', 'postal'], ascending=[True, False]) print(dfc) # create similar as above but using list and doing a zip then Define the columns manually # ie Sandwich getting smushed, then take a bit is a set my_zip = zip([3, 2, 1, 1], ['Toronto', 'Oakville', 'Mississauga', 'Mississauga'], ['1111', '2222', '3333', '4444']) print('my_zip -----------------', my_zip) city = list(my_zip) print('my_zip turned to list -', city) # vs list of tuples my_list_of_tuples = [(3, 'Toronto', '1111'), (2, 'Oakville', '2222'), (1, 'Mississauga', '3333'), (1, 'Mississauga', '4444')] print('my_list_of_tuples -----', my_list_of_tuples) city2 = my_list_of_tuples # single command to set df dfc = pd.DataFrame(city2, columns=['cityID', 'cityName', 'cityPostal']).sort_values(by=['cityID', 'cityPostal'], ascending=[True, False]) print('\nUsing list of tuples' + '\n' * 2, dfc) # single command to set df dfc = pd.DataFrame(city, columns=['cityID', 'cityName', 'cityPostal']).sort_values(by=['cityID', 'cityPostal'], ascending=[True, False]) print('\nUsing list that was ziped then converted back to a list' + '\n' * 2, dfc) # set index dfc.set_index('cityID') print(dfc) # since the index should be unique, this should not be the index but the city ID dfc.reset_index print(dfc) # since the index should be unique, this should not be the index but the city ID dfc.rename(columns={'cityID': 'cityNumber'}, inplace=True) print(dfc) # reset Index to be anal and inplace to commit the change dfc.reset_index(drop=True, inplace=True) print(dfc) zone = {'zoneID': [1, 2, 3], 'zoneName': ['M', 'O', 'T']} dfz = pd.DataFrame(zone) dfmerge = pd.merge(dfc, dfz, left_on='cityNumber', right_on='zoneID') print(dfmerge) # Filtering print(dfmerge.loc[dfmerge.zoneID < 3]) # Filtering with & and Or print(dfmerge.loc[(dfmerge.zoneID < 3) & ((dfmerge.zoneID == 1) | (dfmerge.zoneID == 2))]) # 2nd and 3rd rows then specific columns by Name print(dfmerge.loc[1:2, ['cityName', 'zoneID']]) # 1st and 3rd column, and specific column name print(dfmerge.loc[[0, 2], ['cityName', 'zoneID']]) # using iloc to get rows/columns by numeric value print(dfmerge.iloc[[0, 2], 1:4]) print(dfmerge) # delete column zoneName dfmerge.drop('zoneName', axis=1, inplace=True) print(dfmerge) # delete multiple columns dfmerge.drop(['zoneID', 'cityPostal'], axis=1, inplace=True) print(dfmerge) # delete row by index number dfmerge.drop([3], axis=0, inplace=True) print(dfmerge) # delete non sequential rows by index number dfmerge.drop([0, 2], axis=0, inplace=True) print(dfmerge) df2Data = {'cityNumber': [1, 1, 1, 1, 2, 2, 3, 3], 'cityName': ['Mississauga', 'Mississauga', 'Mississauga', 'Mississauga', 'Oakville', 'Oakville', 'Toronto', 'Toronto']} df2 = pd.DataFrame(df2Data) print('df2\n', df2) # append and sort by index... NOTEICE the duplicate Index Number 1 dfmerge = dfmerge.append(df2).sort_index() print(dfmerge) # merge but this time ignore the index dfmerge = dfmerge.append(df2, ignore_index=True) print(dfmerge) # drop based on filter # stroe the index indexNames = dfmerge.loc[(dfmerge.cityNumber > 1) | (dfmerge.cityNumber > 2)].index print(indexNames) dfmerge.drop(indexNames, inplace=True) print(dfmerge) dfmerge.reset_index(drop=True, inplace=True) print(dfmerge) # set New index based on List origIndex = list(dfmerge.index) print(origIndex) newIndex = list(map(lambda x: x * 2, origIndex)) dfmerge.index = newIndex print(dfmerge) # add column # random ID import random randIDList1 = {'randID_1': [random.randint(0, 9) for x in range(9)]} randIDList2 = {'randID_2': [random.randint(0, 9) for x in range(9)]} print(randIDList1) pdrand1 = pd.DataFrame(randIDList1) pdrand2 = pd.DataFrame(randIDList2) print(pdrand1) # results if you don't reset the index print(pd.concat([dfmerge, pdrand1], axis=1)) # join should work as well dfmerge.reset_index(drop=True, inplace=True) pdrand1.reset_index(drop=True, inplace=True) pdrand2.reset_index(drop=True, inplace=True) # results after dropping index dfmerge = pd.concat([dfmerge, pdrand1, pdrand2], axis=1) print(dfmerge) # using group by to get some stats print(dfmerge.groupby(['randID_1']).count()) print(dfmerge.groupby(['cityName', 'randID_2']).count()) dfcount = dfmerge.groupby(['cityName', 'randID_2']).count() dfcount.index print(dfcount) dfcount.columns = ['a', 'b'] dfcount.rename(columns={'cityName': 'aa'}, inplace=True) print(dfcount) # convert to list df_list_all = dfmerge.values.tolist() df_list_multi_fields = dfmerge[['cityName', 'randID_1']].values.tolist() df_list_city = dfmerge.cityName.tolist() print(df_list_all, df_list_city, df_list_multi_fields) help(pd.Series.loc) # read from excel # I/O # Read and Write to CSV # >>> pd.read_csv('file.csv', header=None, nrows=5) # >>> pd.to_csv('myDataFrame.csv') # Read multiple sheets from the same file # >>> xlsx = pd.ExcelFile('file.xls') # >>> df = pd.read_excel(xlsx, 'Sheet1') # Read and Write to Excel # >>> pd.read_excel('file.xlsx') # >>> pd.to_excel('dir/myDataFrame.xlsx', sheet_name='Sheet1') # define the file to read xls = pd.ExcelFile('C:/Users/rc/Google Drive/corporation/2019/2019 Corporate expenses.xlsx') # assign the excel to dataframe, and choose the tab name df = pd.read_excel(xls, 'Credit Card') # df = df.loc[:, ['Date', 'Type', 'amount']] print(df.groupby(['Type'])['amount', 'credit'].agg('sum'))
import sys import pygame def check(a, b, c): if clicked[a] == 0: return False elif clicked[b] == 0: return False elif clicked[c] == 0: return False else: if clicked [a] % 2 == clicked[b] % 2: if clicked [a]%2 == clicked[c]%2: return True else: return False else: return False # Initialize pygame so it runs in the background and manages things pygame.init() def give_color(clicked, hovering): #determine what color the box will turn when clicked or hovering if clicked != 0: if clicked % 2 == 0: return (255, 255, 255) else: return (255, 0, 0) else: if hovering: return (128, 128, 128) else: return (0, 0, 0) # Create a display. Size must be a tuple, which is why it's in parentheses screen = pygame.display.set_mode( (400, 300) ) clicked = [0, 0, 0, 0, 0, 0, 0, 0, 0] hovered = [False, False, False, False, False, False, False, False, False] # Main loop. Your game would go inside this loop total_clicks = 0 while True: # do something for each event in the event queue (list of things that happen) for event in pygame.event.get(): if event.type == pygame.QUIT: # If so, exit the program sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: total_clicks += 1 pos = pygame.mouse.get_pos() #determine if number of clicks is even or odd if ((50<pos[0] and pos[0]<150) and (50<pos[1] and pos[1]<100)): if total_clicks % 2 == 0: clicked[0] = 2 else: clicked[0] = 1 if ((150<pos[0] and pos[0]<250) and (100<pos[1] and pos[1]<200)): if total_clicks % 2 == 0: clicked[4] = 2 else: clicked[4] = 1 if ((150<pos[0] and pos[0]<250) and (200<pos[1] and pos[1]<250)): if total_clicks % 2 == 0: clicked[7] = 2 else: clicked[7] = 1 if ((50<pos[0] and pos[0]<150) and (100<pos[1] and pos[1]<200)): if total_clicks % 2 == 0: clicked[3] = 2 else: clicked[3] = 1 if ((150<pos[0] and pos[0]<250) and (50<pos[1] and pos[1]<100)): if total_clicks % 2 == 0: clicked[1] = 2 else: clicked[1] = 1 if ((50<pos[0] and pos[0]<150) and (200<pos[1] and pos[1]<250)): if total_clicks % 2 == 0: clicked[6] = 2 else: clicked[6] = 1 if ((250<pos[0] and pos[0]<350) and (50<pos[1] and pos[1]<100)): if total_clicks % 2 == 0: clicked[2] = 2 else: clicked[2] = 1 if ((250<pos[0] and pos[0]<350) and (100<pos[1] and pos[1]<200)): if total_clicks % 2 == 0: clicked[5] = 2 else: clicked[5] = 1 if ((250<pos[0] and pos[0]<350) and (200<pos[1] and pos[1]<250)): if total_clicks % 2 == 0: clicked[8] = 2 else: clicked[8] = 1 if event.type == pygame.MOUSEMOTION: #allow hover of boxes to be gray pos = pygame.mouse.get_pos() if ((50<pos[0] and pos[0]<150) and (50<pos[1] and pos[1]<100)): hovered[0]= True hovered[1]= False hovered[2]= False hovered[3]= False hovered[4]= False hovered[5]= False hovered[6]= False hovered[7]= False hovered[8]= False if ((150<pos[0] and pos[0]<250) and (100<pos[1] and pos[1]<200)): hovered[4]= True hovered[0]= False hovered[1]= False hovered[2]= False hovered[3]= False hovered[5]= False hovered[6]= False hovered[7]= False hovered[8]= False if ((150<pos[0] and pos[0]<250) and (200<pos[1] and pos[1]<250)): hovered[7]= True hovered[0]= False hovered[1]= False hovered[2]= False hovered[3]= False hovered[4]= False hovered[5]= False hovered[6]= False hovered[8]= False if ((50<pos[0] and pos[0]<150) and (100<pos[1] and pos[1]<200)): hovered[3]= True hovered[0]= False hovered[1]= False hovered[2]= False hovered[4]= False hovered[5]= False hovered[6]= False hovered[7]= False hovered[8]= False if ((150<pos[0] and pos[0]<250) and (50<pos[1] and pos[1]<100)): hovered[1]= True hovered[0]= False hovered[2]= False hovered[3]= False hovered[4]= False hovered[5]= False hovered[6]= False hovered[7]= False hovered[8]= False if ((50<pos[0] and pos[0]<150) and (200<pos[1] and pos[1]<250)): hovered[6]= True hovered[0]= False hovered[1]= False hovered[2]= False hovered[3]= False hovered[4]= False hovered[5]= False hovered[7]= False hovered[8]= False if ((250<pos[0] and pos[0]<350) and (50<pos[1] and pos[1]<100)): hovered[2]= True hovered[0]= False hovered[1]= False hovered[3]= False hovered[4]= False hovered[5]= False hovered[6]= False hovered[7]= False hovered[8]= False if ((250<pos[0] and pos[0]<350) and (100<pos[1] and pos[1]<200)): hovered[5]= True hovered[0]= False hovered[1]= False hovered[2]= False hovered[3]= False hovered[4]= False hovered[6]= False hovered[7]= False hovered[8]= False if ((250<pos[0] and pos[0]<350) and (200<pos[1] and pos[1]<250)): hovered[8]= True hovered[0]= False hovered[1]= False hovered[2]= False hovered[3]= False hovered[4]= False hovered[5]= False hovered[6]= False hovered[7]= False # Check to see if the current event is a QUIT event # main code goes here pygame.draw.rect(screen, give_color(clicked[8], hovered[8]), (250,200,100,50)) pygame.draw.rect(screen, give_color(clicked[4], hovered[4]), (150,100,100,100)) pygame.draw.rect(screen, give_color(clicked[7], hovered[7]), (150,200,100,50)) pygame.draw.rect(screen, give_color(clicked[3], hovered[3]), (50,100,100,100)) pygame.draw.rect(screen, give_color(clicked[1], hovered[1]), (150,50,100,50)) pygame.draw.rect(screen, give_color(clicked[6], hovered[6]), (50,200,100,50)) pygame.draw.rect(screen, give_color(clicked[2], hovered[2]), (250,50,100,50)) pygame.draw.rect(screen, give_color(clicked[5], hovered[5]), (250, 100, 100, 100)) pygame.draw.rect(screen, give_color(clicked[0], hovered[0]), (50,50,100,50)) pygame.draw.line(screen, (255, 255, 255), (50, 100), (350, 100), 1) pygame.draw.line(screen, (255, 255, 255), (50, 200), (350, 200), 1) pygame.draw.line(screen, (255, 255, 255), (150, 50), (150, 250), 1) pygame.draw.line(screen, (255, 255, 255), (250, 50), (250, 250), 1) if check(0, 1, 2) == True: print("you win") break elif check(3,4,5) == True: print("You win") break elif check(6,7,8) == True: print("you win") break elif check(0,3,6) == True: print("You win") break elif check(1,4,7) == True: print("you win") break elif check(2,5,8) == True: print("You win") break elif check(0,4,8) == True: print("You win") break elif check(2,4,6) == True: print("You win") break pygame.display.flip()
#1 x = [ [5,2,3], [10,8,9] ] x[1][0] = 15 # Index 0 of index 1 in the string print(x) students = [ {'first_name': 'Michael', 'last_name': 'Jordan'}, {'first_name': 'John', 'last_name': 'Rosales'} ] students[0]['last_name'] = 'Bryant' # [0] is the first index in the string print(students) sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } sports_directory['soccer'][0] = 'Andfres' print(sports_directory) z = [ {'x': 10, 'y': 20} ] z[0]['y'] = 30 print(z) #2 I could not get this one to work because I was not in the python shell and did not use python3 to run it in the terminal students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterate_dictionary(some_list): for curr_dict in some_list: display_str = "" for curr_key in curr_dict.keys(): display_str += f"{curr_key} - {curr_dict[curr_key]}" display_str = display_str[:len(display_str) - 2] print(display_str) iterate_dictionary(students) #3 Figuring these out with the help of the solution code and backing into how the output was derrived. students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterate_dictionary2(key, some_list): for curr_dict in some_list: print(curr_dict[key]) iterate_dictionary2('first_name', students) iterate_dictionary2('last_name', students) #4 # I can not get this one to print out the list of locations dojo = { 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'], 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon'] } def printInfo(some_dict): for key in some_dict.key(): print(f"{len(some_dict[key])} {key.upper()}") for item in some_dict[key]: print(item) print('\n') printInfo(dojo)
#!/usr/bin/env python3 # -*- coding=utf-8 -*- from decimal import Decimal class Player(): def __init__(self): self.hands=[] self.handsValue=0 self.winRate=0 self.currentMoney=Decimal() self.name='' def __str__(self): return self.name+" "+str(self.hands[0])+str(self.hands[1])+" money:"+str(self.currentMoney) def sortHands(self): self.hands.sort(key=lambda card:card.num) """ 以下行为委托 RoundGame类 完成 """ def bet(self,game,cashNum): betNum=Decimal(cashNum) if self.currentMoney<betNum: return False self.currentMoney-=Decimal(str(betNum)) game.playerBet(self,betNum) def fold(self,game): assert type(game)==RoundGame game.playerFold(self) def check(self,game): game.playerCheck(self)
#Given a number and number of changes you can make the number to change it to a palindrom. #Using those you need to return the largestPalindome. #If not possible you need to return -1 def LargestPalindrome(s,n,num): inp=num wr,i=0,0 flag=0 while(i<s//2): if inp[i]!=inp[s-1-i] and flag!=1: wr+=1 i+=1 rev=inp[::-1] if rev!=inp: i=0 if wr<n: for i in range(s//2): if inp[i]!=inp[s-1-i] and i!=0 and n>1: f=inp[0:i] mi=inp[i+1:s-i-1] l=inp[s-i:s] inp=f+"9"+mi+"9"+l n-=2 else: if i==0 and inp[i]!=inp[s-i-1] and n>1: mi=inp[i+1:s-i-1] inp="9"+mi+"9" n-=2 i+=1 for i,each in enumerate(inp): if inp[i]!=inp[s-i-1] and n>0: if int(inp[i])>int(inp[s-i-1]): f=inp[0:s-i-1] l=inp[s-i:] inp=f+inp[i]+l n-=1 else: f=inp[0:i] l=inp[i+1:] inp=f+inp[s-i-1]+l n-=1 else: for i in range(s//2): if i==0 and inp[i]!="9" and n>1: mi=inp[1:s-1] inp="9"+mi+"9" n-=2 elif inp[i]!="9" and n>1: f=inp[0:i] mi=inp[i+1:s-i-1] l=inp[s-i:] inp=f+"9"+mi+"9"+l n-=2 rev=inp[::-1] if inp==rev: return inp else: return "-1" #i="1111" #n=6 print(LargestPalindrome(5,3,"12399"))
#You are given a horizontal numbers each representing a cube side. #You need to pile them vertically such a way that,upper cube is <= lower cube. #Given you can take the horizontal cube side from either left most or from right most. #If it can be piled up vertivally retirn 'YES' or else return 'NO' #EX:3,2,1,1,5 #you first pick 5 and then palce 3 on it. #next 2 is place on 3 and 1 is on 2 and so on,So possibel.Return 'YES' def Piling(n,l): temp=max(l)+1 length=n//2 if n%2==1: length=n//2+1 for i in range(length): if max(l[i],l[n-1-i])<=temp: temp=min(l[i],l[n-1-i]) else: return 'No' return 'Yes' print(Piling(6,[3,2,1,1,2,5]))
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # filename:012.py # author: shuqing # 题目:判断101-200之间有多少个素数,并输出所有素数。 num = 0 for i in range(101, 201): for j in range(2, i): if(i % j == 0): break if (j == i-1): print(i) num += 1 print(num)
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # filename:for.py # author: shuqing for num in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']: print(num) for letter in 'hello': print(letter) for numbers in range(1, 5): print(numbers)
#Point 實體物件的設計: 平面座標上的點 # class Point:#定義類別 # def __init__(self, x, y):#建立初始化函式 # self.x=x#定義實體屬性 # self.y=y#定義實體屬性 # #定義實體方法 # def show(self): # print(self.x, self.y) # def distance(self, targetX, targetY): # return((((self.x-targetX)**2)+((self.y-targetY)**2))**0.5) # p=Point(3,4) #建立實體物件 # p.show() #呼叫實體方法 # result=p.distance(0,0) #計算座標3,4和座標0,0之間的距離 # print(result) #FullName 實體物件的設計: 分開紀錄姓、 名資料的全名 # class FullName:#定義類別 # def __init__(self,first,last): # self.first=first # self.last=last # name1=FullName("bokai","Liu")#產生實體物件 # print(name1.first, name1.last)#操作實體物件屬性 # name2=FullName("djsijdi","ddsi") # print(name2.first, name2.last) #FullName 實體物件的設計: 分開紀錄姓、 名資料的全名 class File: #初始化函式 def __init__(self, name): self.name=name self.file=None #尚未開啟檔案:初期是None #實體方法 def open(self): self.file=open(self.name, mode="r", encoding="utf8") def read(self): return self.file.read() #讀取第一個檔案 f1=File("data1.txt") f1.open() data=f1.read() print(data) #讀取第二個檔案 f2=File("data2.txt") f2.open() data2=f2.read() print(data2)
# 模式 匹配 # abc 找出abc # (abc) 找出abc # ab|cd 找出ab或cd # . 找出除了\n以為的任何字元(\n是換行) # ^abc 找出abc開頭的字 # abc$ 找出abc結尾的字 # abc? 找出0個或多個abc # abc* 找出0個或多個abc(越多越好) # abc*? 找出0個或多個abc(越少越好) # abc+ 找出1個或多個abc(越多越好) # abc- 找出1個或多個abc(越少越好) # abc{m} 找出m個連續的abc # abc{m, n} 找出m~n個連續的abc(越多越好) # abc{m, n}? 找出m~n個連續的abc(越少越好) # [abc] 等於a|b|c # [^abc] 不含abc字串 # abc(?= next) 找出abc且他後面有next # abc(?! next) 找出abc且他後面沒有next # (?<= abc)next 找出next且他前面匹配abc # (?<! abc)next 找出next且他前面不是abc import re source = """III I wish I may, I wish I might...Have a dish of fish tonight. I I I""" m = re.findall('wish',source) print(m) m = re.findall('(wish)',source) print(m) m = re.findall('wish|I',source) print(m) m = re.findall('.',source) print(m) m = re.findall('^I',source) print(m) m = re.findall('to.*$',source) print(m) m = re.findall('I ?',source) print(m) m = re.findall('I *',source) print(m) m = re.findall('wish.*?',source) print(m) m = re.findall('wish+',source) print(m) m = re.findall('wish+?',source) print(m) m = re.findall('I{3}',source) print(m) m =re.findall('I{2,4}',source) print(m) m =re.findall('I{2,3}?',source) print(m) m = re.findall('[wish I]',source) print(m) m = re.findall('[^ wish I]',source) print(m) m = re.findall('I (?=wish)',source) print(m) m = re.findall('I(!=wish)',source) print(m) m = re.findall('(?<=I) wish',source) print(m) m = re.findall('(?<! I) wish',source) print(m)
# coding: utf-8 # In[3]: def sum(n): total=0 i=1 while(i<n): if n%i==0: total+=i i+=1 return total def amc(m): i=m+1 while(1): a=sum(i) if i==sum(a): if i!=a: return i i+=1 # In[4]: amc(5)
""" This code is doing following : 1- Run softmax regression model for mnist digit classification by giving pixels values as input 2- Perform the same operation with CNN """ #Download and input mnist data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import ipdb """ #Visualize the data print('Train data images : ',mnist.train.images.shape) print('Train data labels : ',mnist.train.labels.shape) print('Test data images : ',mnist.test.images.shape) print('Test data labels : ',mnist.test.labels.shape) import tensorflow as tf sess=tf.InteractiveSession() #Define input x=tf.placeholder(tf.float32,shape=[None,784]) y_=tf.placeholder(tf.float32,shape=[None,10]) W=tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) sess.run(tf.global_variables_initializer()) y = tf.matmul(x,W) + b cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) for _ in range(50000): batch = mnist.train.next_batch(100) train_step.run(feed_dict={x: batch[0], y_: batch[1]}) correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})) """ #This section we will use a CNN for mnist digit classification import argparse import sys import tensorflow as tf FLAGS = None batch_size=64 learning_rate = 0.01 mnist = input_data.read_data_sets('MNIST_data', one_hot=True) x = tf.placeholder(tf.float32, [None, 784]) y_ = tf.placeholder(tf.float32, [None, 10]) sess = tf.InteractiveSession() #Initialization of weights and bias def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) #To make code clean, it is good idea to have functions for convolution and pooling operations def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') #Get the weights and bias for first convolution and pooling layer x_image=tf.reshape(x,[-1,28,28,1]) W_conv1=weight_variable([5,5,1,32]) b_conv1=bias_variable([32]) #Before we pass our image to first convolutional filter, we have to reshape the input data into (batch x width x height x channels) #We take the image, pass it to convolution operation and then apply ReLU activation. h_conv1=tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1) h_pool1=max_pool_2x2(h_conv1) W_conv2=weight_variable([5,5,32,64]) b_conv2=bias_variable([64]) h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2) h_pool2=max_pool_2x2(h_conv2) W_fc1 = weight_variable([7*7*64,1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) #Add dropout to prevent overfeating keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) #Add second full connected layer W_fc2 = weight_variable([1024,10]) b_fc2 = bias_variable([10]) y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess.run(tf.global_variables_initializer()) for i in range(2000): batch = mnist.train.next_batch(batch_size) # train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) if i%10 == 0: train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g"%(i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) print("test accuracy %g"%accuracy.eval(feed_dict={ x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
class Node(object): def __init__(self,item): self.item = item self._next = None class singleLinkList(object): def __init__(self): # 头节点 self._head = None def is_empty(self): return self._head == None def length(self): # 首先要指向头节点 cur = self._head count = 0 while cur is not None: count = count+1 cur = cur._next return count def travel(self): if self.is_empty(): return # 首先要指向头节点 cur = self._head while cur != None: print(cur.item) cur = cur._next print("") def first_add(self,elem): # 把新添加的数定义到Node类里,这样它就会有item和_next两个属性 p = Node(elem) p._next = self._head # 把链表的头节点指向新添加的节点 self._head = p def last_add(self,elem): cur = self._head p = Node(elem) # 首先判断这个链表是不是空的 if self.is_empty(): self._head = p else: cur = self._head while cur._next != None: cur = cur._next cur._next = p def insert(self,index,elem): # 如果插入的地方在第一个位置之前,直接调用在首部插入的方法 if index<=0 : self.first_add(elem) # 如果插入的地方在最后一个位置之后,直接调用在尾部插入的方法 elif index>(self.length()-1): self.last_add(elem) else: p = Node(elem) count = 0 pre = self._head while count<(index-1): pre = pre._next count = count+1 p._next = pre._next pre._next = p def remove(self,elem): cur = self._head pre = None while cur is not None: if cur. # 如果第一个就是要删除的节点 if not pre: self._head = cur._next else: pre._next = cur._next break else: # 将删除位置前一个节点的next指向删除位置的后一个节点 pre = cur cur = cur._next def search(self,elem): cur = self._head index = 0 while cur is not None: if cur.item == elem: return index else: cur = cur._next index = index+1 return index if __name__ == "__main__": ll = singleLinkList() print("-------创建链表,首部加1,首部加2---------") ll.first_add(1) # print(ll.travel()) ll.first_add(2) ll.travel() print("-------尾部添加3---------") ll.last_add(3) ll.travel() print("-------在索引为2的位置添加4---------") ll.insert(2, 4) print("length:",ll.length()) ll.travel() print("-------查找链表中某一个数的索引---------") index = ll.search(2) print(index) print("-------删除链表中某一个数---------") ll.remove(3) # print "length:",ll.length() ll.travel()