text
stringlengths
37
1.41M
# 아래와 같은 입력에 대한 출력을 제공하는 프로그램을 작성하시오. # 문제. 4 unpaired tag finder아래와같은입력에대한출력을제공하는프로그램을작성하시오. # 예시 1)Input: "<div><div><b></b></div></p>" # Output: div # 예시 2)Input: "<div>abc</div><p><em><i>test test test</b></em></p>" # Output: i input_string = input("태그 입력:") tag_list = [] tag_str = "" for x in input_string: tag_str = tag_str + x if "<" not in tag_str: tag_str = "" if "<" and ">" in tag_str: num = len(tag_str) tag_str = tag_str[1:num-1] if "/" in tag_str: tag_str = tag_str.replace("/","") if tag_str not in tag_list: tag_list.append("/"+tag_str) else: tag_list.remove(tag_str) else: tag_list.append(tag_str) tag_str = "" print("unpaired tag",tag_list) ############################################ 추가로 /p 태그나 /b 태그 안넣고 싶으면 list작성 후 조건문 돌리기
"""An incomplete Huffman Coding module, for use in COSC262. Richard Lobb, April 2021. """ import re HAS_GRAPHVIZ = True try: from graphviz import Graph except ModuleNotFoundError: HAS_GRAPHVIZ = False class Node: """Represents an internal node in a Huffman tree. It has a frequency count, minimum character in the tree, and left and right subtrees, assumed to be the '0' and '1' children respectively. The frequency count of the node is the sum of the children counts and its minimum character (min_char) is the minimum of the children min_chars. """ def __init__(self, left, right): self.left = left self.right = right self.count = left.count + right.count self.min_char = min(left.min_char, right.min_char) def __repr__(self, level=0): return ((2 * level) * ' ' + f"Node({self.count},\n" + self.left.__repr__(level + 1) + ',\n' + self.right.__repr__(level + 1) + ')') def is_leaf(self): return False def plot(self, graph): """Plot the tree rooted at self on the given graphviz graph object. For graphviz node ids, we use the object ids, converted to strings. """ graph.node(str(id(self)), str(self.count)) # Draw this node if self.left is not None: # Draw the left subtree self.left.plot(graph) graph.edge(str(id(self)), str(id(self.left)), '0') if self.right is not None: # Draw the right subtree self.right.plot(graph) graph.edge(str(id(self)), str(id(self.right)), '1') class Leaf: """A leaf node in a Huffman encoding tree. Contains a character and its frequency count. """ def __init__(self, count, char): self.count = count self.char = char self.min_char = char def __repr__(self, level=0): return (level * 2) * ' ' + f"Leaf({self.count}, '{self.char}')" def is_leaf(self): return True def plot(self, graph): """Plot this leaf on the given graphviz graph object.""" label = f"{self.count},{self.char}" graph.node(str(id(self)), label) # Add this leaf to the graph def traverse(node, dicc=None, path=''): if dicc is None: dicc = dict( ) if isinstance(node, Leaf): # then leaf node, push path onto stack dicc[node.char] = path return dicc else: traverse(node.left, dicc, path + '0') traverse(node.right, dicc, path + '1') return dicc class HuffmanTree: """Operations on an entire Huffman coding tree. """ def __init__(self, root=None): """Initialise the tree, given its root. If root is None, the tree should then be built using one of the build methods. """ self.root = root def encode(self, text): """Return the binary string of '0' and '1' characters that encodes the given string text using this tree. """ dicc = traverse(self.root) binary = [] for char in text: binary.append(dicc[char]) return ''.join(binary) def decode(self, binary): """Return the text string that corresponds the given binary string of 0s and 1s """ cur = self.root shove = [] for c in binary: if isinstance(cur, Leaf): shove.append(cur.char) cur = self.root if c == "0": cur = cur.left elif c == "1": cur = cur.right elif c == "0": cur = cur.left elif c == "1": cur = cur.right if isinstance(cur, Leaf): shove.append(cur.char) return ''.join(shove) def plot(self): """Plot the tree using graphviz, rendering to a PNG image and displaying it using the default viewer. """ if HAS_GRAPHVIZ: g = Graph() self.root.plot(g) g.render('tree', format='png', view=True) else: print("graphviz is not installed. Call to plot() aborted.") def __repr__(self): """A string representation of self, delegated to the root's repr method""" return repr(self.root) def build_from_freqs(self, freqs): """Define self to be the Huffman tree for encoding a set of characters, given a map from character to frequency. """ pairs = [] # Leaf (freq, char) for key, val in freqs.items(): pairs.append(Leaf(val, key)) pairs.sort(key=lambda node: -node.count) while len(pairs) > 1: pairs.sort(key=lambda node: -node.count - ord()) a,b = pairs.pop(), pairs.pop() if a.count == b.count: # sort alphabet, nodes go on the right if can if isinstance(b, Leaf) and isinstance(a, Leaf): if a.char < b.char: b,a = a,b pairs.append(Node(a,b)) assert len(pairs) > 0, "hmmm" self.root = pairs.pop() def build_from_string(self, s): """Convert the string representation of a Huffman tree, as generated by its __str__ method, back into a tree (self). There are no syntax checks on s so it had better be valid! """ s = s.replace('\n', '') # Delete newlines s = re.sub(r'Node\(\d+,', 'Node(', s) self.root = eval(s) # The example from the notes freqs = {'a': 9, 'b': 8, 'c': 15, 'd': 3, 'e': 5, 'f': 2} tree = HuffmanTree() tree.build_from_freqs(freqs) print(tree) print("\n\n") freqs = { 'p': 27, 'q': 11, 'r': 27, 'u': 8, 't': 5, 's': 3} tree = HuffmanTree() tree.build_from_freqs(freqs) print(tree)
# coding=utf-8 def extract_data_from_post(post): """ Extract likes_count, shares_count, comments_count from post :param post: facebook post :return: int, int, int """ # The number of reactions, shares, comments of a specific post reactions_count = 0 shares_count = 0 comments_count = 0 # If the post have reactions if 'reactions_count' in post: reactions_count = int(post['reactions_count']) # If the post has been shared if 'shares_count' in post: shares_count = int(post['shares_count']) # If the post has been commented if 'comments_count' in post: comments_count = int(post['comments_count']) # Return statement return reactions_count, shares_count, comments_count def get_stats_from_list(list_of_numbers): """ Return statistics about the data, essentially Max/Average :param list_of_numbers: List of numbers :return: int, float """ # Check if the list is empty if len(list_of_numbers) == 0: # Set to 0 maximum = average = 0 else: maximum, average = list_of_numbers[-1], sum(list_of_numbers) * 1.0 / len(list_of_numbers) # Return statement return maximum, average def get_stats_from_all_posts(posts, dic): """ Get statistics about all the posts :param posts: All posts of a facebook page :param dic: dictionary where to add the key value entries :return: dictionary """ # Create three lists respectively for reactions, shares and comments reactions = [] shares = [] comments = [] # Add likes, shares and comments counts of every post to their respective list for post in posts: # Get the stats n_reactions, n_shares, n_comments = extract_data_from_post(post) # Add each object to it's appropriate list reactions.append(n_reactions) shares.append(n_shares) comments.append(n_comments) # Sort list to get the maximum reactions.sort() shares.sort() comments.sort() # Add to the dictionary the maximum and average of the likes, shares and comments of the posts' page dic['max_reactions'], dic['avg_reactions'] = get_stats_from_list(reactions) dic['max_shares'], dic['avg_shares'] = get_stats_from_list(shares) dic['max_comments'], dic['avg_comments'] = get_stats_from_list(comments) # Add to the dictionary the total number of posts in the page dic['total_posts'] = len(posts) # Add to the dictionary the talking_about_count (the talking_about_count out of the page's fans number) dic['talking_about_percent'] = dic['talking_about_count'] * 1.0 / dic['likes'] # Return statement return dic
a = int(input('valor a: ')) b = int(input('valor b: ')) c = int(input('valor c: ')) if a == b == c: print('todos os lados são igual é escaleno\ne') elif a == b or b == c or c == a: print('dois lados são iguais é Isósceles\ne') elif a != b != c: print('todos os lados são direfentes é Escaleno\ne') if a < b + c and b < a + c and c < b + a: print('podem formar um triangulo') else: print('não forma triangulo')
num = int(input('digite um numero até 4 digitos')) uni = num // 1 % 10 dez = num // 10 % 10 cen = num // 100 % 10 mil = num // 1000 % 10 print('unidade é {}\n' 'dezena é {}\n' 'centena é {}\n' 'milhar é {}\n' ''.format(uni, dez, cen, mil))
import sqlite3, datetime, time from pycpfcnpj import gen, cpfcnpj #pip install pycpfcnpj ou interpretador: procurar por: pycpfcnpj while True: connection = sqlite3.connect('cafeteria.db') c = connection.cursor() opcao = int(input('digite 1 para cadastro de cliente\n' 'digite 2 para cadastro de produto\n' 'digite 3 para fazer o pedido\n' 'digite 4 para relatório de vendas por dia\n' 'digite 5 para consulta de cadastro\n' 'digite 6 para alteração de cadastro\n')) if opcao == 1: cpfuser = input('digite seu cpf válido: ') dado = cpfcnpj.validate(cpfuser) if dado == True: print('trueee') cpf = cpfuser nomecompleto = str(input('digite nome completo: ')) datacadastro = str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S')) dia = int(input('digite o dia de aniversário ')) mes = int(input('digite o mes de aniversário ')) ano = int(input('digite o ano de aniversário ')) datanascimento = datetime.date(ano, mes, dia) num_ddd = int(input('digite seu DDD, 2 dígitos xx: ')) num_contato = int(input('digite numero de telefone, 9 dígitos: ')) def create_table(): c.execute( "create table if not exists cliente (id integer primary key, nomecompleto text, cpf integer, datacadastro text, datanascimento text, dia integer, mes integer, ano integer, ddd integer, contato integer)") create_table() def dadosentrada(): c.execute( "insert into cliente (nomecompleto, cpf, datacadastro, datanascimento, dia, mes, ano, ddd, contato) values (?,?,?,?,?,?,?,?,?)", (nomecompleto, cpf, datacadastro, datanascimento, dia, mes, ano, num_ddd, num_contato)) connection.commit() dadosentrada() else: print('false') elif opcao == 2: nomeproduto = str(input('digite o nome do produto: ')) pscliente = str(input('digite alguma observação do cliente: ')) valorproduto = float(input('digite o valor do produto: ')) def create_table2(): c.execute("create table if not exists produto (id integer primary key AUTOINCREMENT, nomeproduto text, pscliente text, valorproduto real)") create_table2() def dadosproduto(): c.execute("insert into produto (nomeproduto, pscliente, valorproduto) values (?,?,?)", (nomeproduto, pscliente, valorproduto)) connection.commit() dadosproduto() elif opcao == 3: acao = str(input('digite número do CPF do usuário: ')) sql3 = "select * from cliente where cpf = ? " for row in c.execute(sql3, (acao,)): id = row[0] print('usuario: {},\n' 'data do cadastro: {},\n' 'data do nascimento: {},\n' 'fone {} {}.\n' ''.format(row[1], row[3], row[4], row[8], row[9])) num = id print(num) '''if num > 0: print('zero ou maior') #estamos aqui else: print('nada')''' elif opcao == 4: print('4') elif opcao == 5: print('5') elif opcao == 6: print('6') else: print('opcao errada')
import math #ou #from math import trunc numero = float(input('digite numero real')) print('o valor digitado foi {}' ' e a porção inteira é {}' ''.format(numero, math.trunc(numero)))
valorcasa = float(input('valor da casa?')) salario = float(input('seu salario?')) print('mensalidade poderá ser até R$ {}'.format(salario*0.7)) quantidadeanos = int(input('quantidade de anos')) print('a quant de meses é {}'.format(quantidadeanos*12)) print('parabéns vc poderar comparar a casa' if (valorcasa/(quantidadeanos*12)) < (salario*0.7) else 'vc não poderar comprar a casa')
bea = 0 for c in range(0, 6): num = int(input('digite')) if num % 2 == 0: bea += num print(bea)
import datetime from funcao_aleatorias import falar, adicionar_tarefa, ler_tarefas # definir o nome da assistente virtual nome_assistente = "Milena a sua mocinha gostosa." # obter a data e hora atual agora = datetime.datetime.now() # perguntar ao usuário o que ele quer fazer falar(f"Olá, Douglas, eu sou a {nome_assistente}. O que você gostaria de fazer?") falar("Você pode me pedir para adicionar uma tarefa ao seu calendário ou para ler suas tarefas agendadas.") while True: comando = input("> ").lower() if "adicionar" in comando: falar("Para que dia e hora você gostaria de agendar a tarefa?") falar("Por favor, digite o dia no formato DD/MM/YYYY e a hora no formato HH:MM.") data_hora = input("> ") dia, hora = data_hora.split() tarefa = comando.split("adicionar", 1)[1].strip() adicionar_tarefa(dia, hora, tarefa) elif "ler" in comando: ler_tarefas() elif "cantar" in comando: pass elif "sair" in comando: falar("Até mais!") break else: falar("Desculpe, eu não entendi o que você disse. Por favor, tente novamente.")
#obtained_num = int(input("Please provide a number to simply output: ")) # print(obtained_num) print('INPUT OBTAINED:: ' + input('Please provide a val to simply output'))
a_tuple = (100, 200, 300) b_tuple = (500, 600, 700) print(a_tuple) print(a_tuple[0]) print(a_tuple[-1]) #del a_tuple # print(a_tuple) a, b, c = a_tuple print(f'a: {a}, b: {b}, c: {c}') print(a_tuple[:2]) print(a_tuple[1:]) print(a_tuple[:]) print(a_tuple + b_tuple)
import sys import pygame pygame.init() # Set the window size size = 600, 500 w, h = size screen = pygame.display.set_mode(size) BLACK = 0, 0, 0 RED = 255, 0, 0 GREEN = 0,255,0 GRAY = 150, 150, 150 YELLOW = 255, 255, 0 r = 25 BALL_COLOR = RED BALL_RADIUS = 20 WALL_COLOR = GRAY HOME_COLOR = GREEN CELL_WIDTH = 50 CELL_HEIGHT = 50 WALLS = [ (3, 4), (3, 5), (2, 2),(3,1),(8,6),(8,5),(6,5),(5,5),(8,7),(6,8), (11,6),(10,6),(10,8),(10,9),(7,9),(5,8) ] home=[(11,9)] # ball coordinates x = 3 y = 2 def pyhome(x,y): center = (x*CELL_WIDTH + CELL_WIDTH//2, y*CELL_HEIGHT + CELL_HEIGHT//2) pygame.draw.circle(screen, HOME_COLOR, center, BALL_RADIUS) def draw_ball(x, y): center = (x*CELL_WIDTH + CELL_WIDTH//2, y*CELL_HEIGHT + CELL_HEIGHT//2) pygame.draw.circle(screen, BALL_COLOR, center, BALL_RADIUS) def draw_wall(x, y): rect = (x*CELL_WIDTH, y*CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT) pygame.draw.rect(screen, WALL_COLOR, rect) def draw_walls(): for x, y in WALLS: draw_wall(x, y) def draw_grid(): for y in range(0, h, CELL_HEIGHT): pygame.draw.line(screen, YELLOW, (0, y), (w, y)) for x in range(0, w, CELL_WIDTH): pygame.draw.line(screen, YELLOW, (x, 0), (x, h)) def paint(): screen.fill(BLACK) draw_walls() draw_grid() pyhome(11,9) draw_ball(x, y) def bound(x, minvalue, maxvalue): if x < minvalue: return minvalue elif x > maxvalue: return maxvalue else: return x def main(): global x global y global home while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: if (x+1, y) in WALLS: #print("Not possible!") pass else: x = bound(x+1,0,11) elif event.key == pygame.K_LEFT: if (x-1, y) in WALLS: #notpossible pass else: x = bound(x-1,0,11) elif event.key == pygame.K_UP: if (x,y-1) in WALLS: #notpossible pass else: y=bound(y-1,0,9) elif event.key == pygame.K_DOWN: if(x,y+1) in WALLS: pass else: y=bound(y+1,0,9) paint() pygame.display.flip() pygame.time.wait(50) if(x,y) in home: sys.exit() main()
import cv2 import numpy as np # Function that applies Sobel x or y, # then takes an absolute value and applies a threshold. def abs_sobel_thresh(img, orient, sobel_kernel, grad_thresh): # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Take the derivative in x or y given orient = 'x' or 'y' if orient == 'x': sobel = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) if orient == 'y': sobel = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) # Take the absolute value of the derivative or gradient abs_sobel = np.absolute(sobel) # Scale to 8-bit (0 - 255) then convert to type = np.uint8 scaled_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel)) # Create a mask of 1's where the scaled gradient magnitude # is > thresh_min and < thresh_max binary_output = np.zeros_like(scaled_sobel) binary_output[(scaled_sobel >= grad_thresh[0]) & (scaled_sobel <= grad_thresh[1])] = 1 # Return this mask as your binary_output image return binary_output # Function that applies Sobel x and y, # then computes the magnitude of the gradient # and applies a threshold def mag_thresh(img, sobel_kernel, mgn_thresh): # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Take the gradient in x and y separately sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) # Calculate the magnitude abs_sobel = np.sqrt(np.square(np.absolute(sobelx)) + np.square(np.absolute(sobely))) # Scale to 8-bit (0 - 255) then convert to type = np.uint8 scaled_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel)) # Create a mask of 1's where the scaled gradient magnitude # is > thresh_min and < thresh_max binary_output = np.zeros_like(scaled_sobel) binary_output[(scaled_sobel >= mgn_thresh[0]) & (scaled_sobel <= mgn_thresh[1])] = 1 # Return this mask as your binary_output image return binary_output # Function that applies Sobel x and y, # then computes the direction of the gradient # and applies a threshold. def dir_thresh(img, sobel_kernel, d_thresh): # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Take the gradient in x and y separately sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) # Take the absolute value of the x and y gradients abs_sobelx = np.absolute(sobelx) abs_sobely = np.absolute(sobely) # Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient direction = np.arctan2(abs_sobely, abs_sobelx) # Create a binary mask where direction thresholds are met binary_output = np.zeros_like(direction) binary_output[(direction > d_thresh[0]) & (direction < d_thresh[1])] = 1 # Return this mask as your binary_output image return binary_output def LUV_thresh(img, l_thresh): img = np.copy(img) height, width = img.shape[0], img.shape[1] LUV = cv2.cvtColor(img, cv2.COLOR_RGB2LUV).astype(np.float) L = LUV[:, :, 0] l_binary = np.zeros_like(L) l_binary[(L > l_thresh[0]) & (L <= l_thresh[1])] = 1 return l_binary def LAB_thresh(img, b_thresh): img = np.copy(img) height, width = img.shape[0], img.shape[1] LAB = cv2.cvtColor(img, cv2.COLOR_RGB2LAB).astype(np.float) B = LAB[:, :, 2] b_binary = np.zeros_like(B) b_binary[(B > b_thresh[0]) & (B <= b_thresh[1])] = 1 return b_binary def HLS_thresh(img, s_thresh): img = np.copy(img) height, width = img.shape[0], img.shape[1] HLS = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float) S = HLS[:, :, 2] s_binary = np.zeros_like(S) s_binary[(S > s_thresh[0]) & (S <= s_thresh[1])] = 1 return s_binary def HSV_thresh(img, v_thresh): img = np.copy(img) height, width = img.shape[0], img.shape[1] HSV = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) V = HSV[:, :, 2] v_binary = np.zeros_like(V) v_binary[(V > v_thresh[0]) & (V <= v_thresh[1])] = 1 return v_binary def R_G_thresh(img, color_thresh): img = np.copy(img) height, width = img.shape[0], img.shape[1] R = img[:, :, 0] G = img[:, :, 1] color_combined = np.zeros_like(R) r_g_condition = (R > color_thresh) & (G > color_thresh) def color_thresh_combined(img, s_thresh, l_thresh, v_thresh, b_thresh): V_binary = HSV_thresh(img, v_thresh) S_binary = HLS_thresh(img, s_thresh) L_binary = LUV_thresh(img, l_thresh) color_binary = np.zeros_like(V_binary) color_binary[(V_binary == 1) & (S_binary == 1) & (L_binary == 1)] = 1 # color_binary[(V_binary == 1) & (S_binary == 1) & (B_binary == 1) & (L_binary == 1)] = 1 return color_binary def combine_thresholds(img, s_thresh, l_thresh, v_thresh, b_thresh, gradx_thresh, grady_thresh, magn_thresh, d_thresh, ksize): img = np.copy(img) height, width = img.shape[0], img.shape[1] binary_x = abs_sobel_thresh(img, 'x', ksize, gradx_thresh) binary_y = abs_sobel_thresh(img, 'y', ksize, grady_thresh) mag_binary = mag_thresh(img, ksize, magn_thresh) dir_binary = dir_thresh(img, ksize, d_thresh) color_binary = color_thresh_combined(img, s_thresh, l_thresh, v_thresh, b_thresh) img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) binary_output = np.zeros_like(img) binary_output[((binary_x == 1) & (binary_y == 1) & (mag_binary == 1)) | (color_binary == 1) | ((mag_binary == 1) & (dir_binary == 1)) ] = 1 # apply the region of interest mask mask = np.zeros_like(binary_output) region_of_interest_vertices = np.array([[0, height - 1], [width / 2, int(0.4 * height)], [width - 1, height - 1]], dtype=np.int32) cv2.fillPoly(mask, [region_of_interest_vertices], 1) thresholded = cv2.bitwise_and(binary_output, mask) return thresholded def grayscale(img): """Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray')""" return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Or use BGR2GRAY if you read an image with cv2.imread() # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def canny(img, low_threshold=100, high_threshold=200): """Applies the Canny transform""" return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): """Applies a Gaussian Noise kernel""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. """ # defining a blank mask to start with mask = np.zeros_like(img) # defining a 3 channel or 1 channel color to fill the mask with depending on the input image if len(img.shape) > 2: channel_count = img.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 # filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(mask, vertices, ignore_mask_color) # returning the image only where mask pixels are nonzero masked_image = cv2.bitwise_and(img, mask) return masked_image def convert_hsv(image): return cv2.cvtColor(image, cv2.COLOR_RGB2HSV) def convert_hls(image): return cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
<<<<<<< HEAD my_string = "This is a string!" print(my_string.upper()) # Or more concisely print("This is a string!".lower()) ======= my_string = "This is a string!" print(my_string.upper()) # Or more concisely print("This is a string!".lower()) >>>>>>> 2ab29db80d2817a1c80482a26ac9c1190fd392c6 #COMMENT
import sys # algorithm for http://www.geeksforgeeks.org/printing-brackets-matrix-chain-multiplication-problem/ # algorithm for print best parenthesis in matrix multiplication class HoldName: def __init__(self, name): self.name = name def printParenthesis(i: int, j: int, n: int, backets, name: HoldName): if i == j: print(chr(name.name), end="") name.name += 1 return print("(", end="") printParenthesis(i, backets[i][j], n, backets, name) printParenthesis(backets[i][j]+1, j, n, backets, name) print(")", end="") def MatrixChainOrder(p, n): m = [[0 for x in range(n)] for x in range(n)] backets = [[0 for x in range(n)] for x in range(n)] for i in range(1, n): m[i][i] = 0 # L is chain length. for L in range(2, n): for i in range(1, n - L + 1): j = i + L - 1 m[i][j] = 9999999999 for k in range(i, j): # q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j] if q < m[i][j]: m[i][j] = q backets[i][j] = k hold_name = HoldName(ord('A')) print("Optimal Parenthesization: ", end="") printParenthesis(1, n-1, n, backets, hold_name) print("\nOptimal Cost is: "+str(m[1][n-1])) if __name__ == '__main__': arr = [40, 20, 30, 10, 30] MatrixChainOrder(arr, len(arr))
class Solution: def isPalindrome(self, x: int) -> bool: s = str(x) num = len(s) if num % 2 != 0: s = s[:num//2] + s[num//2 + 1:] s1 = s[:num//2] s2 = s[num//2:] s2 = s2[::-1] flag = True for i in range(len(s1)): if s1[i] != s2[i]: flag = False return flag if __name__ == '__main__': sol = Solution().isPalindrome(131) print(sol)
class Solution: def reverse(self, x: int) -> int: if x >= 2 ** 31 - 1 or x <= -2 ** 31: return 0 sol = str(x) if x >= 0: sign = str() else: sign = sol[0] sol = sol[1:] sol = sol[::-1] if int(sol) >= 2 ** 31 - 1 or int(sol) <= -2 ** 31: return 0 return int(sign + sol) if __name__ == "__main__": s = Solution() print(0xffffffff) print(s.reverse(1534236469))
# Cargamos los datos de Iris desde Scikit-learn # Graficamos # Importamos las librerias necesarias from matplotlib import pyplot as plt from sklearn.datasets import load_iris # Un aspecto sutil, es que al establecer una métrica entre frases, puede resultar que una frase es # repetida más de dos ocasiones, ejemplo “Cómo estas, cómo estas, cómo estas”. Dentro de la bolsa de palabras # lo que uno obtendrá será un vector como el de la frase “Cómo estas” pero multiplicado por 3. Es decir, un # vector de la forma (3,0,0,3,0,0,0,0,), entonces lo que se hace para evitar este tipo de anomalías es algo # usual en álgebra lineal, normalizar los vectores. Es decir, se cambia el vector origina (3,0,0,3,0,0,0,0) # dividido entre raíz de 2, lo cual hace que el vector sea igual en la norma al obtenido de (1,0,0,1,0,0,0,0). # Así esas dos frases ya pueden considerarse iguales en el espacio de frases. # # Cargamos los datos y graficamos datos = load_iris() caract = datos.data caract_names = datos.feature_names tar = datos.target # Graficamos los datos con colores distintos y tipo de marcas distintos for t, marca, c in zip(range(3), ">ox", "rgb"): plt.scatter(caract[tar == t, 0], caract[tar == t, 1], marker=marca, c=c) plt.show() # Importamos las librerias necesarias from matplotlib import pyplot as plt from sklearn.datasets import load_iris import mlpy from sklearn.cluster import KMeans #Cargamos los datos y graficamos datos=load_iris() dat=datos.data caract_names=datos.feature_names tar=datos.target #Calculamos los cluster cls, means, steps = mlpy.kmeans(dat, k=3, plus=True) #steps #Esta variable permite conocer los pasos que realizó el algoritmo para terminar #Construimos las gráficas correspondiente plt.subplot(2,1,1) fig = plt.figure(1) fig.suptitle("Ejemplo de k-medias",fontsize=15) plot1 = plt.scatter(dat[:,0], dat[:,1], c=cls, alpha=0.75) #Agregamos las Medias a las gráficas plot2 = plt.scatter(means[:,0], means[:,1],c=[1,2,3], s=128, marker='d') #plt.show() #Calculamos lo mismo mediante la librería scikit-lean KM=KMeans(init='random',n_clusters=5).fit(dat) #Extraemos las medias L=KM.cluster_centers_ #Extraemos los valores usados para los calculos Lab=KM.labels_ #Generamos las gráfica plt.subplot(2,1,2) fig1= plt.figure(1) fig.suptitle("Ejemplo de k-medias",fontsize=15) plot3= plt.scatter(dat[:,0], dat[:,1], c=Lab, alpha=0.75) #Agregamos las Medias a las gráficas plot4= plt.scatter(L[:,0], L[:,1],c=[1,2,3,4,5], s=128, marker='d') #Mostramos la gráfica con los dos calculos plt.show()
#!/usr/bin/env python3 # coding:utf-8 class Student(object): count = 0 books = [] def __init__(self,name,age): self.name = name self.age = age pass s = Student('Saotao', 25) s.books.extend(["python","java"]) print('student\'s name is: %s, age is: %d' %(s.name,s.age)) print('student book list: %s' %s.books)
class Node(): def __init__(self, value, height=None): self.value = int(value) self.parent = None self.left = None self.right = None self.height = height class binaryTree(): def __init__(self, height): self.root = Node(2**height - 1, height) self.current_node = self.root self.nodes = {2**height - 1 : self.root} self.left(self.root) self.right(self.root) def left(self, parent_node): if(parent_node.height != 1): left_node = Node(parent_node.value - 2 ** (parent_node.height - 1)) left_node.height = parent_node.height - 1 left_node.parent = parent_node parent_node.left = left_node self.nodes[left_node.value] = left_node self.left(left_node) self.right(left_node) else: return def right(self, parent_node): if(parent_node.height != 1): right_node = Node(parent_node.value - 1) right_node.height = parent_node.height - 1 right_node.parent = parent_node parent_node.right = right_node self.nodes[right_node.value] = right_node self.left(right_node) self.right(right_node) else: return def tree_solution(self, q): answer = [] for node_value in q: parent_node = self.nodes[node_value].parent if(parent_node): answer.append(parent_node.value) else: answer.append(-1) return (str(answer)[1:-1]) def solution(h, q): ''' Google foobar challenge. Problem 02. ion-flux-relabeling Solution ''' tree = binaryTree(h) tree.tree_solution(q) return tree.tree_solution(q) solution(3, [7, 3, 5, 1]) solution(5, [19, 14, 28])
#!/usr/bin/python # -*- coding: UTF-8 -*- str = input("快点输入:") print "你刚才输入的内容是:", str ''' 输出结果: 快点输入:[x*7 for x in range(13,18,2)] 你刚才输入的内容是: [91, 105, 119] '''
# -*- coding:utf-8 -*- #! /bin/env python3 __author__ = 'weekend27' # variable args def hello(greeting, *args): if (len(args)==0): print('%s!' % greeting) else: print('%s, %s!' % (greeting, ', '.join(args))) hello('Hi') # => greeting='Hi', args=() hello('Hi', 'Johnson') # => greeting='Hi', args=('Johnson') hello('Hello', 'Michael', 'Bob', 'Adam') # => greeting='Hello', args=('Michael', 'Bob', 'Adam') names = ('Lory', 'Tensa') hello('Hello', *names) # =>greeting='Hello', args=('Lory', 'Tensa')
class Avion:#Tipos de aviones existentes __numero_avion = 0#generador de id automatico del avion def __init__(self, nombre, capacidad, precio, clase): self.__ID = Avion.__numero_avion self.__nombre = nombre#Nombre del modelo self.__capacidad = int(capacidad) self.__precio = float(precio) self.__clase = clase Avion.__numero_avion += 1 @property def precio(self):#retorna el precio base del avion return self.__precio @precio.setter#modifica el precio base del avion def precio(self, precio): self.__precio = precio @property def capacidad(self):#retorna la capacidad del avion return self.__capacidad @capacidad.setter def capacidad(self, numero):#disminuye/aumenta la capacidad del avion self.__capacidad +=numero @property def clase(self): return self.__clase
from Lab2.Node import Node class LinkedList(object): head = None tail = None size = 0 def __init__(self, node: Node = None): if node is None: self.head = None self.tail = None self.size = 0 return if node.next is None: self.head = node self.tail = node self.size = 1 def insert_head(self, data): if self.head is None: self.head = Node(data) self.tail = self.head self.size += 1 return curr_node = Node(data) curr_node.next = self.head self.head = curr_node self.size += 1 def add_multi_nodes(self, node: Node): if node is None: self.empty_list() return if node.next is None: self.insert_head(node) return self.head= node self.size = 0 curr_node = node while curr_node is not None: self.size += 1 curr_node = curr_node.next self.tail = curr_node def append_list(self, list): # if added list is empty return if list.size is 0: return # if self is empty return if self.size is 0: return # combine both sizes self.size += list.size # add list to the tail of self self.tail.next = list.head self.tail = list.tail def remove_head(self): if self.head is None: self.size = 0 return # If there is 1 node, empty list if self.size is 1: self.empty_list() return self.head = self.head.next self.size -= 1 def empty_list(self): self.head = None self.tail = None self.size = 0 def copy_list(self): copy = LinkedList() copy.head = Node(self.head.item) curr_copy = copy.head curr_self = self.head # Copy every node from self to copy for i in range(1, self.size): curr_copy.next = Node() curr_copy = curr_copy.next curr_self = curr_self.next curr_copy.item = curr_self.item # Set tail and size copy.tail = curr_copy copy.size = self.size return copy def isSorted(self): # return true if list has 1 or 0 elements if self.head is None or self.size is 1: return True # Set pointers to see if list is sorted pointer1 = self.head pointer2 = pointer1.next while pointer2 is not None: if pointer1.item > pointer2.item: return False pointer1 = pointer1.next pointer2 = pointer2.next return True def find_max(self) -> int: if self.head is None: return -1 #set pointer and max variable max_num = self.head.item curr_node = self.head # find max item on the list while curr_node is not None: if curr_node.item > max_num: max_num = curr_node.item curr_node = curr_node.next return max_num def print(self): curr_node = self.head while curr_node is not None: print(curr_node.item) curr_node = curr_node.next
# For all questions, use the following class definitions class MaxHeap(object): # Constructor def __init__(self): self.tree = [] # -------------------------------------------------------------------------------------------------------------- # Problem 19 # -------------------------------------------------------------------------------------------------------------- def get_max_sibling_gap(self): max_sib_gp = -1 i = 0 while (2 * i) + 2 < len(self.tree): # TODO: Replace 123 with your answer left_sib = (2 * i) + 1 right_sib = (2 * i) + 2 sib_gp = right_sib - left_sib # TODO: Replace 123 with your answer if sib_gp > max_sib_gp: max_sib_gp = sib_gp # TODO: Replace 123 with your answer i += 1 return max_sib_gp # -------------------------------------------------------------------------------------------------------------- # Problem 20 # -------------------------------------------------------------------------------------------------------------- def is_valid(self): for i in range(1, len(self.tree)): # TODO: Replace 123 with your answer if self.tree[i] > self.tree[(i - 1)//2]: # TODO: Replace False with your answer return False return True # -------------------------------------------------------------------------------------------------------------- # Problem 21 # -------------------------------------------------------------------------------------------------------------- def is_a_node_equal_to_its_parent(self): for i in range(1, len(self.tree)): # TODO: Replace 123 with your answer if self.tree[i] == self.tree[(i - 1)//2]: # TODO: Replace False with your answer return True return False # -------------------------------------------------------------------------------------------------------------- # Problem 22 # -------------------------------------------------------------------------------------------------------------- def print_path(self, i): if len(self.tree) == 0: return while i > 0: print(self.tree[i]) i = (i-1)//2 print(self.tree[0])
def get_smallest_key_at_d(root, d): cur = root while cur is not None: if d == 0: return cur.key[0] d -= 1 cur = cur.left return 1
class HashTable: # Builds a hash table of size 'size' def __init__(self, size): self.table = [[] for i in range(size)] def hash(self, k): return k % len(self.table) # Inserts k in the appropriate bucket if k is not already there def insert(self, k): loc = self.hash(k) bucket = self.table[loc] if not k in bucket: bucket.append(k) # Removes k if it is in the table. If k is not in the table, an Exception is raised def remove(self, k): loc = self.hash(k) bucket = self.table[loc] if k in bucket: bucket.remove(k) else: raise ValueError('hashtable.remove(k): k is not in the table') def find(self, k): # Returns bucket and index where k is stored in the table # If k is not in table, return None and -1 as the bucket and index loc = self.hash(k) bucket = self.table[loc] if k in bucket: index = bucket.index(k) return bucket, index return None, -1 def __str__(self): s = "" for i in range(len(self.table)): bucket = self.table[i] s += str(i) + ": " s += str(bucket) s += "\n" return s def load_factor(self): # Problem 2 num_elements = 0 for bucket in self.table: num_elements += len(bucket) return num_elements / len(self.table) def size_longest_list(self): # Problem 3 max_size = 0 for bucket in self.table: if len(bucket) > max_size: max_size = len(bucket) return max_size def is_valid(self): # Problem 4 for i in range(len(self.table)): i = self.table.index(self.table[i]) for key in self.table[i]: if not key % len(self.table) == i: return False return True def insert_asc(self, k): # Problem 5 loc = self.hash(k) bucket = self.table[loc] if len(bucket) == 0: bucket.append(k) return for i in range(len(bucket)): if k == bucket[i]: return if k < bucket[i]: bucket.insert(i, k) return bucket.append(k) def largest_key(self): # Problem 6 max_key = float("-inf") for bucket in self.table: if len(bucket) > 0 and max(bucket) > max_key: max_key = max(bucket) return max_key def resize(self, size): # Problem 7 new_hash = HashTable(size) new_hash.table = [[] for i in range(size)] for bucket in self.table: for key in bucket: new_hash.insert_asc(key) self.table = new_hash.table def contains(self, k): loc = self.hash(k) bucket = self.table[loc] return k in bucket def is_equal(self, hash_table): # Problem 8 for bucket in self.table: for key in bucket: if not hash_table.contains(key): return False return True table = HashTable(7) table.insert(3) table.insert(17) table.insert(5) table.insert(6) table.insert_asc(10) table.insert_asc(19) table.insert_asc(12) table.insert_asc(4) table.insert_asc(30) table2 = HashTable(3) table2.insert(3) table2.insert(17) table2.insert(5) table2.insert(6) table2.insert_asc(10) table2.insert_asc(19) table2.insert_asc(12) table2.insert_asc(4) table2.insert_asc(30) table.resize(5) print(table) print(table.is_equal(table2))
# For all questions, use the following class definitions import math class BinaryTreeNode: def __init__(self, item=0, left=None, right=None): self.item = item self.left = left self.right = right class BinarySearchTree: def __init__(self): self.root = None def height(self): return self._height(self.root) # -------------------------------------------------------------------------------------------------------------- # Problem 7 # -------------------------------------------------------------------------------------------------------------- def _height(self, node): if node is None: return -1 return max(self._height(node.left), self._height(node.right)) + 1 def num_nodes_at_depth(self, d): return self._num_nodes_at_depth(d, self.root) # -------------------------------------------------------------------------------------------------------------- # Problem 8 # -------------------------------------------------------------------------------------------------------------- def _num_nodes_at_depth(self, d, node): if node is None: return 0 if d == 0: return 1 return self._num_nodes_at_depth(d - 1, node.left) + self._num_nodes_at_depth(d - 1, node.right) def min_val(self): return self._min_val(self.root) # -------------------------------------------------------------------------------------------------------------- # Problem 9 # -------------------------------------------------------------------------------------------------------------- def _min_val(self, node): if node is None: return math.inf cur = node while cur.left is not None: cur = cur.left return cur.item def max_val_at_depth(self, d): return self._max_val_at_depth (d, self.root) # -------------------------------------------------------------------------------------------------------------- # Problem 10 # -------------------------------------------------------------------------------------------------------------- def _max_val_at_depth(self, d, node): if node is None or d < 0: return -math.inf if d == 0: return node.item return max(self._max_val_at_depth(d - 1, node.left), self._max_val_at_depth(d - 1, node.right))
class Section1: # Given a non-negative int n, return the number # of digits in n that are less than or equal # to 5 - Use recursion - no loops. # Example1: count(285) -> 2 # Example2: count(565891) -> 3 @staticmethod def count(n: int) -> int: if n <= 5: return 1 if n < 10: return 0 last_digit = n % 10 rest_of_digits = n // 10 if last_digit <= 5: return 1 + Section1.count(rest_of_digits) return Section1.count(rest_of_digits) def main(): test_result = Section1.count(1273) print("test_result = ", test_result) if __name__ == "__main__": main()
################################################################################ # Input Capture Unit # # Created by VIPER Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import pwm import icu import streams #create the serial port using default parameters streams.serial() #define a pin where a button is connected, you can use the Nucleo button pin as input or change it with any other digital pin available buttonPin=BTN0 #this is the pin where the button is connected, for the various supported board VIPER automatically translates it on the board button specific pins #define a pin where the ICU is used. D2 works with Arduino footprint boards while on Particle boards D0 can be used captPin=D2.ICU #On Arduino like boards #captPin=D0.ICU #On Particle boards #define the Pin where the PWM is controlled. D13 works with Arduino footprint boards where the LED1 is also connected #while on Particle boards A4 can be used pwmPin=D13.PWM #On Arduino like boards pwmPin=A4.PWM #On Particle boards #set the pin as input with PullUp, the button will be connected to ground pinMode(buttonPin, INPUT_PULLUP) #define a function for printing capture results on the serial port def print_results(y): print("Time ON is:", y[0],"micros") print("Time OFF is:",y[1],"micros") print("Period is:", y[0]+y[1], "micros") print() #define a global variable for PWM duty cycle and turn on the PWM on board LED (Pin 13) duty=10 pwm.write(pwmPin,100, duty,MICROS) #pwm.write needs (pn, period, duty, time_unit) #define the function to be called for changing the PWM duty when the button is pressed def pwm_control(): global duty duty= duty+10 pwm.write(pwmPin, 100, duty,MICROS) if duty>=100: duty=0 print("Duty:", duty, "millis") #Attach an interrupt on the button pin waiting for signal going from high to low when the button is pressed. #The interrupt if triggered call the pwm_control function onPinFall(buttonPin, pwm_control) while True: #define an icu capture on pin 2 to be triggered when the pin rise. #this routine acquires 10 steps (HIGH or LOW states) or terminates after 50000 micros, the time unit is MICROS #this is a blocking function, icu.capture can be also instanced as non blocking using call-back, refer to the doc for more info x = icu.capture(captPin,HIGH,10,50000,MICROS) print("alive") # x is a list of steps lengths in microseconds, pass it to the printing function for showing on the serial console print_results(x) sleep(1000)
import intervals as I def fun(x): return x**2-x stanga = raw_input('Alegeti capatul din stanga al intervalului: ') st=float(stanga) dreapta = raw_input('Alegeti capatul din dreapta al intervalului: ') dr=float(dreapta) interval=I.closed(st, dr) print interval i=1 rezultate=[] while i<=6: xzero=(st+dr)/2 if(fun(xzero)*fun(st)<0): dr=xzero else: st=xzero i+=1 rezultate.append("%.4f" % xzero) print rezultate
def fibonacci(n): if n < 2: return n return fibonacci(n-2) + fibonacci(n-1) n = int(input()) print(fibonacci(n))
#!python class MinHeap(object): """A MinHeap is an unordered collection with access to its minimum item, and provides efficient methods for insertion and removal of its minimum.""" def __init__(self): """Initialize this min heap with an empty list of items""" self.items = [] def __repr__(self): """Return a string representation of this min heap""" return 'MinHeap({})'.format(self.items) def __len__(self): return self.size() def size(self): """Return the number of items in the heap""" return len(self.items) def peek(self): return self.get_min() def get_min(self): """Return the minimum item at the root of the heap""" if self.size() < 1: raise ValueError('Heap is empty and has no minimum item') return self.items[0] def pop(self): return self.remove_min() def remove_min(self): """Remove and return the minimum item at the root of the heap""" if self.size() < 1: raise ValueError('Heap is empty and has no minimum item') if self.size() == 1: # Remove and return the only item return self.items.pop() assert self.size() > 1 min_item = self.items[0] # Move the last item to the root and bubble down to the leaves last_item = self.items.pop() self.items[0] = last_item if self.size() > 1: self._bubble_down(0) return min_item def push_pop(self, item): return self.replace_min(item) def replace_min(self, item): """Remove and return the minimum and insert a new item into the heap""" if self.size() < 1: raise ValueError('Heap is empty and has no minimum item') min_item = self.items[0] # Replace the root and bubble down to the leaves self.items[0] = item if self.size() > 1: self._bubble_down(0) return min_item def push(self, item): self.insert(item) def insert(self, item): """Insert an item into the heap""" # Insert the item at the end and bubble up to the root self.items.append(item) if self.size() > 1: self._bubble_up(self._last_index()) def _bubble_up(self, index): """Ensure the heap-ordering property is true above the given index, swapping out of order items, or until the root node is reached""" if index == 0: return # This index is the root node if not (0 <= index <= self._last_index()): raise IndexError('Invalid index: {}'.format(index)) item = self.items[index] parent_index = self._parent_index(index) parent_item = self.items[parent_index] if item < parent_item: self.items[parent_index] = item self.items[index] = parent_item self._bubble_up(parent_index) def _bubble_down(self, index): """Ensure the heap-ordering property is true below the given index, swapping out of order items, or until a leaf node is reached""" if not (0 <= index <= self._last_index()): raise IndexError('Invalid index: {}'.format(index)) left_index = self._left_child_index(index) right_index = self._right_child_index(index) if left_index > self._last_index(): return # This index is a leaf node (does not have any children) item = self.items[index] left_child_index = self._left_child_index(index) right_child_index = self._right_child_index(index) if left_child_index < len(self.items): min_child_index = None if right_child_index < len(self.items): left_child_item = self.items[left_child_index] right_child_item = self.items[right_child_index] min_child_index = left_child_index if left_child_item < right_child_item else right_child_index else: min_child_index = left_child_index min_child_item = self.items[min_child_index] if item > min_child_item: self.items[index] = min_child_item self.items[min_child_index] = item self._bubble_down(min_child_index) def _last_index(self): """Return the last valid index in the underlying array of items""" return len(self.items) - 1 def _parent_index(self, index): """Return the parent index of the item at the given index""" if index < 1: raise IndexError('Heap index {} has no parent index'.format(index)) return (index - 1) >> 1 def _left_child_index(self, index): """Return the left child index of the item at the given index""" return (index << 1) + 1 def _right_child_index(self, index): """Return the right child index of the item at the given index""" return (index << 1) + 2
class Tree23: def __init__(self): self.root = None def insert(self, item): if self.root == None: self.root = Node23(None, item, None) else: new = self.root.insert(item) if new != None: self.root = new def searchFor(self, item): if self.root == None: return False else: return self.root.searchFor(item) def getString(self): if self.root == None: return "[empty]" else: grid = self.root.makeDiagram() return "\n".join(grid)+"\n" def getList(self): if self.root == None: return [] else: out = [] self.root.addContentsToList(out) return out class Node23: def __init__(self, leftIn, val, rightIn): self.a = val self.b = None self.leftSub = leftIn self.midSub = None self.rightSub = rightIn def insert(self, item): if self.leftSub == None: # if this node is a leaf if self.b == None: if item < self.a: self.b = self.a self.a = item else: self.b = item else: if item < self.a: return Node23( Node23(None, item, None), self.a, Node23(None, self.b, None)) elif item < self.b: return Node23( Node23(None, self.a, None), item, Node23(None, self.b, None)) else: return Node23( Node23(None, self.a, None), self.b, Node23(None, item, None)) else: # if this node has children if item < self.a: # if we want to insert the item into the left subtree new = self.leftSub.insert(item) if new != None: # if the operation ejected a node if self.b == None: # if we don't have a 'b' node and can just move 'a' over self.b = self.a self.a = new.a self.leftSub = new.leftSub self.midSub = new.rightSub else: # if we have a 'b', we must eject a new node headed by 'a' return Node23(new, self.a, Node23(self.midSub, self.b, self.rightSub)) else: # if item is to the right of 'a' if self.b == None: # if 'b' is none we can just insert item to the right subtree new = self.rightSub.insert(item) if new != None: # we don't have to eject anything because we have room self.b = new.a self.midSub = new.leftSub self.rightSub = new.rightSub else: # b has a value so we have a choice between mid and right if item < self.b: # we insert the node in the middle new = self.midSub.insert(item) if new != None: return Node23( Node23(self.leftSub, self.a, new.leftSub), new.a, Node23(new.rightSub, self.b, self.rightSub)) else: new = self.rightSub.insert(item) if new != None: return Node23( Node23(self.leftSub, self.a, self.midSub), self.b, new) def searchFor(self, item): if self.a == item or self.b == item: return True elif item < self.a: if self.leftSub == None: return False else: return self.leftSub.searchFor(Item) elif self.b == None or item > self.b: if self.rightSub == None: return False else: return self.rightSub.searchFor(item) else: if self.midSub == None: return False else: return self.midSub.searchFor(item) def makeDiagram(self): leftGrid = [""] midGrid = [""] rightGrid = [""] aStr = "" bStr = "" if self.leftSub: leftGrid = self.leftSub.makeDiagram() if self.midSub: midGrid = self.midSub.makeDiagram() if self.rightSub: rightGrid = self.rightSub.makeDiagram() if self.a != None: aStr = str(self.a) if self.b != None: bStr = "="+str(self.b) out = [""] for i in range(0, len(leftGrid)): while len(out)<=i+1: out.append(" "*len(out[0])) out[i+1] += leftGrid[i] out[0] += " "*len(leftGrid[0]) out[0]+=aStr for i in range(0, len(out)): out[i]+=" "*(len(out[0])-len(out[i])) for i in range(0, len(midGrid)): while len(out)<=i+1: out.append("#"*len(out[0])) out[i+1] += midGrid[i] out[0] += "="*len(midGrid[0]) out[0]+=bStr for i in range(0, len(out)): out[i]+=" "*(len(out[0])-len(out[i])) for i in range(0, len(rightGrid)): while len(out)<=i+1: out.append(" "*len(out[0])) out[i+1] += rightGrid[i] out[0] += " "*len(rightGrid[0]) return out def addContentsToList(self, out): if self.leftSub != None: self.leftSub.addContentsToList(out) if self.a != None: out.append(self.a) if self.midSub != None: self.midSub.addContentsToList(out) if self.b != None: out.append(self.b) if self.rightSub != None: self.rightSub.addContentsToList(out)
from task.utils import * from task.exceptions import WrongCityNameError import requests from textwrap import indent COUNTRY_CITY_URL = "https://public.opendatasoft.com/api/records/1.0/search/?dataset=worldcitiespop&q={}&facet=country" COUNTRY_CURRENCY_URL = 'https://restcountries.eu/rest/v2/name/{}?fullText=true' def pretty_print(data, city): """ Pretty print of formatted data :param data: dict of params to print :param city: name of printed city """ print(f"=> {city.capitalize()}") print(f"=>{'-' * 10}") for key, value in data.items(): print(indent(f"{key}: {value}", '=>')) print(f"=>{'-' * 10}") def find_country_info(city_name): """ Finds code of country in which searched city is located :param city_name: name of the searching city :return: dict of insights about city :raise WrongCityNameError if city was not found """ response = requests.get(url=COUNTRY_CITY_URL.format(city_name)) try: data = response.json()['records'][0] return { 'CountryCode': data['fields']['country'].upper() } except Exception: raise WrongCityNameError("Invalid City Name") def find_currency_country(data): """ Finds country name & currency by country code :param data: dict of insights about city :return: tuple of country name, country currency """ country_code = data['CountryCode'] response = requests.get(url=COUNTRY_CURRENCY_URL.format(country_code)) data = response.json()[0] return data['name'], data['currencies'][0]['code'], data['population'] def main(): """ Gets user's input(city name) and returns list of country insights """ args = parse_arguments() if args.file is None: cities = " ".join(args.cities).lower().split(", ") else: cities = read_file(args.file) for city in cities: try: data = find_country_info(city) data['Country'], data['Currency'], data['Population'] = find_currency_country(data) pretty_print(data, city) except Exception as exception: print(f"=>{'-' * 10}") print(exception) print(f"=>{'-' * 10}") if __name__ == '__main__': main()
#coding: utf-8 #codes f=open("test.txt","r") f2=open("test2.txt","w") # print(f.read()) for line in f: if "让我掉下眼泪的" in line: line=line.replace("让我掉下眼泪的","让我们彼此掉下眼泪的") f2.write(line) else: f2.write(line) f.close() f2.close()
animals = ['cat', 'dog', 'monkey'] for animal in animals: print(animal) # Prints "cat", "dog", "monkey", each on its own line. animals = ['cat', 'dog', 'monkey'] for idx, animal in enumerate(animals): print('#%d: %s' % (idx + 1, animal)) # Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line nums = list(range(1,5)) # range is a built-in function that creates a list of integers print(nums) # Prints "[0, 1, 2, 3, 4]" print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]" print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]" print(nums[:2]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]" print(nums[:]) # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]" print(nums[:-1]) # Slice indices can be negative; prints ["0, 1, 2, 3]" nums[2:4] = [8, 9] # Assign a new sublist to a slice print(nums) # Prints "[0, 1, 8, 9, 4]" #循环遍历 #for-in 可以用来遍历数组与字典: words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) # 使用数组访问操作符,能够迅速地生成数组的副本 for w in words[:]: if len(w) > 6: words.insert(0, w) # words -> ['defenestrate', 'cat', 'window', 'defenestrate'] #如果我们希望使用数字序列进行遍历,可以使用 Python 内置的 range 函数: a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) #Python 字符串支持分片、模板字符串等常见操作: var1 = 'Hello World!' var2 = "Python Programming" print("var1[0]: ", var1[0]) print("var2[1:5]: ", var2[1:5]) # var1[0]: H # var2[1:5]: ytho print("My name is %s and weight is %d kg!" % ('Zara', 21)) # My name is Zara and weight is 21 kg! var1[0:4] len(str) string.replace("-", " ") ",".join(list) "hi {0}".format('j') str.find(",") str.index(",") # same, but raises IndexError str.count(",") str.split(",") str.lower() str.upper() str.title() str.lstrip() str.rstrip() str.strip() str.islower() # 移除所有的特殊字符 re.sub('[^A-Za-z0-9]+', '', mystring) #如果需要判断是否包含某个子字符串,或者搜索某个字符串的下标: # in 操作符可以判断字符串 if "blah" not in somestring: print('suc') # find 可以搜索下标 s = "This be a string" if s.find("is") == -1: print("No 'is' here!") else: print("Found 'is' in the string.")
# -*- coding: utf-8 -*- WORDLIST_FILENAME = 'words-utf8.txt' HEBREW_WORDS = [w.split()[0] for w in file(WORDLIST_FILENAME, 'r').readlines()] KALPI_WORDS = ['אמת', 'זך', 'ףץ', 'ל', "נז", "ג", "יז", "י", "יץ", "רק", "מחל", "קץ", "שס", "קנ", "ף", "ני", "ודעם", "פה", "כ", "זץ", "נץ", "מרצ", "ע", "טב", "ז"] def initial_form(w): w = w.replace('ף', 'פ') w = w.replace('ץ', 'צ') w = w.replace('ן', 'נ') w = w.replace('ם', 'מ') w = w.replace('ך', 'כ') return w KALPI_INITIAL = [initial_form(w) for w in KALPI_WORDS] def process(): to_process = [('', w) for w in HEBREW_WORDS] done = [] while to_process: current_process = to_process to_process = [] for beginning, remaining in current_process: for kalpi in KALPI_WORDS: if remaining == kalpi: done.append(beginning + remaining) elif remaining.startswith(kalpi): to_process.append((beginning + kalpi, remaining[len(kalpi):])) return sorted(set(done)) def process_allow_finals(): to_process = [('', w) for w in HEBREW_WORDS] done = [] while to_process: current_process = to_process to_process = [] for beginning, remaining in current_process: for kalpi in KALPI_INITIAL: if initial_form(remaining) == kalpi: done.append(beginning + remaining) elif initial_form(remaining).startswith(kalpi): to_process.append((beginning + remaining[:len(kalpi)], remaining[len(kalpi):])) return sorted(set(done))
from itertools import combinations from Warehouse import Warehouse, is_Subset from typing import List from solution1 import findCheapest_simple # combine a list of warehouse into one single big 'warehouse' def combineSuppliers(suppliers: List[Warehouse]) -> (dict, int): ret = {} # and compute their total shipping cost (assume shipping cost is independent on item quantity) total_cost = 0 for supplier in suppliers: total_cost += supplier.cost for e, v in supplier.inventory.items(): if e not in ret: ret[e] = v else: ret[e] += v return ret, total_cost def add_cost_index(supply_list: List[Warehouse]) -> None: for i in range(len(supply_list)): supply_list[i].cost = i+1 def findCheapest_complex(order: dict, supply: List[Warehouse]): min_cost = float('inf') min_cost_list = [] add_cost_index(supply) for i in range(1, len(supply)+1): # use python build in function to compute every combination from 1 to n of the supplier warehouse for combined in list(combinations(supply, i)): single_combined, cost = combineSuppliers(combined) if is_Subset(order, single_combined) and cost < min_cost: min_cost = cost min_cost_list = combined return findCheapest_simple(order, min_cost_list)
startRange = int(input("Enter the starting range of input")) endRange = int(input("Enter the ending range of input")) lists = [] for i in range(startRange,endRange+1) : count = 0; if i != 1: for j in range(2,i) : if i % j == 0 : count = 1 break; if count == 0 : lists.append(i) for s in lists: print(s) Enter the starting range of input1 Enter the ending range of input20 2 3 5 7 11 13 17 19 ======================================================= num =int(input("enter the numberto check whether it is prime or not : ")) lists = [] count = 0 for i in range(2,num): if num % i == 0: count = 1 break; if count == 0 : print(" {} is a prime number ".format(num)) else : print("{} is not a prime number ".format(num)) enter the numberto check whether it is prime or not : 3 3 is a prime number =======================================================
num=int(input("Enter the number to whelter it is armstrong number or not")) temp=num count = 0 output=0 lists=[] while temp > 0 : count =count + 1 lists.append(temp%10) temp=int(temp/10) for i in lists: output = int(output + pow(i,count)) #print(output) if(num == output): print('{} is a armstrong number'.format(num)) else: print('{} is not a armstrong number'.format(num)) ======================================================== num=input("Enter the number to whelter it is armstrong number or not") temp=int(num) count = len(num) print(count) output=0 lists=[] while temp > 0 : lists.append(temp%10) temp=int(temp/10) for i in lists: output = int(output + pow(i,count)) # print(output) if(int(num) == output): print('{} is a armstrong number'.format(num)) else: print('{} is not a armstrong number'.format(num)) output: Enter the number to whelter it is armstrong number or not153 3 153 is a armstrong number
principle = int(input("Enter the total amount")) rate = int(input("Enter the interest")) n = int(input("Enter the total number of years")) output = (principle * rate * n)/100 print(int(output))
people = { 'geetha': ' used to tell lot of lies ', 'deepak':' dont know what to say ', 'arthi':" used to make fun out of others" } for name,story in people.items() : print('{} : {}'.format(name,story)) ====================================== def display_facts(facts): for fact in facts: print('{}: {}'.format(fact, facts[fact])) print() facts = { 'Jason': 'Can fly an airplane.', 'Jeff': 'Is afraid of clowns.', 'David': 'Plays the piano.' } display_facts(facts) facts['Jeff'] = 'Is afraid of heights.' facts['Jill'] = 'Can hula dance.' display_facts(facts) ============================================== airport = [ ('chennai','ch001'),('karnataka','kr001'),('kerala','kr001') ] for (airport_name,airport_code) in airport: print(' the code for {} is {} '.format(airport_name,airport_code)) ============================================== airports = [ ("O’Hare International Airport", 'ORD'), ('Los Angeles International Airport', 'LAX'), ('Dallas/Fort Worth International Airport', 'DFW'), ('Denver International Airport', 'DEN') ] for (airport, code) in airports: print('The code for {} is {}.'.format(airport, code)) ================================================= with open("C:/Users/Mohan/sample/test.txt") as testing: #length = len(testing_content) le = 0 for i in testing: le = le + 1 print(le, ".",i.rstrip()) ================================================= unsorted_file_name = 'C:/Users/Mohan/sample/test.txt' sorted_file_name = 'C:/Users/Mohan/sample/animals-sorted.txt' animals = [] try: with open(unsorted_file_name) as animals_file: for line in animals_file: animals.append(line) animals.sort() except: print('Could not open {}.'.format(unsorted_file_name)) try: with open(sorted_file_name, 'w') as animals_sorted_file: for animal in animals: animals_sorted_file.write(animal) except: print('Could not open {}.'.format(sorted_file_name)) for i in animals: print(i) ===================================================
class Account: def __init__(self,owner,deposit): self.owner=owner self.deposit=deposit def __str__(self): return f'Account owner: {self.owner}\nAccount balance: ${self.deposit}' def depositt(self,amount_added): self.deposit = self.deposit+amount_added print("Deposit Accepted") def withdraw(self,withdraww): if self.deposit >= withdraww: self.deposit = self.deposit-withdraww print("Withdrawal Accepted") else: print("Funds Unavailable!") acct1 = Account('Jose',100) print(acct1) print(acct1.owner) print(acct1.deposit) acct1.depositt(50) acct1.withdraw(75) acct1.withdraw(500)
# -*- encoding:utf8 -*- # http://www.pythonchallenge.com/pc/def/equality.html # http://www.pythonchallenge.com/pc/def/linkedlist.php # http://wiki.pythonchallenge.com/index.php?title=Level3:Main_Page import re import requests import BeautifulSoup url = 'http://www.pythonchallenge.com/pc/def/equality.html' html = requests.get(url) soup = BeautifulSoup.BeautifulSoup(html.content) book = soup.findAll(text=lambda text:isinstance(text, BeautifulSoup.Comment)) result = ",".join(re.findall("[a-z]+[A-Z]{3}[a-z][A-Z]{3}[a-z]+", book[0])) print(result)
"""Helper functions used across multiple scripts.""" __author__ = "Kris Jordan <kris@cs.unc.edu>" from datetime import datetime def date_prefix(suffix: str) -> str: """Generate a date prefixed string given a suffix. Args: suffix: Will follow the date and a dash. Returns: A str in the format of "YY.MM.DD-HH.MM-{suffix}" """ now = datetime.now() prefix = f"{str(now.year)[2:]}.{now.month:02}.{now.day:02}-{now.hour:02}.{now.minute:02}" return f"{prefix}-{suffix}"
#!/usr/bin/env python3 # hamming — generates bits with the hamming encoding # Usage: # py hamming.py -number N # N — number of bits in an encoded sequence, default — random from 11 to 20 import random import argparse import math def get_print_form(list: list) -> str: for index in range(len(list)): list[index] = str(list[index]) return ''.join(list) parser = argparse.ArgumentParser(description='Generates bits with the hamming encoding') parser.add_argument('-number', type=int, default=-1, help='Number of bits in an encoded sequence, default — random from 11 to 20.') args = parser.parse_args() if args.number <= 0: # to prevent from a negative input N = random.randint(11, 20) else: N = args.number bits = [random.randint(0, 1) for _ in range(N)] # Find positions for parity bits and insert placeholders there positions = [2 ** x - 1 for x in range(math.ceil(math.log2(N)))] # positions — powers of 2 minus 1 (indexes start from 0) for index in range(len(positions)): bits.insert(positions[index], 'placeholder') # Get bits required to calculate the parity bits calculation_dict = {str(position): [] for position in positions} keys = list(calculation_dict.keys()) for position_index in range(1, len(positions) + 1): for bit_index in range(1, len(bits) + 1): if isinstance(bits[bit_index-1], str): continue if len(bin(bit_index)) >= (position_index + 2) and bin(bit_index)[-position_index] == '1': calculation_dict[keys[position_index - 1]].append(bits[bit_index - 1]) # Calculate parity bits and append them parity_bits = [] for key in keys: parity_itter = calculation_dict[key][0] for index in range(1, len(calculation_dict[key])): parity_itter = parity_itter ^ calculation_dict[key][index] parity_bits.append(parity_itter) for index in range(len(positions)): del bits[positions[index]] bits.insert(positions[index], parity_bits[index]) print(f"Code: {get_print_form(bits)}, parity bits: {get_print_form(parity_bits)}")
#1) Write a Python script to merge two Python dictionaries Colors1 = {"Pink":"Purple", "Blue":"Violet", "Black":"White"} Colors2 = {"Orange":"Yellow", "Red":"maroon", "Brown":"Green"} Colors1.update(Colors2) print(Colors1) #2) Write a Python program to remove a key from a dictionary Colors1 = {"Pink":"Purple", "Blue":"Violet", "Black":"White"} del Colors1["Pink"] print(Colors1) #3) Write a Python program to map two lists into a dictionary num = ["1", "2", "3"] Colors = ["Pink", "Blue", "Black"] a = dict(zip(num, Colors)) print(a) #4) Write a Python program to find the length of a set set={"Hello", "Hey", "Hola", "Hi", "Heya"} print(len(set)) #5) Write a Python program to remove the intersection of a 2nd set from the 1st set set1 = {"100", "200", "300", "400", "600"} set2 = {"700", "850", "200", "100", "900"} print(set1) print(set2) set1.difference_update(set2) print(set1)
#Day 2 : String Practice #How to print a value? print("30 days 30 hour challenge") print('30 days 30 hour challenge') #Assigning String to Variable: Hours = "thirty" print(Hours) #Indexing using String: Days = "Thirty days" print(Days[3]) #How to print the particular character from certain text? Challenge = "I will win" print(Challenge[5:10]) #Print the length of Character: Challenge = "I will win" print(len(Challenge)) #Convert String into lower character; Challenge = "I will win" print(Challenge.lower()) #String Concatenation – Joining two strings a = "30 Days" b = "30 hours" c = a + b print(c) #Adding space during concatenation a = "30 Days" b = "30 hours" c = a + " " + b print(c) #casefold() - Usage text = "Thirty days and Thirty hours" x = text.casefold() print(x) #capitalize text = "DON’T TROUBLE TROUBLE UNTIL TROUBLE TROUBLES YOU" x = text.capitalize() print(x) #find text = "DON’T TROUBLE TROUBLE UNTIL TROUBLE TROUBLES YOU" x=text.find("TROUBLE") print(x) #isalpha text= "DON’T TROUBLE TROUBLE UNTIL TROUBLE TROUBLES YOU" x=text.isalpha() print(x) #isalnum() text="DON’T TROUBLE TROUBLE UNTIL TROUBLE TROUBLES YOU" x=text.isalnum() print(x) #Output: 30 days 30 hour challenge 30 days 30 hour challenge thirty r l win 10 i will win 30 Days30 hours 30 Days 30 hours thirty days and thirty hours Don’t trouble trouble until trouble troubles you 6 False False
import time import sys def print_pause(message_to_print): print(message_to_print) sys.stdout.flush() time.sleep(3) def valid_input(prompt,option1, option2): while True: response = input(prompt).lower() if option1 in response: break elif option2 in response: break else: print_pause("Sorry, I don't understand.") return response def intro(): print_pause("Hello! I am Peteboxes, the ThaiHouse Bot") print_pause("We have the best padthai in town, and you can choose from two choices of meat.") print_pause("The first is organic grass fed beef.") print_pause("The second is cage free chicken") def get_order(): response = valid_input("Would you like beef or chicken in your padthai?\n", "beef", "chicken") if "beef" in response: print_pause("Beef it is!") elif "chicken" in response: print_pause("Chickens it is!") print_pause("Your order will be ready shortly") order_again() def order_again(): response = valid_input("Would you like another padthai? Please say yes or no.\n", "yes", "no") if "no" in response: print_pause("OK, goodbye!") elif "yes" in response: print_pause("Very good, I'm Happy to take your order.") get_order() def order_food(): intro() get_order() order_food()
''' Insertion Sort * like a card game * pick an element and insert it into sorted sequence ''' def insertionSort(arr): # traverse through 1 to len(arr) for idx in range(1, len(arr)): current_val = arr[idx] # move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position position = idx while position > 0 and arr[position-1] > current_val: arr[position] = arr[position-1] position -= 1 arr[position] = current_val ''' avg case: O(n^2) worst case: O(n^2) best case: O(n) - in case for an already sorted list * shifting vs. exchanging: shifting(1/3 of processing work) '''
''' # Tree * essential data structure for storing hierarchial data with a directed flow * similar to linked lists and graphs, trees are composed of nodes which hold data. * Nodes store references to zero or more other tree nodes * `root`, `parent`, `child`, `sibling` node * a node with no children: `leaf` node * each node has at most one parent * each time we move from a parent to a child, `level` down * depending on the orientation, `height` or `depth # Binary Search Tree * type of tree where each parent can have no more than two children - left, right child * left child must be lesser than their parent, right child greater ''' class TreeNode: def __init__(self, value): self.value = value # data self.children = [] # references to other nodes def add_child(self, child_node): # creates parent-child relationship print("Adding " + child_node.value) self.children.append(child_node) def remove_child(self, child_node): # removes parent-child relationship print("Removing " + child_node.value + " from " + self.value) self.children = [child for child in self.children if child is not child_node] def traverse(self): # moves through each node referenced from self downwards nodes_to_visit = [self] while len(nodes_to_visit) > 0: current_node = nodes_to_visit.pop() print(current_node.value) nodes_to_visit += current_node.children
from math import * #these work even without math import my_num = 9 print(str(my_num) + " my favourite no.") print(abs(my_num*(-1))) print(max(1,2,3,4,5)) #same for min print(pow(9,3)) #float o/p print(round(2.3456)) #these require math import print(floor(3.7)) print(ceil(3.7)) print(sqrt(3.7))
name = input("Enter your name: ") #by default, user input is considered as a string age = input("Enter your age: ") print("Hello " + name + ", you are " + age + " years old!") num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = float(num1) + float(num2) print("Addition is " + str(result))
from datetime import date def date_from_isoformat(isostring): """ Converts an isostring to date :param isostring: The date-string :return: The date created from string """ parts = isostring.split("-") return date(int(parts[0]), int(parts[1]), int(parts[2])) def is_between(check, start, end): """ Checks whether a date is between two other dates. :param check: :type check: date :param start: :type start: date :param end: :type end: date :return: True or False """ if check < start or end < check: return False else: return True
# small_decimal=range(0,10) # print(small_decimal) # my_range=small_decimal[::2] # print(my_range) # print(my_range.index(4)) deciam=range(0,100) my_range=deciam[3:40:3] for i in my_range: print(i) print('='*50) for i in range(3,40,3): print(i) print(my_range==range( 3,40,3))
string="1234567890" # for i in string: # print(i) my_iterator=iter(string) print(my_iterator) for i in range(1,11): print(next(my_iterator)) # for i in my_iterator: # print(next(i))
shopping_list=['milk','pasta','eggs','spam','bread','rice'] item_to_find="spam" found_at=None for index in range(len(shopping_list)): if shopping_list[index]==item_to_find: found_at=index break if found_at is not None: print(f"Item found at position {found_at}") else: print(f"{item_to_find} not found ")
shopping_list=['milk','pasta','eggs','spam','bread','rice'] item_to_find="spam" found_at=None if item_to_find in shopping_list: found_at=shopping_list.index(item_to_find) if found_at is not None: print(f"item found at position {found_at}") else: print(f"{item_to_find} not found ")
shopping_list=['milk','pasta','eggs','spam','bread','rice'] item_to_find="pasta" found_at=None for index in range(len(shopping_list)): if shopping_list[index]==item_to_find: found_at=index print(f"Item found at position {index}")
def uses_only(word, characters): for letter in word: if letter not in characters: return False return True file = open("words.txt") num = 0 for line in file: word = line.strip() if uses_only(word, 'a c e f h l o') == True: print(word) num = num + 1 print(num) # Yes, there are about 188 words meet the requirements and we can select these words to make a sentence
day=1 month=1 year=1900 week=1 sum=0 sum1=0 month_tab={1:31,3:31,5:31,7:31,8:31,10:31,12:31,9:30,4:30,6:30,11:30} months=range(1,13) del months[1] while year<=2000: if week>7: week=week-7 if month==2: if (year==2000) or (year%100!=0 and year%4==0): if day>29: day=day-29 month=month+1 else: if day>28: day=day-28 month=month+1 if month in months: if day >month_tab.get(month): day=day-month_tab.get(month) month=month+1 if month>=13: month=month-12 year=year+1 if week==7 and day==1 and year>=1901 and year<=2000: sum=sum+1 day=day+1 week=week+1 print sum
from random import random, seed, randint, randrange, choice,sample from datetime import datetime #1. random shnowng rand numbers between 0 < x < 1 for _ in range(5): print(random(), end= ' ') #2. seeding showing the generated rand numbers doe not change if the see number its the same seed(20) print ("first Number ", randint(25,50)) seed(30) print ("Second Number ", randint(25,50)) seed(20) print ("Third Number ",randint(25,50)) print('------------------------randrange with seed and step-----------------------------') #3. randrange with seed and step over of 2 seed(10) for _ in range(10): print(randrange(0,5,2), end=' ') print('\n') seed(10) for _ in range(10): print(randrange(0,5,2), end=' ') print('\n') print('------------------------SAMPLE AND CHOICE-----------------------------') #4. DISADVANTAGE OF THE ABOVE INVOCATIONS IS THAT THEY RETURN REPETED SAMPLES # WHAT IF YOU WANT TO RETURN A UNQIUE SAMPLE EVERYTIME THERE IS A DRAW LIKE A LOOTTTTTOOOO WE WOULDNT WANT THE DRAWN ELEMENT TO BE REPEATED IN A SINGLE OUTPUT #choice , and sample draw_list = [1,2,3,4,5,6,7,8,9,10] print(choice(draw_list)) #select a random element from the list print(sample(draw_list,5)) #sample or draw five items from the list print(sample(draw_list,8)) #draw 8 items from the list
a=int(input("Masukkan Angka A : ")) b=int(input("Masukkan Angka B : ")) c=int(input("Masukkan Angka C : ")) if a > b and a > c: print(a,"Terbesar dari 3 bilangan yang diinputkan") elif b > a and b > c: print(b,"Terbesar dari 3 bilangan yang diinputkan") else: print(c,"Terbesar dari 3 bilangan yang diinputkan")
def ExtractSubSquence(aList): """This Function takes a list of numbers and extracts the longest sub sequence \n of numbers that are in ascending order""" subSequence = [] counter = 0 #keeps track of the length of the sub sequences to find the longest for i in range(len(aList)): if i == len(aList)-1: return("The Longest Sub Sequence is >> " + str(longestSubSequence)) elif aList[i] < aList[i+1]: subSequence.append(aList[i]) elif aList[i] > aList[i+1]: subSequence.append(aList[i]) if counter < len(subSequence): counter = len(subSequence) #making the counter the length of the sub sequence longestSubSequence = [] for i in range(len(subSequence)): longestSubSequence.append(subSequence[i]) # appending the element in the sub sequence to the longest sub sequence list subSequence = [] # restarting the sub sequence return(longestSubSequence) list1 = [1,2,3,1,5,8,9,3,4,5,6,7,1] list2 = [1,2,3,4,5,6,7,8,3,5,6,1,2] list3 = [1,2,3,2,5,8,97,1,2,2] print(ExtractSubSquence(list1)) print(ExtractSubSquence(list2)) print(ExtractSubSquence(list3))
import random # Demo of basic input in python # name = input("Enter your name: ") # print("Hello " + name) # Demo of a program that computes for an area of a circle # radius = float(input("Enter the radius: ")) # area = 3.14 * (radius**2) # print("The area of the Circle is: " + str(area)) # Demo of a program that computes for a volume of a cylinder # radius = float(input("Enter the Radius: ")) # height = float(input("Enter the Height: ")) # volume = 3.14 *(radius**2 * height) # print("The Volume of the Cylinder: " + str(volume)) #Demo for array # fruits = ["apple", "banana", "cherry", "strawberry", "melon", "watermelon"] # print(fruits[0]) # print(fruits[1]) # print(fruits[2]) #Demo for for Loop # for x in fruits: # print(x) # i = 0 # while i < 10: # print("Hello World") # print(i) # i = i + 1 #sample text-based game with simple conditional statement character_health = 100 item = "" name = input("Enter your name: ") print("Hello " + name) while character_health > 0: if character_health != 100 and item == "Fish": n = input("You have taken some damage to heal select [1 to heal/ 0 to ignore]") if n == "1": character_health += 10 print("Your character's health is back to " + str(character_health)) else : print("Your character's health is back to " + str(character_health)) v = int(input("Choose 1 if you want to cross the river\nChoose 2 if you want to jump on the ravine\nChoose 3 if you want to fight monster in the dungeon \nInput: ")) #Start of Journey if v == 1: choice = input("If you want to go fishing select [1 for yes/ 0 for no]") if choice == "1": #Fishing minigame print("You have chosen Fishing! ") chance = random.randint(0,9) if chance > 6: item = "Fish" print("You have catch a Fish!") else: print("There is no fish to catch") elif choice == "0": print("You have crossed the river") elif v == 2: #damages the player print("You have jumped into the ravine") print("Your character has taken 10pt of damage") character_health = character_health - 10 elif v == 3: #damages the player print("You have enter the dungeon") else: print("Invalid input") print("Your character's Health: " + str(character_health)) print("Your Character is dead!")
import timeit CACHE = dict() def factorial(n: int) -> int: if n == 0: return 1 else: return n * factorial(n - 1) def run_factorial(n: int)-> int: cached = CACHE.get(n) if cached: return cached if n == 0: return 1 else: result = n * factorial(n - 1) CACHE[n] = result return result stmt_no_cache = "" \ "factorial(500);" \ "factorial(400);" \ "factorial(450);" \ "factorial(350)" stmt_cache = "" \ "run_factorial(500);" \ "run_factorial(400);" \ "run_factorial(450);" \ "run_factorial(350)" duration_no_cache = timeit.timeit(stmt=stmt_no_cache, globals=globals(), number=10000) duration_cache = timeit.timeit(stmt=stmt_cache, globals=globals(), number=10000) print(f'Duration cache: {duration_cache}') print(f'Duration no cache: {duration_no_cache}') print(f'{round(duration_no_cache/duration_cache)} times faster with cache.')
from dataclasses import dataclass @dataclass() class Contact: name: str addresses: list = None def __str__(self): return f'{self.__dict__}' def __iadd__(self, other): if isinstance(other, Address): self.addresses.append(other) return self def __contains__(self, item): if isinstance(item, Address): return item in self.addresses @dataclass class Address: location: str def __repr__(self): return f'{self.__dict__}' contact = Contact(name='José', addresses=[Address(location='JPL')]) contact += Address(location='Houston') contact += Address(location='KSC') print(contact) # {'name': 'José', 'addresses': [{'city': 'JPL'}, {'city': 'Houston'}, {'city': 'KSC'}]} if Address(location='Bajkonur') in contact: print(True) else: print(False) # False
distance_meters = int(input("Input distance in metres: ")) distance_kilometers = int(distance_meters/1_000) distance_miles = float(distance_meters/1608) distance_nautical_miles = float(distance_meters/1852) print(f'Distance in meters: {distance_meters}') print(f'Distance in kilometers: {distance_kilometers}') print(f'Distance in miles: {distance_miles}') print(f'Distance in nautical miles: {distance_nautical_miles}') print(f'All: {distance_meters},{distance_kilometers},{distance_miles},{distance_nautical_miles}')
# def is_odd(n): # return n % 2 == 1 # a = list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # print(a) # def not_empty(s): # return s and s.strip() # a = list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) # print(a) #### filter # def _odd_iter(): # n = 1 # while True: # n = n + 2 # yield n # def _not_divisible(n): # return lambda x: x % n > 0 # def primes(): # yield 2 # it = _odd_iter() # 初始序列 # while True: # n = next(it) # 返回序列的第一个数 # yield n # it = filter(_not_divisible(n), it) # 构造新序列 # # 打印100以内的素数: # for n in primes(): # if n < 100: # print(n) # else: # break #####sorted #返回函数 # def lazy_sum(*args): # def sum(): # ax = 0 # for n in args: # ax = ax + n # return ax # return sum # f = lazy_sum(1, 3, 5, 7, 9) # print(f()) #一个函数可以返回一个计算结果,也可以返回一个函数。 #返回一个函数时,牢记该函数并未执行,返回函数中不要引用任何可能会变化的变量。 #匿名函数 #关键字lambda表示匿名函数,冒号前面的x表示函数参数。 # f = lambda x: x * x # print(f(5)) #装饰器 # def log(func): # def wrapper(*args, **kw): # print('call %s():' % func.__name__) # return func(*args, **kw) # return wrapper # def log(text): # def decorator(func): # def wrapper(*args, **kw): # print('%s %s():' % (text, func.__name__)) # return func(*args, **kw) # return wrapper # return decorator # import functools # def log(func): # @functools.wraps(func) # def wrapper(*args, **kw): # print('before call %s():' % func.__name__) # f = func(*args, **kw) # print('after call %s():' % func.__name__) # return f # return wrapper # # @log('excute') # @log # def now(): # print('2015-3-25') # now() # import functools # def log(text = 'call'): # def decorator(func): # @functools.wraps(func) # def wrapper(*args, **kw): # print('%s %s():' % (text, func.__name__)) # return func(*args, **kw) # return wrapper # return decorator # @log() # def go(): # print('1024') # @log('eve') # def gogo(): # print('1025') # go() # gogo() # import functools # # 调用方式@log 或者 @log('xxxx') # def log(args): # text = "" if callable(args) else args # def decorator(func): # @functools.wraps(func) # def wrapper(*args, **kw): # print('before ' + text) # return func(*args, **kw) # return wrapper # return decorator(args) if callable(args) else decorator # # 测试 # @log('xxx') # def test1(): # print('func1') # @log # def test2(): # print('func2') # test1() # test2() #偏函数 functools.partial #简单总结functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。 # import functools # int2 = functools.partial(int, base=2) # print(int2('1000000'))
from cs50 import get_float change = get_float("How much change are you owed?\n") while change < 0: change = get_float("How much change are you owed?\n") coins_number = 0 while change > 0.0: coins_number += 1 if change >= 0.25: change -= 0.25 elif change >= 0.1: change -= 0.1 elif change >= 0.05: change -= 0.05 else: change -= 0.01 change=round(change,2) print(coins_number)
import re import random import wikipedia from collections import defaultdict class MessageParser(object): """This is a basic class to do some very basic parsing of messages and returning strings for specific inputs. """ def __init__(self): """Constructor: Initialise the user dictionary, used for keeping score """ # Default all user scores to 0 self._userDict = defaultdict(int) def findCommandInMessage(self, msgString): """Searches for a command by finding the first (if any) # in a string, then getting all of the alpha characters immediately following the #. Returns empty if no # is found in the input string. """ returnString = '' m = re.search("#(?P<cmd>[a-zA-Z0-9_]+)", msgString) if m: returnString = m.group("cmd") return returnString def findNameInMessage(self, msgString): """Searches for a name by finding the first (if any) @ in a string, then getting all of the alpha characters immediately following the @. Returns an empty string if no @ is found in the input string. """ returnString = '' m = re.search("@(?P<name>[a-zA-Z]+)", msgString) if m: returnString = m.group("name") return returnString def findScoreInMessage(self, msgString): """Searches for a score by finding the first (if any) + or - in a string, then getting all of the alpha characters immediately following the +/-. Returns an empty string if no + or - is found in the input string. """ returnString = '' m = re.search("(?P<score>[\-\+][0-9]+)", msgString) if m: returnString = m.group("score") return returnString def parseDieRoll(self, msgString): """Parses the "roll the dice" command by finding the desired die size then returning a random number from 1 to the found size. Thanks to Doug for the idea, which was lovingly ripped off. Returns an error string if no valid die size is found. """ errorString = "Invalid die. Try #rtd d<number>." returnString = '' m = re.search("d(?P<die>[0-9]+)", msgString) if m: try: dieSize = int(m.group("die")) except: returnString = errorString else: if dieSize > 0: returnString = str(random.randint(1, dieSize)) else: returnString = errorString else: returnString = errorString return returnString def handleRandomCommand(self): """Gets a random page from Wikipedia and prints the summary paragraph. """ returnString = "" pg = wikipedia.random(1) try: returnString = wikipedia.summary(pg) except wikipedia.exceptions.DisambiguationError: returnString = self.handleRandomCommand() return returnString def cAtFaCtS(self): """Thanks for signing up for Cat Facts! .. """ returnString = "" facts = open("catfacts.txt", "r") catlines = facts.read() catlinesSplit = catlines.split(";") returnString = random.choice(catlinesSplit) facts.close() return returnString def chuck(self): """Chuck Norris Facts .. """ returnString = "" facts = open("chucknorris.txt", "r") chucklines = facts.read() chucklinesSplit = chucklines.split(";") returnString = random.choice(chucklinesSplit) facts.close() return returnString def parseMessage(self, chat_message): """Parses the input chat message object's text and keeps the user score up to date if necessary """ returnString = '' name = self.findNameInMessage(chat_message.text) command = self.findCommandInMessage(chat_message.text) if name: score = self.findScoreInMessage(chat_message.text) if score: # If both a name and score were found in the message text, # update the dictionary and print the user's total score intScore = 0 try: intScore = int(score) except: returnString = "Invalid Score Format! Try <+/-><number>." else: lname = name.lower() self._userDict[lname] += intScore returnString = '{}: {}'.format( lname, self._userDict[lname] ) elif command: if command == "score": returnString = ' | '.join( '{}: {}'.format(*item) for item in self._userDict.items() ) elif command == "3257": returnString = "Hot Asphalt" elif command == "rtd": returnString = self.parseDieRoll(chat_message.text) elif command == "random": returnString = self.handleRandomCommand() elif command == "catfacts": returnString = self.cAtFaCtS() elif command == "chucknorris": returnString = self.chuck() else: returnString = "I don't know how to {}.".format(command) return returnString
import math class Coord: def __init__(self, x, y, dir): self.x = x self.y = y self.dir = dir def __str__(self): return "X: {0}, Y: {1}, D: {2}".format(self.x, self.y, self.dir) def update(self, x, y, dir): self.x = x self.y = y self.dir = dir def updateXY(self, x, y): self.x = x self.y = y def angle2Coord(self, coord2): return math.atan2(coord2.y-self.y, coord2.x-self.x) * 180 / math.pi def distanceToCoord(self, coord2): return math.sqrt((coord2.x - self.x)**2 + (coord2.y - self.y)**2)
"""Module for classes representing a PokerGame player and table of players""" import random import sys from Action import Action, InvalidActionException from Hand import Hand from PokerException import PokerException from Utils import assertInstance, UserSelection ###################################################################### # # Exceptions # class PlayerAlreadySeatedException(PokerException): """Player is already seated at this table.""" pass class SeatFullException(PokerException): """Seat is already taken.""" pass class TableFullException(PokerException): """Table is full.""" pass class ZeroStackException(PokerException): """Player's stack is zero.""" pass ###################################################################### class Player(object): """Interface to a player in a game. Contains state related to player for a particular game and logic for interfacing with the player (be that a human or code).""" STATUS_SITTING_OUT = 0x01 STATUS_ACTIVE = 0x02 STATUS_ALL_IN = 0x03 STATUS_FOLDED = 0x04 STATUS_STRINGS = { STATUS_SITTING_OUT : "sitting out", STATUS_ACTIVE : "active", STATUS_ALL_IN : "all_in", STATUS_FOLDED : "folded", } def __init__(self, name=None, stack=0, HandClass=Hand): if name is None: name = "Unnamed Player" self.name = name self.stack = stack self.HandClass = HandClass # Amount bet in current hand not yet swept into pot self.bet = 0 if self.stack > 0: self.status = self.STATUS_ACTIVE else: self.status = self.STATUS_SITTING_OUT # Private state self._hand = None def new_hand(self): """Create a new hand for player, setting status to active""" self.muck_hand() self._hand = self.HandClass() self.status = self.STATUS_ACTIVE def deal_card(self, deck): """Deal the player a card from the given deck""" deck.deal(self._hand) def muck_hand(self): """Muck the player's hand, setting player's status to folded""" self._hand = None self.status = self.STATUS_FOLDED def get_public_hand_as_str(self): """Return a string with the players hand as viewed publicly""" return self._hand.get_public_string() def make_active(self): """Make the player active. Stack must be non-zero.""" if self.stack == 0: raise ZeroStackException() self.status = self.STATUS_ACTIVE def sit_out(self): """Change player's status to sitting out.""" self.status = self.STATUS_SITTING_OUT def get_status(self): """Return status as string""" return self.STATUS_STRINGS[self.status] def is_sitting_out(self): """Is the player sitting out?""" return (self.status == self.STATUS_SITTING_OUT) def is_active(self): """Is the player still actively betting?""" return (self.status == self.STATUS_ACTIVE) def is_all_in(self): """Is the player all-in?""" return (self.status == self.STATUS_ALL_IN) def is_folded(self): """Is the player folded?""" return (self.status == self.STATUS_FOLDED) def get_action(self, request, game, hand_state): """Get a players betting action. Returns a Action instance.""" if request.is_ante_request(): action = self.get_ante_action(request, game, hand_state) elif request.is_blind_request(): action = self.get_blind_action(request, game, hand_state) elif request.is_opening_bet_request(): action = self.get_opening_bet_action(request, game, hand_state) elif request.is_call_request(): action = self.get_call_action(request, game, hand_state) elif request.is_option_request(): action = self.get_option_action(request, game, hand_state) else: raise ValueError("Unrecognized ActionRequest: {}".format(request)) return action def get_ante_action(self, request, game, hand_state): """Get Action in response to ante request""" return Action.new_ante(min(request.amount, self.stack), all_in = request.amount >= self.stack) def get_blind_action(self, request, game, hand_state): """Get Action in response to blind request""" return Action.new_blind(min(request.amount, self.stack), all_in = request.amount >= self.stack) def get_opening_bet_action(self, request, game, hand_state): """Get Action in response to opening bet request""" # No bet required, check 75%, bet 25% random_number = random.random() if random_number < .75: action = Action.new_check() else: action = Action.new_bet(min(request.amount, self.stack), all_in=request.amount >= self.stack) return action def get_call_action(self, request, game, hand_state): """Get Action in response to call request""" # Bet in front of us, fold 50%, call 35%, raise 15% (if allowed) random_number = random.random() if (random_number < .15) and \ (request.raise_amount is not None) and \ (self.stack > request.amount): action = Action.new_raise(min(request.raise_amount, self.stack), all_in=request.raise_amount >= self.stack) elif random_number < .50: action = Action.new_call(min(request.amount, self.stack), all_in=request.amount >= self.stack) else: action = Action.new_fold() return action def get_option_action(self, request, game, hand_state): """Get Action in request to option request""" # Calls in front of us, raise 25%, check 75% random_number = random.random() if (random_number < .25) and \ (self.stack > 0): action = Action.new_raise(min(request.raise_amount, self.stack), all_in=request.raise_amount >= self.stack) else: action = Action.new_check() return action def message(self, string): """Handle a message to the player. This implementation just discards it.""" pass def process_action(self, action): """Move amount of action from stack to bet. If action is an all-in, verify that is the case.""" if action.amount < 0: raise InvalidActionException("Action is negative") if action.amount > self.stack: raise InvalidActionException("Bet is larger than player stack") if action.is_all_in() and (action.amount != self.stack): raise InvalidActionException("All-in action is not size of stack") self.stack -= action.amount self.bet += action.amount def win(self, amount): """Add given winings to stack""" self.stack += amount def __str__(self): return self.name ###################################################################### class HumanPlayer(Player): """Interface to a human player. >>> player=HumanPlayer("Jane", stack=1000, input=sys.stdin, output=sys.stdout) >>> str(player) 'Jane' >>> player.stack 1000 """ def __init__(self, name=None, stack=0, HandClass=Hand, input=sys.stdin, output=sys.stdout): """Create an interface to human player using given input and output streams.""" self.input = input self.output = output Player.__init__(self, name, stack, HandClass) def get_opening_bet_action(self, request, game, hand_state): """Get Action in response to open bet request""" self.display_hand_state(request, game, hand_state) user_selection = self._newUserSelection() user_selection.add_option("c", "check", Action.new_check()) user_selection.add_option("b", "bet", Action.new_bet(request.amount)) return user_selection.get_user_selection() def get_call_action(self, request, game, hand_state): """Get Action in response to call request""" self.display_hand_state(request, game, hand_state) user_selection = self._newUserSelection() user_selection.add_option("c", "call {}".format(request.amount), Action.new_call(request.amount)) user_selection.add_option("f", "fold", Action.new_fold()) if request.raise_amount != None: user_selection.add_option(\ "r", "raise to {}".format(request.raise_amount), Action.new_raise(request.raise_amount)) return user_selection.get_user_selection() def get_option_action(self, request, game, hand_state): """Get Action in request to option request""" self.display_hand_state(request, game, hand_state) user_selection = self._newUserSelection() user_selection.add_option("c", "check", Action.new_check()) user_selection.add_option("r", "raise {}".format(request.raise_amount), Action.new_raise(request.raise_amount)) return user_selection.get_user_selection() def display_hand_state(self, request, game, hand_state): """Display current hand state to player""" self.message("Pot: {}".format(hand_state.pot)) self.display_players(game, hand_state) self.display_hand(game, hand_state) def display_players(self, game, hand_state): """Display other players at the table""" # Start at player after myself and go around table player = game.table.get_next_player(self) while player is not self: self.display_player(player) player = game.table.get_next_player(player) def display_player(self, player): """Display given player""" player_str = "{0}: Stack: {0.stack}".format(player) if player.is_sitting_out(): self.message("{} - Sitting out".format(player_str)) elif player.is_folded(): self.message("{} - Folded".format(player_str)) else: all_in_str = "(ALL-IN)" if player.is_all_in() else "" self.message("{} Bet: {} {} Hand: {}"\ .format(player_str, player.bet, all_in_str, player.get_public_hand_as_str())) def display_hand(self, game, hand_state): """Display players hand""" rank_strs = [] if game.HighRanker is not None: high_rank = game.HighRanker.rankHand(self._hand) rank_strs.append("High: {}".format(high_rank)) if game.LowRanker is not None: low_rank = game.LowRanker.rankHand(self._hand) rank_strs.append("Low: {}".format(low_rank)) self.message("Your hand: {} ({})".format(self._hand, " ".join(rank_strs))) def message(self, string): """Handle a message to the player.""" self.output.write(string.rstrip() + "\n") def _newUserSelection(self): """Return a new UserSelection instance""" return UserSelection(input_stream=self.input, output_stream=self.output) ###################################################################### class Table(object): """Collection of players at a table""" def __init__(self, number_of_seats=9, players=None): """Create a table with given number of seats. Seat array of players if given.""" assertInstance(number_of_seats, int) self.number_of_seats = number_of_seats # One extra seat for seat 0 which we don't use to keep # indexing simple. self.players = [ None ] * (number_of_seats + 1) if players is not None: self.seat_players(players) self.dealer = None def seat_player(self, player, seat_number=None): """Seat the given player. If seat_number is given, seat player there, otherwise chose randomly.""" if player in self.players: raise PlayerAlreadySeatedException( "Player %s is already seated" % player) if seat_number is None: empty_seats = self.get_empty_seats() if len(empty_seats) == 0: raise TableFullException() seat_number = random.choice(empty_seats) else: if self.players[seat_number] is not None: raise SeatFullException() self.players[seat_number] = player def seat_players(self, players, in_order=False): """Randomly seat the given players. If in_order is True, seat in order at lowest numbered seats.""" if in_order: empty_seats = self.get_empty_seats() for player in players: if len(empty_seats) == 0: raise TableFullException() self.seat_player(player, seat_number=empty_seats.pop(0)) else: for player in players: self.seat_player(player) def get_seated_players(self): """Return an array of seated players""" return filter(lambda p: p is not None, self.players) def get_player_seat(self, player): """Given a player return their seat number""" return self.players.index(player) def get_player_by_seat(self, seat): """Given a seat number, return the player sitting there""" return self.players[seat] def get_empty_seats(self): """Return an array of seat numbers which are empty""" return filter(lambda n: self.players[n] is None, range(1, len(self.players))) def get_active_players(self): """Return an array of players who are active in the hand. This means players are not sitting out or have folded.""" return filter(lambda p: p.is_active() or p.is_all_in(), self.get_seated_players()) def get_next_player(self, starting_player, filter=None): """Return the next player clockwise from given player. If filter is not none, it should be a function used to filter out players. If it returns False, player will be skipped. If no players passes filter, IndexError is raised. May return given player if logic so dictates.""" starting_seat = self.get_player_seat(starting_player) seat = (starting_seat + 1) % len(self.players) while True: if (self.players[seat] is not None) and \ ((filter is None) or filter(self.players[seat])): break if seat == starting_seat: # We've go all the way around without a match raise IndexError() seat = (seat + 1) % len(self.players) return self.players[seat] def random_dealer(self): """Make a random player the dealer.""" # XXX Should we choose a player with a non-zero stack? self.dealer = random.choice(self.get_seated_players()) def set_dealer(self, player): """Set the dealer to the given player.""" self.dealer = player def get_dealer(self): """Return the current dealer""" return self.dealer def advance_dealer(self): """Advance the dealer to the next player""" # XXX Should we choose a player with a non-zero stack? try: self.dealer = self.get_next_player(self.dealer) except IndexError: # No other player available, leave button where it is pass def __str__(self): player_strings = [] for seat, player in enumerate(self.players): if player is None: continue s = "%d: %s" % (seat, player) if player == self.get_dealer(): s+= "*" player_strings.append(s) return " ".join(player_strings)
"""Class for ranking poker hands""" from Cards import Rank from PokerException import PokerInternalException from PokerRank import PokerRank from Ranker import RankerBase class LowRanker(RankerBase): """Given a Hand, return its PokerRank for low. Ignores straights and flushes (i.e. wheel is best low hand).""" @classmethod def rankHand(cls, hand): """Given a Hand return a PokerRank for its best hand. Limited to Hands of five to seven cards.""" hand.makeAcesLow() # Iterate through all the possible sets of cards in hand and # find the highest rank lowRank = None for cards in hand.hands(): rank = cls._rankHand(cards) if (lowRank is None) or (rank < lowRank): lowRank = rank return lowRank @classmethod def bestHand(cls, hands): """Riven an array of hands, return the best hands and their rank. Returns an array of best hand indexes (even if there is just one) and the rank of those hands.""" best_hands = [] best_rank = None for index, hand in enumerate(hands): rank = cls.rankHand(hand) if rank is None: continue if (best_rank is None) or (rank < best_rank): best_hands = [index] best_rank = rank elif best_rank == rank: best_hands.append(index) return best_hands, best_rank @classmethod def _rankHand(cls, hand): """Given a Hand, return its PokerRank for its best low hand. Limited to Hands of 5-7 cards.""" if len(hand) > 7: raise ValueError("Hand has too many cards (%d > 7)" % len(hand)) if len(hand) < 5: raise ValueError("Hand has too few cards (%d < 5)" % len(hand)) rankCounts = hand.countRanks() # Count ranks which we have at least one of atLeastOne = filter(lambda rank: rankCounts[rank] > 0, Rank.rankRange) # If we don't have at least two different ranks, we have five-of-a-kind if len(atLeastOne) < 2: raise PokerInternalException("Apparently have five of a kind with hand %s" % hand) if len(atLeastOne) >= 5: # We can make a hand without a pair return PokerRank.highCard(atLeastOne[4], atLeastOne[0:4]) # We didn't find 5 unpaired cards, figure out where we stand atLeastTwo = filter(lambda rank: rankCounts[rank] > 1, Rank.rankRange) if len(atLeastTwo) == 0: raise PokerInternalException("Invalid state (no pair) with hand %s" % hand) if len(atLeastOne) == 4: # We will have one pair which will be lowest rank remaining pairRank = atLeastTwo[0] # Remove pair to obtain kickers atLeastOne.remove(pairRank) return PokerRank.pair(pairRank, atLeastOne) elif (len(atLeastOne) == 3) & (len(atLeastTwo) >= 2): # We have two pair pairRank1 = atLeastTwo[0] pairRank2 = atLeastTwo[1] # Remove pairs to obtain kicker atLeastOne.remove(pairRank1) atLeastOne.remove(pairRank2) return PokerRank.twoPair(pairRank1, pairRank2, atLeastOne) # If we reach this point, we have at least trips. atLeastThree = filter(lambda rank: rankCounts[rank] > 2, Rank.rankRange) if len(atLeastThree) == 0: raise PokerInternalException("Invalid state (no trips) with hand %s" % hand) if len(atLeastOne) == 3: tripsRank = atLeastThree[0] # Remove trips to obtain kickers atLeastOne.remove(tripsRank) return PokerRank.trips(tripsRank, atLeastOne) # If we reach this point, we have a full house or quads if len(atLeastOne) != 2: raise PokerInternalException("Invalid state (less than two ranks) with hand %s" % hand) if len(atLeastTwo) > 1: # Remove trips from pairs to find full house fillers tripsRank = atLeastThree[0] atLeastTwo.remove(tripsRank) return PokerRank.fullHouse(tripsRank, atLeastTwo[0]) # If we reach this point, we have quads atLeastFour = filter(lambda rank: rankCounts[rank] > 3, Rank.rankRange) if len(atLeastFour) == 0: raise PokerInternalException("Invalid state (no quads) with hand %s" % hand) quadsRank = atLeastFour[0] # Remove quads to obtain kicker atLeastOne.remove(quadsRank) return PokerRank.quads(quadsRank, atLeastOne) class EightLowRanker(LowRanker): """Given a hand return its PokerRank if it qualifies for a 8-low or better. Ignore straights and flushes (i.e. wheel is best low hand).""" @classmethod def rankHand(cls, hand): """Given a Hand returna a PokerRank for its best 8-low hand. Returns None if hand does not qualify for 8-low or better. Limted to Hands of five to seven cards.""" hand.makeAcesLow() # Iterate through all the possible sets of cards in hand and # find the highest rank lowRank = None for cards in hand.combinations_of_eight_or_lower(5): rank = cls._rankHand(cards) if (lowRank is None) or (rank < lowRank): lowRank = rank return lowRank
#!/usr/bin/python3 # - * - encode: utf-8 - * - import sys, re input_file = sys.argv[1] word_to_search = sys.argv[2] with open(input_file, 'r') as f: lines = f.readlines() f.close() for line in lines: array = re.findall(word_to_search, line) if word_to_search in array: words = line.split() for word in words: if word not in array: print(word, end=' ') else: print('\033[91m' + word + '\033[0m') print('')
# Question Link: https://www.hackerrank.com/challenges/py-set-add/problem n=int(input()) s= set('') for i in range (0,n): st=input(); s.add(st); count =0 for _ in s: count+=1 print(count)
""" File to contain LWR Class """ import numpy as np # import data and assign each control and GT data point a unique ID def load_data(file_name, header, footer, cols): """ Function to import data from a file Input: file_name = Full file names header = number of header rows starting from 0 footer = number of footer rows starting from 0 cols = select the columns with useful data. set to None for all columns Output: data = list type of data from file. Files must be in same directory as the python file """ data = np.genfromtxt(file_name, skip_header=header, skip_footer=footer, usecols=cols, names=True, dtype=None, delimiter=',') return data class LWLR(object): """ Class to handle LWLR learning for given data set. """ def __init__(self, data_x, data_y, h): self.training_data_x = data_x self.training_data_y = data_y self.N = data_x.shape[0] self.n = data_x.shape[1] self.W = np.zeros([self.N,self.N]) self.beta = 0 self.residuals = 0 self.h = h # bandwidth self.Zinv = 0 def determine_beta(self, input_mat, output_vec, inv_matrix=None): """ Calulates the beta matrix given an input matrix and output vector inv_matrix is used to avoid recomputing the matrix inverse from the prediction step if doing a weighted prediction """ if inv_matrix is None: buf = np.dot(input_mat.T, input_mat) buf = np.linalg.pinv(buf) else: buf = inv_matrix buf = np.dot(buf, input_mat.T) B = np.dot(buf, output_vec) return B def unweighted_prediction(self, query): """ Calculate the unweighted prediction for a given query array """ self.beta = self.determine_beta(self.training_data_x, self.training_data_y) uwprediction = np.dot(query, self.beta) return uwprediction def weighted_prediction(self,query): """ Calculate the locally weighted prediction for a given query array """ self.get_weight_matrix(query) Z_matrix = np.dot(self.W, self.training_data_x) # Compute Z Matrix V_matrix = np.dot(self.W, self.training_data_y) # Compute V Matrix # Step by Step work through the prediction equation: buf = np.dot(Z_matrix.T, Z_matrix) buf = np.linalg.pinv(buf) self.Zinv = np.copy(buf) buf = np.dot(query.T, buf) buf = np.dot(buf, Z_matrix.T) wprediction = np.dot(buf, V_matrix) self.beta = self.determine_beta(Z_matrix, V_matrix, inv_matrix=self.Zinv) # used for variance computation return wprediction def get_weight_matrix(self, query): """ Determine the weight matrix for a query point """ for i, xi in enumerate(self.training_data_x): buf = np.dot((xi - query).T,(xi - query)) # Unweighted Euclidean Distance d = np.sqrt(buf) / self.h # Unweighted Euclidean Distance K = np.exp(-1 * np.dot(d.T, d)) # Gaussian Kernal self.W[i][i] = round(np.sqrt(K), 8) # Assemble Weight Matrix def evaluate_learning(self): """ Calculate the variance for a given query point and MSE """ n_lwr = 0 p_lwr = 0 criteria = 0 MSE_cv = 0 for i, xi in enumerate(self.training_data_x): if self.W[i][i] == 0: continue else: z_i = self.W[i][i] * xi v_i = self.W[i][i] * self.training_data_y[i] r_i = np.dot(z_i, self.beta) - v_i buf = self.W[i][i]**2 buf = np.dot(buf, z_i.T) buf = np.dot(buf, self.Zinv) p_lwr = np.dot(buf, z_i) criteria += r_i**2 n_lwr += self.W[i][i]**2 buf = np.dot(z_i.T, self.Zinv) buf = np.dot(buf, z_i) MSE_cv += (r_i / (1 - buf))**2 var_q = criteria / (n_lwr - p_lwr) MSE_cv_q = MSE_cv * (1 / n_lwr) return var_q, MSE_cv_q
import pyttsx3 # for text to speech import speech_recognition # for recognition of speech import wikipedia # for wikipedia summary import webbrowser # for working with web browsers from datetime import * # for time related stuffs from time import sleep # for sleep function import sys # for own python environment stuffs from pyjokes import pyjokes # for jokes # useful variables message = '' # would be the message to be spoke username = '' # to remember the username command = '' # would be the command taken from user summary = '' # would be summary of search introduction = 'I am an artificial bot, i am deemed to help you out, please tell me how might i help you, ' \ 'you can use commands to let me do something, regards' # intro # content = '' # content of file # declaring variables related time today = datetime.today() # current time date = today.strftime('%d') # current date month = today.strftime('%b') # current month day = today.strftime('%w') # current day hour = today.strftime('%H') # current hour, should be on 24 hour format minutes = today.strftime('%M') # current minutes seconds = today.strftime('%S') # current seconds am_pm = today.strftime('%p') # am/pm # initializing engine engine = pyttsx3.init() # voices = engine.getProperty('voices') # can # engine.setProperty('voices', voices[0].id) # engine.say('Hello World') # engine.runAndWait() # recognizer recognizer = speech_recognition.Recognizer() # recognizer microphone = speech_recognition.Microphone() # microphone # methods : def say(subject): engine.say(subject) engine.runAndWait() # noinspection PyChainedComparisons def greet(): if hour >= str(0) and hour <= str(12): say('good morning') elif hour >= str(13) and hour <= str(15): say('good afternoon') elif hour >= str(16) and hour <= str(20): say('good evening') else: # say("It's too late night sir, will talk tomorrow") # return pass sleep(0.3) say(introduction) if __name__ == '__main__': # greet() if hour >= str(22): # if time is greater than 10:00 pm, then exit sleep(0.3) say('I am tired, will talk later') say('Thank you for giving your precious time to me, i hope we will talk again, will meet soon, Bye') exit() while command != 'exit': # taking command with microphone as source: print('listening... give a command') # telling the user that microphone is listening recognizer.pause_threshold = 0.9 # waits for 0.9 seconds audio = recognizer.listen(source) # noinspection PyBroadException try: # recognizing print('recognizing command...') # sleep(0.1) command = recognizer.recognize_google(audio, language='en-in') print(f'command taken : {str(command).lower()}') except Exception as e: # if unable to recognize then: print('unable to recognize') say('unable to recognize this might because of no internet connection please restart') exit(1) if command != '': # command should be in lower or upper case # defining choices : print('replying....') if command.lower() == 'exit': # if command taken from user is 'exit', then: say('Thank you for giving your precious time to me, i hope we will talk again, will meet soon, Bye') break # terminates the infinite loop elif command.lower() == 'what is your name': # if command is 'what is your name' : say("well, i don't have a name till, my work is to win heart by my work not by my name") elif command.lower() == 'who are you': # if command is 'who are you' say(introduction) # say('what about you') elif 'how are you' in command.lower(): # if command is 'how are you': say('I am fine as always, doing my work everytime, how about you') elif command.lower() == 'i am fine too': # connected with upper case say('glad to hear, anything new to tell') elif command.lower().startswith('hello'): # if command is starting with 'hello': greet() elif command.lower().startswith('i am'): # if user told his/her name using 'i am': if len(command) < 16: username = command[5:].lower() # remember the name print(f'username : {username}') say(f'hello {username}, you have such a wonderful name, i liked it') elif command.startswith('my name is'): # name... username = command[11:].lower() print(username) say(f'hello {username}, you have such a wonderful name, i like it') elif 'tell me the time' in command.lower(): # tells current time say(f'the time now is {hour} hours and {minutes} minutes') elif 'what is the day today' in command.lower(): # tells current day say(f'today is {day}') elif 'what is the date today' in command.lower(): # tells current date say(f'today is {date} {month}') elif 'open google' in command.lower(): # opens google say('opening google...') webbrowser.open_new_tab('google.com') elif 'open youtube' in command.lower(): # opens youtube say('opening youtube...') webbrowser.open_new_tab('youtube.com') elif 'open github' in command.lower(): # opens github say('opening github...') webbrowser.open_new_tab('github.com') elif 'open bing' in command.lower(): # opens bing say('opening bing...') webbrowser.open_new_tab('bing.com') elif 'search' in command.lower(): # searches the words after 'search' say('searching on wikipedia...') summary = wikipedia.summary(command.lower()) # webbrowser.open_new_tab(wikipedia.summary(command)) say(summary) elif 'tell interpreter location' in command.lower(): location = sys.executable print(f'location of interpreter is {location}') say(f'location of interpreter is {location}') elif 'tell me a joke' in command or 'do you have a joke' in command: say('telling joke...') joke = pyjokes.get_joke(language='en') # print(pyjokes.get_joke(language='en', category='neutral')) say(joke) print(joke) # opening .txt files elif command.startswith('open file') and command.lower().endswith('to read'): if len(command) < 25: try: with open(command[10:14]+'.txt', 'r') as file: say(f'opening {file.name}') print(f'content inside {file.name} : {file.read()}') say('closing file') except(FileNotFoundError, FileExistsError) as exception: say('unable to open file') print('exception', exception) else: say('you have to apply the location of file') name_location = input('enter the location and name of the file') with open(name_location, 'r') as file: say(f'opening {file.name}') print(f'content inside {file.name} : {file.read()}') say('closing file') elif command.lower().startswith('open file') and command.lower().endswith('to write'): try: if len(command) < 25: with open(command[10:14]+'.txt', 'w') as file: say(f'opening {file.name}') toWrite = input('type the content that you want to write : ') file.write(toWrite) say('file updated') say('closing file') else: name_location = input('enter the location : ') with open(name_location, 'w') as file: say('file opened') toWrite = input('type the content that you want to write : ') file.write(toWrite) say('file updated successfully') say('closing file') except(FileNotFoundError, FileExistsError) as exception: say('file not valid') else: # if no command matches, then : say('sorry, i did not got your command well, can you say that again please')
ab = { "lufubo":23, "chengming":34, "yangg":45} print("lufubo's age %s" % ab["lufubo"]) ab["lufubo"] = 99 print("lufubo's age %s" % ab["lufubo"]) print("ab len %d" % len(ab)) #del ab["lufubo"] print("ab len %d" % len(ab)) for name, age in ab.items(): print("name %s age:%d" % (name, age)) print("\n") new_name = "lufubo" if new_name in ab: print("%s's address is %s" % (new_name,ab["lufubo"]))
name = "Lucian" #Har skapat variablen name och tilldelat det värdet Lucian age = 17 #skapat variablen age och tilldelat det värdet 29 print(f"Hello {name} you are {age} year old") side = float(input("Ange kvadratens sida")) area = side**2 omkrets = 4*side print(f"kvadratens area är {area} a.e. och kvadraten omkrets är {omkrets} l.e.")
def palindromes_of_length_n(n): middle = list(map(str, range(10))) if n%2==1 else [''] outer = [''] if n != 1: outer = list(map(str, range(10**(n//2-1), 10**(n//2)))) result = [] for x in outer: for y in middle: result.append(x + y + x[::-1]) return result def palindromes_of_length_under_n(n=7): result = [] for i in range(1,n): result += palindromes_of_length_n(i) return result def is_bin_of_n_palindrome(n): b = bin(n)[2:] return b==b[::-1] result = 0 print(palindromes_of_length_under_n()) for x in map(int, palindromes_of_length_under_n()): if is_bin_of_n_palindrome(x): print(x, bin(x)) result += x print(result)
a=int(input("Number of students")) marks_in_bme=[] name=[] for i in range (a): h=input("Enter name of students") name.append(h) i=int(input("Enter marks")) marks_in_bme.append(i) print(name) print(marks_in_bme) result=zip(name,marks_in_bme) result_set=set(result) print(result_set)
#! /usr/bin/env python3 import numpy as np import tkinter as tk import tkinter.ttk as ttk import tkinter.filedialog as tkfdlg class PolygonDrawer: """Shows a Tk window on which a rectangle can be drawn.""" def __init__(self): """Builds and shows the window.""" # Set up root window self.root = tk.Tk() self.root.title("Polygon in canvas") self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) #fn = tkfdlg.askopenfilename(title="Wähle Datei aus") #print(type(fn)) #print(fn) # Set up frame in root window self.mainframe = ttk.Frame(self.root, height="20c", width="20c") self.mainframe.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S)) # Show a label ttk.Label(self.mainframe, text="Klicken, um ein Polygon zu zeichnen" ).grid(column=0, row=0, sticky=(tk.W)) # Set up canvas self.canvas = tk.Canvas(self.mainframe, background="white") self.canvas.grid(column=0, row=1, sticky=(tk.N, tk.W, tk.E, tk.S)) self.canvas.bind("<1>", self.canvas_clicked) self.canvas.bind("<Motion>", self.canvas_dragged) # Initialize rectangle drawing state variables self.rectState = False self.x_base = None self.y_base = None # Enter the event loop self.root.mainloop() def canvas_clicked(self, e): """Callback function for mouse clicks on the canvas. If no rectangle is being drawn, a new rectangle is initialized. If a rectangle is being drawn, it is finalized. """ if not self.rectState: # No rectangle being drawn; draw a new one self.canvas.delete("r") self.x_base = e.x self.y_base = e.y self.canvas.create_rectangle( (self.x_base, self.y_base, self.x_base, self.y_base), outline="red", tag="r") self.rectState = True else: # Finalize currently drawn rectangle self.canvas.itemconfigure("r", outline="black") self.x_base = None self.y_base = None self.rectState = False def canvas_dragged(self, e): """Callback function for mouse movement on the canvas. If no rectangle is being drawn, do nothing. If a rectangle is being drawn, update its shape. """ if not self.rectState: return x = e.x y = e.y x_nw, x_se = (self.x_base, x) if x > self.x_base else (x, self.x_base) y_nw, y_se = (self.y_base, y) if y > self.y_base else (y, self.y_base) self.canvas.coords("r", x_nw, y_nw, x_se, y_se) if __name__ == "__main__": PolygonDrawer()
class SessionView: """SessionView base class This class defines an API for session views. Session views should be created by subclassing this class and implementing the necessary methods. """ @classmethod def create(cls, *args, **kwargs): """Create a new SessionView instance and return it. This method is the preferred way to instantiate a session view. It calls the (optional) 'prepare' method to perform all necessary preparation that must be run in the GUI thread before creating the SessionView. Then, the class is instantiated, and the new instance is returned. The arguments (args, kwargs) are provided to both the 'prepare' and '__init__' method. """ cls.prepare(*args, **kwargs) return cls(*args, **kwargs) @classmethod def prepare(cls, *args, **kwargs): """Run all preparation tasks. For details, see the 'create' method. """ pass def __init__(self, title='SessionView'): raise NotImplementedError def mainloop(self): """Run the GUI mainloop. This method must be implemented by subclasses. """ raise NotImplementedError def update_status(self, msg, current=None, total=None): """Callback for updating the status message. This method must be run from the GUI thread. This method must be implemented by subclasses. """ raise NotImplementedError
import sys import re def weird_list(string, n): return [word for word in re.split(r"[\W|_]+", string) if len(word) > n] if __name__ == "__main__": if len(sys.argv) != 3: print("ERROR") else: try: print(weird_list(str(sys.argv[1]), int(sys.argv[2]))) except ValueError: print("ERROR")
"""N-queens puzzle The N-queens problem is about placing N chess queens on an N*N chessboard so that no two queens threaten each other. A solution requires that no two queens share the same row, column diagonal or anti-diagonal.The problem's target is try to find how many solutions exist. """ import time from z3 import * class Todo(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg def __repr__(self): return self.__str__() def n_queen_la(board_size: int, verbose: bool = False) -> int: solver = Solver() n = board_size # Each position of the board is represented by a 0-1 integer variable: # ... ... ... ... # x_2_0 x_2_1 x_2_2 ... # x_1_0 x_1_1 x_1_2 ... # x_0_0 x_0_1 x_0_2 ... # board = [[Int(f"x_{row}_{col}") for col in range(n)] for row in range(n)] # only be 0 or 1 in board for row in board: for pos in row: solver.add(Or(pos == 0, pos == 1)) # @exercise 11: please fill in the missing code to add # the following constraint into the solver: # each row has just 1 queen, # each column has just 1 queen, # each diagonal has at most 1 queen, # each anti-diagonal has at most 1 queen. # raise ("exercise 11: please fill in the missing code.") for row in board: solver.add(sum(row) == 1) b = list(zip(*board)) for row in b: solver.add(sum(row) == 1) for i in range(n * 2 - 1): tmp = [] for j in range(i + 1): if i - j < n: k = i - j if k < n and k >= 0 and j < n: tmp.append(board[j][k]) solver.add([sum(tmp) <= 1]) for i in range(n * 2 - 1): tmp = [] d = n - i - 1 for j in range(n): k = j - d if k >= 0 and k < n: tmp.append(board[j][k]) solver.add(sum(tmp) <= 1) # count the number of solutions solution_count = 0 start = time.time() while solver.check() == sat: solution_count += 1 model = solver.model() if verbose: # print the solution print([(row_index, col_index) for row_index, row in enumerate(board) for col_index, flag in enumerate(row) if model[flag] == 1]) # generate constraints from solution solution_cons = [(flag == 1) for row in board for flag in row if model[flag] == 1] # add solution to the solver to get new solution solver.add(Not(And(solution_cons))) print(f"n_queen_la solve {board_size}-queens by {(time.time() - start):.6f}s") return solution_count def n_queen_bt(board_size: int, verbose: bool = False) -> int: n = board_size solutions = [[]] def is_safe(col, solution): same_col = col in solution same_diag = any(abs(col - j) == (len(solution) - i) for i, j in enumerate(solution)) return not (same_col or same_diag) start = time.time() for row in range(n): solutions = [solution + [col] for solution in solutions for col in range(n) if is_safe(col, solution)] print(f"n_queen_bt solve {board_size}-queens by {(time.time() - start):.6f}s") if verbose: # print the solutions for solution in solutions: print(list(enumerate(solution))) return len(solutions) def n_queen_la_opt(board_size: int, verbose: bool = False) -> int: solver = Solver() n = board_size # We know each queen must be in a different row. # So, we represent each queen by a single integer: the column position # the q_i = j means queen in the row i and column j. queens = [Int(f"q_{i}") for i in range(n)] # each queen is in a column {0, ... 7 } solver.add([And(0 <= queens[i], queens[i] < n) for i in range(n)]) # one queen per column solver.add([Distinct(queens)]) # at most one for per anti-diagonal & diagonal solver.add([If(i == j, True, And(queens[i] - queens[j] != i - j, queens[i] - queens[j] != j - i)) for i in range(n) for j in range(i)]) # count the number of solutions solution_count = 0 start = time.time() while solver.check() == sat: solution_count += 1 model = solver.model() if verbose: # print the solutions print([(index, model[queen]) for index, queen in enumerate(queens)]) # generate constraints from solution solution_cons = [(queen == model[queen]) for queen in queens] # add solution to the solver to get new solution solver.add(Not(And(solution_cons))) print(f"n_queen_la_opt solve {board_size}-queens by {(time.time() - start):.6f}s") return solution_count if __name__ == '__main__': # 8-queen problem has 92 solutions print(n_queen_la(8)) print(n_queen_la_opt(8)) # @exercise 12: Try to compare the backtracking with the LA algorithms, # by changing the value of the chessboard size to other values, # which one is faster? What conclusion you can draw from the result? # raise ("exercise 12: please fill in the missing code.") print(n_queen_bt(8)) # @exercise 13: Try to compare the efficiency of n_queen_la_opt() method # with your n_queen_la() method. # What's your observation? What conclusion you can draw? # n_queen_la solve 8-queens by 6.432873s # n_queen_la_opt solve 8-queens by 0.723236s # n_queen_bt solve 8-queens by 0.038886s # 92 print(n_queen_la(9)) print(n_queen_la_opt(9)) print(n_queen_bt(9)) # n_queen_la solve 9-queens by 37.563531s # n_queen_la_opt solve 9-queens by 5.235053s # n_queen_bt solve 9-queens by 0.191486s # 352 print("The problems of 12,13:") print("bt 性能最优\n" "la_opt 性能居中\n" "la 性能最差") # raise ("exercise 13: please fill in the missing code.")
import random class NotecardPseudoSensor: def __init__(self, card): self.card = card # Read the temperature from the Notecard’s temperature # sensor. The Notecard captures a new temperature sample every # five minutes. def temp(self): temp_req = {"req": "card.temp"} temp_rsp = self.card.Transaction(temp_req) return temp_rsp["value"] # Generate a random humidity that’s close to an average # indoor humidity reading. def humidity(self): return round(random.uniform(45, 50), 4)
"""Create a Car class that has the following characteristics: 1. It has a gas_level attribute. 2. It has a constructor (__init__ method) that takes a float representing the initial gas level and sets the gas level of the car to this value. 3. It has an add_gas method that takes a single float value and adds this amount to the current value of the gas_level attribute. 4. It has a fill_up method that sets the car’s gas level up to 13.0 by adding the amount of gas necessary to reach this level. It will return a float of the amount of gas that had to be added to the car to get the gas level up to 13.0. However, if the car’s gas level was greater than or equal to 13.0 to begin with, then it doesnt’t need to add anything and it simply returns a 0. """ class Car: def __init__(self, gas_level: float): self.gas_level = gas_level def add_gas(self, amount): self.gas_level += amount return self.gas_level def fill_up(self): if self.gas_level >= 13.0: return 0 else: amount_of_gas_necessary = 13.0 - self.gas_level return amount_of_gas_necessary example_car = Car(9) print(example_car.fill_up())
import numpy as np class Solver(): def __init__(self, dim): self.dim = dim self.queen_pos = [] #saves x and y coordinate of each queen self.solution_map = np.zeros((dim, dim)) #I found 5 different patterns to place queens depending of dimension if dim%2 != 0 and dim%3 != 0: # 5 7 11 13 17 19 23 25 self.sol__not_mod2_and_not_mod3() if dim%2 == 0 and (dim-2)%3 != 0: # 4 6 10 12 16 18 22 24 self.sol__mod2_and_not_m2_mod3() if (dim-2)%6 == 0: # 8 14 20 26 self.sol__m2_mod6() if (dim-9)%12 == 0: # 9 21 self.sol__m9_mod12() if (dim-3)%12 == 0: # 15 27 self.sol__m3_mod12() for i in self.queen_pos: #put queen in board self.solution_map[i[0], i[1]] = 1 self.print_map() def print_map(self): for i in self.solution_map: res = "|" for j in i: res += " " if j == 0 else "X" res += "|" print(res) print("-"*(self.dim+2)) #putting queens like stairs means that queen placement follows this pattern : # +1,+1,+1 for x and +2,+2,+2 for y #put queens like stairs starting at 0,0 def sol__not_mod2_and_not_mod3(self): for i in range(0,self.dim): self.queen_pos.append([i,(i*2)%(self.dim)]) #put queens like stairs starting at 0,1 def sol__mod2_and_not_m2_mod3(self): for i in range(0,self.dim): self.queen_pos.append([i,(i*2+1)%(self.dim+1)]) #put half queens like stairs starting at 0,1 #put 3 queens at specific location #put the rest like stairs starting at queen//2+2,6 def sol__m2_mod6(self): for i in range(0,self.dim//2): self.queen_pos.append([i,(i*2+1)%(self.dim+1)]) self.queen_pos.append([self.dim//2+1,0]) self.queen_pos.append([self.dim//2,2]) self.queen_pos.append([self.dim-1,4]) for i in range(self.dim//2+3, self.dim): self.queen_pos.append([i-1,(i*2+1)%(self.dim+1)]) return 1 #put half queens minus 1 like stairs starting at 0,2 #put two queens at specific location #put the rest with this pattern : -1,+3,-1,+3,-1 for x and +2,+2,+2 for y starting at queen//2+1,2 def sol__m9_mod12(self): for i in range(0,self.dim//2-1): self.queen_pos.append([i,i*2+2]) self.queen_pos.append([self.dim//2-1,0]) self.queen_pos.append([self.dim-1,self.dim-1]) for i in range(0, self.dim//2): self.queen_pos.append([(i-(i%2)+(i-1)%2)+self.dim//2,i*2+1]) return 1 #put half queens like stairs starting at 0,2 #put one queen at specific location #put the rest with this pattern : -1,+3,-1,+3,-1 for x and +2,+2,+2 for y starting at queen//2+1,2 def sol__m3_mod12(self): for i in range(0,self.dim//2): self.queen_pos.append([i,i*2+2]) self.queen_pos.append([self.dim-2,0]) for i in range(0, self.dim//2): self.queen_pos.append([(i-(i%2)+(i-1)%2)+self.dim//2,i*2+1]) return 1
import numpy as np import cv2 #from matplotlib import pyplot as plt import gdal import osr from gdalconst import * import time import sys import os def pixel2coord(ds, x, y): """Returns global coordinates to pixel center using base-0 raster index""" ''' GeoTransform() returns a tuple where (X, Y) are corner coordinates of the image indicating the origin of the array, i.e. data element[0,0]. But, which corner? If deltaX is positive, X is West. Otherwise, X is East. If deltaY is positive, Y is South. Otherwise, Y is North. In other words, when both deltaX and deltaY is positive, (X, Y) is the lower-left corner of the image. It is also common to have positive deltaX but negative deltaY which indicates that (X, Y) is the top-left corner of the image. There are several standard notations for SRS, e.g. WKT, Proj4, etc. GetProjection() returns a WKT string. The meaning and unit-of-measurement for X, Y, deltaX and deltaY are based on the spatial reference system (SRS) of the image. For example, if the SRS is Stereographic projection, they are in kilometres. ''' ulx, xres, xskew, uly, yskew, yres = ds.GetGeoTransform()#(X, deltaX, rotation, Y, rotation, deltaY) = ds.GetGeoTransform() xp = xres * x + ulx #+ b * y yp = yres * y + uly #d * x return(xp, yp) def distance(x1, y1, x2, y2): return ((x1-x2)**2+(y1-y2)**2)**(0.5) def getExtension(extn): if (extn == "HFA"): return ".img" elif (extn == "ENVI"): return ".hdr" elif (extn == "VRT"): return ".vrt" elif (extn == "ELAS"): return "" elif (extn == "NITF"): return ".ntf" elif (extn == "GPKG"): return ".gpkg" elif (extn == "ERS"): return ".ers" else: return ".tif" def gdal_register(outimgloc, inputimgloc, refimgloc, iplist, reflist, outformat, outorder, outintp, downscale, tolerance, min_gcps, proj_type = "ref"): if len(iplist)==0: print("NO GCPs to translate with.") return extn = getExtension(outformat) command = "gdal_translate -of " + str(outformat)+ " " inputimg = gdal.Open(inputimgloc, GA_ReadOnly) if inputimg is None: print("FAILED TO IMPORT INPUT IMAGE") else: print("INPUT IMAGE IMPORTED") #refIMAGE = gdal.Open("112_53_a_22oct12.img", GA_ReadOnly) refimg = gdal.Open(refimgloc, GA_ReadOnly) if refimg is None: print("FAILED TO IMPORT REFERENCE IMAGE") else: print("REFERENCE IMAGE IMPORTED") print(proj_type) if(proj_type=="Reference Image"): inSRS = refimg.GetProjection() print("***PROJ SYSTEM: REF IMG") elif(proj_type=="Input Image"): inSRS = inputimg.GetProjection() print("***PROJ SYSTEM: INP IMG") else: inSRS = refimg.GetProjection() print("ELSE INVOKED *********") inSRS_converter = osr.SpatialReference() inSRS_converter.ImportFromWkt(inSRS) inSRS_forPyProj = inSRS_converter.ExportToProj4() adcmd = "-a_srs \"" + str(inSRS_forPyProj) + "\" " command = command + adcmd for i in range(len(iplist)): refx, refy = pixel2coord(refimg, downscale*reflist[i][0], downscale*reflist[i][1]) adcmd = "-gcp " + str(int(downscale*iplist[i][0])) + " " + str(int(downscale*iplist[i][1])) + " " + str(refx) + " " + str(refy)+ " " command = command + adcmd command = command + " " + (inputimgloc) + " temp" + extn print(command) os.system(command) print("GCPs added Successfully.") print("WARP STARTS") filename = os.path.basename(inputimgloc)[:-4] cmd2 = "gdalwarp -of " + outformat + \ " -r " + outintp + \ " -order " + outorder + \ " -refine_gcps " + str(tolerance) + " " + str(min_gcps) + \ " -co COMPRESS=NONE temp" + extn + \ " \"" + \ str(outimgloc) + "/" + filename + extn + "\"" print(cmd2) os.system(cmd2) os.system("del temp.tif") #os.system("gdalinfo " + inputimgloc +" > log.txt") print("WARP COMPLETE") def pointsFromMatches(kp1, kp2, matches): pairsOfKp1 = [i[0].queryIdx for i in matches] pairsOfKp2 = [i[0].trainIdx for i in matches] sP = cv2.KeyPoint_convert(kp1, pairsOfKp1) dP = cv2.KeyPoint_convert(kp2, pairsOfKp2) return sP, dP def drawcv(imagename, img3): screen_res = 1920, 1080 scale_width = screen_res[0] / img3.shape[1] scale_height = screen_res[1] / img3.shape[0] scale = min(scale_width, scale_height) window_width = int(img3.shape[1] * scale) window_height = int(img3.shape[0] * scale) cv2.namedWindow(imagename, cv2.WINDOW_NORMAL) cv2.resizeWindow(imagename, window_width, window_height) cv2.imshow(imagename, img3) def draw2cv(imagename, imgA, imgB): imgAx = len(imgA[0]) imgAy = len(imgA) imgBx = len(imgB[0]) imgBy = len(imgB) imgA = cv2.resize(imgA, (imgBx, imgBy)) img = np.hstack((imgA, imgB)) drawcv(imagename, img) #plt.imshow(img) #plt.show() def correlate(img, template): w, h = template.shape[::-1] # All the 6 methods for comparison in a list #methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', # 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'] #for meth in methods: meth = 'cv2.TM_SQDIFF_NORMED' method = eval(meth) # Apply template Matching res = cv2.matchTemplate(img,template,method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) #print("correlate called") # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: return min_val else: return max_val #bottom_right = (top_left[0] + w, top_left[1] + h) #cv2.rectangle(img,top_left, bottom_right, 255, 2) #drawcv(img) #cv2.destroyAllWindows()
# Given two binary trees, write a function to check if they are equal or not. # Two binary trees are considered equal if they are structurally identical and the nodes have the same value. class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ return (p and q and p.val == q.val and \ self.isSameTree(p.left, q.left) and \ self.isSameTree(p.right, q.right)) or \ (not p and not q)
# https://leetcode.com/problems/encode-and-decode-tinyurl/description/ class Codec: def __init__(self): self.encode_map = dict() self.decode_map = dict() def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ if longUrl in self.encode_map: return self.encode_map[longUrl] id = len(self.encode_map) + 1 self.encode_map[longUrl] = id self.decode_map[id] = longUrl return str(id) def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ shortUrl = int(shortUrl) if shortUrl in self.decode_map: return self.decode_map[shortUrl] return '' # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
# https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return curr, next = head, head.next while next: while next and next.val == curr.val: next = next.next if not next: break curr.next = next curr = curr.next next = curr.next curr.next = next return head
# https://leetcode.com/problems/island-perimeter/ class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid: return 0 self.number_of_rows = len(grid) self.number_of_columns = len(grid[0]) self.visited = set() self.perimeter = 0 self.dfs(grid, 0, 0) # count the bottom borders of the bottom islands for j in range(self.number_of_columns): if grid[self.number_of_rows-1][j]: self.perimeter += 1 # count the right borders of the rightmost islands for i in range(self.number_of_rows): if grid[i][self.number_of_columns-1]: self.perimeter += 1 return self.perimeter def dfs(self, grid, i, j): if i >= self.number_of_rows or j >= self.number_of_columns: return if (i,j) in self.visited: return self.visited.add((i,j)) # add node to our set of visited nodes node = grid[i][j] original_perimeter = self.perimeter if not node: # current node is water if j-1 >= 0 and grid[i][j-1]: # node to your left is land self.perimeter += 1 if i-1 >= 0 and grid[i-1][j]: # node to your top is land self.perimeter += 1 else: # current node is land if j-1 < 0 or not grid[i][j-1]: # node to your left is water self.perimeter += 1 if i-1 < 0 or not grid[i-1][j]: # node to your top is water self.perimeter += 1 # print 'At island[', i, '][', j, '], counted ', self.perimeter - original_perimeter, ' sides!' self.dfs(grid, i, j+1) # dfs to the right self.dfs(grid, i+1, j) # dfs to the bottom # DFS? # Remeber to keep track of visited nodes! # Start at one node --> check left and top # If you're water # If water is on your left --> dont do anything # Else --> perimeter++ # # If water is on your top --> dont do anything # Else --> perimeter++ # If you're land # If water is on your left --> perimeter++ # Else --> dont do anything # # If water is on your top --> perimeter++ # Else --> dont do anything # DFS to the right # DFS to the bottom # At the very end, count the bottom borders of the rectangle
# https://leetcode.com/problems/battleships-in-a-board/description/ class Solution(object): def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ self.visited = set() count = 0 for r in range(len(board)): for c in range(len(board[r])): if board[r][c] == 'X' and (r,c) not in self.visited: # traverse through entire battleship at this point, marking each node in battleship as "visited" self.dfs(board, r, c) count += 1 return count def dfs(self, board, r, c): if (r,c) in self.visited: return if r < 0 or r >= len(board): return if c < 0 or c >= len(board[r]): return if board[r][c] == '.': return self.visited.add((r,c)) self.dfs(board, r-1, c) # traverse up self.dfs(board, r+1, c) # traverse down self.dfs(board, r, c-1) # traverse left self.dfs(board, r, c+1) # traverse right
# https://leetcode.com/problems/pascals-triangle-ii/discuss/ class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ if rowIndex == 0: return [1] if rowIndex == 1: return [1,1] res = [1] prevRow = self.getRow(rowIndex-1) for i in xrange(len(prevRow)-1): res += [prevRow[i]+prevRow[i+1]] res += [1] return res
# https://leetcode.com/problems/print-binary-tree/description/ # 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 printTree(self, root): """ :type root: TreeNode :rtype: List[List[str]] """ if not root: return [] m = self.getHeight(root) n = (2**m) - 1 result = [['' for col in range(n)] for row in range(m)] self.fillResultTree(result, root, 0, 0, n) return result def fillResultTree(self, result, root, level, leftBound, rightBound): if not root: return if leftBound == rightBound: return rootIndex = (leftBound + rightBound) // 2 result[level][rootIndex] = str(root.val) self.fillResultTree(result, root.left, level+1, leftBound, rootIndex) self.fillResultTree(result, root.right, level+1, rootIndex+1, rightBound) def getHeight(self, root): if not root: return 0 return 1 + max(self.getHeight(root.left), self.getHeight(root.right))
# https://leetcode.com/problems/longest-univalue-path/description/ # 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 longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 return self.longestPath(root) def longestPath(self, root): if not root: return 0 usingRoot = self.calculateLongestPath(root.left, root.val) + self.calculateLongestPath(root.right, root.val) usingRootLeft = self.longestPath(root.left) usingRootRight = self.longestPath(root.right) return max(usingRoot, usingRootLeft, usingRootRight) def calculateLongestPath(self, root, val): if not root: return 0 if root.val != val: return 0 return 1 + max(self.calculateLongestPath(root.left, val), self.calculateLongestPath(root.right, val))