text
stringlengths
37
1.41M
# Given an array of integers A with even length, return true if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2. # # # # # # # # # # #   # Example 1: # # # Input: A = [3,1,3,6] # Output: false # # # Example 2: # # # Input: A = [2,1,2,6] # Output: false # # # Example 3: # # # Input: A = [4,-2,2,-4] # Output: true # Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4]. # # # Example 4: # # # Input: A = [1,2,4,16,8,4] # Output: false # # #   # Constraints: # # # 0 <= A.length <= 3 * 104 # A.length is even. # -105 <= A[i] <= 105 # # class Solution: def canReorderDoubled(self, A): """ :type A: List[int] :rtype: bool """ A.sort() dict = {} for i in A: dict[i] = dict.get(i, 0) + 1 while True: tmp_list = [i for i in dict if dict[i] > 0] if len(tmp_list) == 0: break tmp = min(tmp_list) dict[tmp] -= 1 if tmp * 2 in dict and dict[tmp*2] > 0: dict[tmp*2] -= 1 elif tmp / 2 in dict and dict[tmp/2] > 0: dict[tmp/2] -= 1 else: return False return True
# -*- coding:utf-8 -*- # Given a string s, return the longest palindromic substring in s. # #   # Example 1: # # # Input: s = "babad" # Output: "bab" # Note: "aba" is also a valid answer. # # # Example 2: # # # Input: s = "cbbd" # Output: "bb" # # # Example 3: # # # Input: s = "a" # Output: "a" # # # Example 4: # # # Input: s = "ac" # Output: "a" # # #   # Constraints: # # # 1 <= s.length <= 1000 # s consist of only digits and English letters (lower-case and/or upper-case), # # class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ new_s = [] for char in s: new_s.append('#') new_s.append(char) new_s.append('#') max_right = 0 pos = 0 max_len = 0 radius = [0 for _ in xrange(len(new_s))] for i, char in enumerate(new_s): if i < max_right: radius[i] = min(radius[pos-(i-pos)], max_right - i) else: radius[i] = 1 # Expand radius[i] self.expand(radius, i, new_s) # Update max_right, pos if i + radius[i] - 1 > max_right: max_right = i + radius[i] - 1 pos = i # Update max_len if max_len < radius[i]: max_len = radius[i] mid = i max_len = max_len - 1 start = (mid - 1) // 2 - (max_len - 1) // 2 return s[start:start + max_len] def expand(self, radius, i, s): while i - radius[i] >= 0 and i + radius[i] < len(s) and s[i-radius[i]] == s[i+radius[i]]: radius[i] += 1
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. # # Note: For the purpose of this problem, we define empty string as valid palindrome. # # Example 1: # # # Input: "A man, a plan, a canal: Panama" # Output: true # # # Example 2: # # # Input: "race a car" # Output: false # # #   # Constraints: # # # s consists only of printable ASCII characters. # # class Solution: def isPalindrome(self, s: str) -> bool: x=''.join(str for str in s if (str.isalpha() or str.isdigit())) return x.lower()==x[::-1].lower()
# -*- coding:utf-8 -*- # A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. # # Write a data structure CBTInserter that is initialized with a complete binary tree and supports the following operations: # # # CBTInserter(TreeNode root) initializes the data structure on a given tree with head node root; # CBTInserter.insert(int v) will insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode; # CBTInserter.get_root() will return the head node of the tree. # # # # # # #   # # Example 1: # # # Input: inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]] # Output: [null,1,[1,2]] # # # # Example 2: # # # Input: inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]] # Output: [null,3,4,[1,2,3,4,5,6,7,8]] # # # #   # # Note: # # # The initial given tree is complete and contains between 1 and 1000 nodes. # CBTInserter.insert is called at most 10000 times per test case. # Every value of a given or inserted node is between 0 and 5000. # # # # # #   # #   # # # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class CBTInserter(object): def __init__(self, root): """ :type root: TreeNode """ l = [] s = [root] while s: tmp = s.pop(0) l.append(tmp.val) if tmp.left: s.append(tmp.left) if tmp.right: s.append(tmp.right) self.head = None self.queue = [] self.parent = [] for i in l: if self.head is None: self.head = TreeNode(i) self.queue.append(0) self.queue.append(1) self.parent.append(self.head) self.parent.append(self.head) else: node = self.queue.pop(0) par = self.parent.pop(0) if node == 0: par.left = TreeNode(i) self.parent.append(par.left) self.parent.append(par.left) elif node == 1: par.right = TreeNode(i) self.parent.append(par.right) self.parent.append(par.right) self.queue.append(0) self.queue.append(1) def insert(self, v): """ :type v: int :rtype: int """ if self.head is None: self.head = TreeNode(v) return None else: node = self.queue.pop(0) par = self.parent.pop(0) if node == 0: par.left = TreeNode(v) self.parent.append(par.left) self.parent.append(par.left) elif node == 1: par.right = TreeNode(v) self.parent.append(par.right) self.parent.append(par.right) self.queue.append(0) self.queue.append(1) return par.val def get_root(self): """ :rtype: TreeNode """ return self.head # Your CBTInserter object will be instantiated and called as such: # obj = CBTInserter(root) # param_1 = obj.insert(v) # param_2 = obj.get_root()
# Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once. # # 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. # # Return the latest 24-hour time in "HH:MM" format.  If no valid time can be made, return an empty string. # #   # Example 1: # # # Input: A = [1,2,3,4] # Output: "23:41" # Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest. # # # Example 2: # # # Input: A = [5,5,5,5] # Output: "" # Explanation: There are no valid 24-hour times as "55:55" is not valid. # # # Example 3: # # # Input: A = [0,0,0,0] # Output: "00:00" # # # Example 4: # # # Input: A = [0,0,1,0] # Output: "10:00" # # #   # Constraints: # # # arr.length == 4 # 0 <= arr[i] <= 9 # # class Solution: def largestTimeFromDigits(self, A): """ :type A: List[int] :rtype: str """ import itertools tmp = list(itertools.permutations(A,4)) tmp = [1000 * i[0] + 100 * i[1] + 10 * i[2] + i[3] for i in tmp] tmp.sort() tmp = tmp[::-1] for i in tmp: time = str(i) if len(time) < 4: time = '0' * (4 - len(time)) + time hour = int(time[:2]) minute = int(time[2:]) if 0 <= hour <= 23 and 0 <= minute <= 59: return time[:2] + ':' + time[2:] return ''
# You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. # #   # Example 1: # # # Input: nums = [5,2,6,1] # Output: [2,1,1,0] # Explanation: # To the right of 5 there are 2 smaller elements (2 and 1). # To the right of 2 there is only 1 smaller element (1). # To the right of 6 there is 1 smaller element (1). # To the right of 1 there is 0 smaller element. # # #   # Constraints: # # # 0 <= nums.length <= 10^5 # -10^4 <= nums[i] <= 10^4 # # class Solution: def countSmaller(self, nums): res = [0] * len(nums) T = BinarySearchTree() for i in range(len(nums)-1, -1, -1): res[i] = T.insert(nums[i]) return res class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None self.count = 1 self.left_smaller = 0 class BinarySearchTree: def __init__(self): self.root = None def insert(self, val): count = 0 if self.root is None: self.root = TreeNode(val) return count root = self.root while root: if val > root.val: count += root.count + root.left_smaller if root.right is None: root.right = TreeNode(val) break else: root = root.right elif val < root.val: root.left_smaller += 1 if root.left is None: root.left = TreeNode(val) break else: root = root.left elif val == root.val: count += root.left_smaller root.count += 1 break return count # def countSmaller(self, nums): # def sort(enum): # half = len(enum) / 2 # if half: # left, right = sort(enum[:half]), sort(enum[half:]) # for i in range(len(enum))[::-1]: # if not right or left and left[-1][1] > right[-1][1]: # smaller[left[-1][0]] += len(right) # enum[i] = left.pop() # else: # enum[i] = right.pop() # return enum # smaller = [0] * len(nums) # sort(list(enumerate(nums))) # return smaller
# Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. # # # Note that it is the kth smallest element in the sorted order, not the kth distinct element. # # # Example: # # matrix = [ # [ 1, 5, 9], # [10, 11, 13], # [12, 13, 15] # ], # k = 8, # # return 13. # # # # Note: # You may assume k is always valid, 1 ≤ k ≤ n2. class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: if not matrix: return None import heapq h = [] heapq.heappush(h, (matrix[0][0], 0, 0)) while k > 0: result, i, j = heapq.heappop(h) if i == 0 and j + 1 < len(matrix[0]): heapq.heappush(h, (matrix[i][j+1], i, j+1)) if i + 1 < len(matrix): heapq.heappush(h, (matrix[i+1][j], i+1, j)) k -= 1 return result # search path (num means this value will be searched in #num round) # 1 2 3 4 # 2 3 4 # 3 4 # 4
# Given the root of a binary tree, calculate the vertical order traversal of the binary tree. # # For each node at position (x, y), its left and right children will be at positions (x - 1, y - 1) and (x + 1, y - 1) respectively. # # The vertical order traversal of a binary tree is a list of non-empty reports for each unique x-coordinate from left to right. Each report is a list of all nodes at a given x-coordinate. The report should be primarily sorted by y-coordinate from highest y-coordinate to lowest. If any two nodes have the same y-coordinate in the report, the node with the smaller value should appear earlier. # # Return the vertical order traversal of the binary tree. # #   # Example 1: # # # Input: root = [3,9,20,null,null,15,7] # Output: [[9],[3,15],[20],[7]] # Explanation: Without loss of generality, we can assume the root node is at position (0, 0): # The node with value 9 occurs at position (-1, -1). # The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2). # The node with value 20 occurs at position (1, -1). # The node with value 7 occurs at position (2, -2). # # Example 2: # # # Input: root = [1,2,3,4,5,6,7] # Output: [[4],[2],[1,5,6],[3],[7]] # Explanation: The node with value 5 and the node with value 6 have the same position according to the given scheme. # However, in the report [1,5,6], the node with value 5 comes first since 5 is smaller than 6. # #   # Constraints: # # # The number of nodes in the tree is in the range [1, 1000]. # 0 <= Node.val <= 1000 # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: node_map = {root.val: (0, 0)} queue = [root] while queue: node = queue.pop(0) if node.left: queue.append(node.left) node_map[node.left.val] = (node_map[node.val][0] - 1, node_map[node.val][1] - 1) if node.right: queue.append(node.right) node_map[node.right.val] = (node_map[node.val][0] + 1, node_map[node.val][1] - 1) sorted_x = sorted(node_map.keys(), key = lambda x: (node_map[x][0], -node_map[x][1], x)) res = [] tmp = [] for i in sorted_x: if len(tmp) == 0 or node_map[i][0] == node_map[tmp[-1]][0]: tmp.append(i) else: res.append(tmp) tmp = [i] res.append(tmp) return res
""" Lambidas são funções em nome - funções anônimas #lambida lambda x: 3 * x + 1 #Como utilizar a expressão lambida calc = lambda x: 3 * x + 1 print(calc(4)) # Expressão Lambida com multiplas entradas nome_completo = lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title() print(nome_completo('Francisco', 'Ricardo')) print(nome_completo(' FRANCISCO ', ' Ricardo ')) #lambidas sem entrada amar = lambda : 'Como não amar Python? ' uma = lambda x: 3 * x + 1 duas = lambda x, y: (x * y) ** 0.5 tres = lambda x, y, z: 3 / (1 / x + 1 / y + 1 / z) print(amar()) print(uma(6)) print(duas(5, 7)) print(tres(3, 6, 9)) autores = ['Francisco Ricardo', 'Daniel Neto', 'Joel Filho', 'Carolinie R. Betesek', 'A. C. Souza', 'Danielle Rufino Alves'] print(autores) autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) """ #Função Quadratica # f(x) = a * x ** 2 + b * x + c #Definindo a Função def geradora_funcao_quadratica(a, b, c): """ Retorna a função f(x) = a * x ** 2 + b * x + c""" return lambda x: a * x ** 2 + b * x + c teste = geradora_funcao_quadratica(2, 3, -5) print(teste(0)) print(teste(1)) print(teste(2))
""" raise => lança exceções raise TipoDoError('Menssagem de Error') """ #Exemplo def colore(texto, cor): if type(texto) is not str: raise TypeError('O Texto precisa ser uma string') if type(cor) is not str: raise TypeError('A cor precisa ser uma string') print(f'O texto {texto} será impresso na cor {cor}') colore(True, 'Vermelho')
""" List Comprehension Podemos adicionar estruturas condicionais lógicas as nossas list comprehension """ #Exemplo #1 numeros = [1, 2, 3, 4, 5, 6] pares = [numero for numero in numeros if numero % 2 == 0] impares = [numero for numero in numeros if numero % 2 != 0] print(numeros) print(pares) print(impares) # Refatorando #Qualquer numero par módulo de 2 é 0 e o 0 em Python e False. not False = True pares = [numero for numero in numeros if not numero % 2] impares = [numero for numero in numeros if numero % 2] print(pares) print(impares) #2 res = [numero * 2 if numero % 2 == 0 else numero / 2 for numero in numeros] print(res)
""" print("Qual é Seu nome?") nome = input() # print('Seja Bem-Vindo(a) %s' % nome.upper()) # print('Seja Bem-Vindo(a) {0}' .format(nome.upper())) print(f'Seja Bem-Vindo(a) {nome.title()}') ano = input('Em que ano você nasceu ? \n') print(f'Sua idade é {2020 - int(ano)} anos') numero = range(1, 10) nome = 'Francisco' for letra in enumerate(nome): print(letra[1]) for letra in range(11): print(letra) for letra in range(1, 11): print(letra) for letra in range(1, 11, 3): print(letra) for letra in range(11, 0, -1): print(letra) """ for letra in range(11, 0, -1): print(letra)
__author__ = 'ddow' """ Notes on creating a form letter. Continuing from almost the same file from last week. This time, Dan was at the computer. """ # We explore three ways of filling data into a form letter. name, units, item, unitprice = 'Customer', 20, 'turtles', 40.2 total = units * unitprice signature = 'Sarah Palindrome' TEMPLATE1 = """ Dear {}, Thanks for your order of {} {} at a unit price of {}. Your total bill will be {}, payable at your convenience. You may order more {} any time. Downtown Billing, {} """ LetterA = TEMPLATE1.format(name,units,item,unitprice,total,item,signature) print(LetterA) # NOTE THE FORMAT FOR {total:} It gives two decimals and uses commas for big numbers # Using keywords TEMPLATE2 = """ Dear {name:}, Thanks for your order of {units:} {item:} at a price of ${unitprice:0.02f}. Your total will be ${total:0,.02f}, payable at your convenience. You may order more {item:} any time. Downtown Billing, {signed:} ------------------------------------------------------------------------ """ LetterB = TEMPLATE2.format(item='turtles', units=40, name='customer', unitprice=60.2, signed='Sara Palindrome', total=units*unitprice) print(LetterB) # dictionary d = dict() d['name']='Customer' d['item']='pythons' d['units']=20 d['unitprice']=120.50 d['signed']='Sarah Palindrome' d['total']=d['units']*d['unitprice'] LetterC = TEMPLATE2.format(**d) print(LetterC)
""" Dynamic programming by memoization """ def lcs_by_memoization(str1, str2, len_str1, len_str2, arr): if arr[len_str1][len_str2] != -1: return arr[len_str1][len_str2] else: if len_str1 == 0 or len_str2 == 0: arr[len_str1][len_str2] = 0 elif str1[len_str1-1] == str2[len_str2-1]: arr[len_str1][len_str2] = 1 + lcs_by_memoization(str1, str2, len_str1-1, len_str2-1, arr) else: arr[len_str1][len_str2] = max(lcs_by_memoization(str1, str2, len_str1-1, len_str2, arr), lcs_by_memoization(str1, str2, len_str1, len_str2-1, arr)) return arr[len_str1][len_str2] """ Dynamic programming by bottom up """ def lcs_bottom_up_approach(str1, str2): len1 = len(str1) len2 = len(str2) arr = [[None]*(len2+1) for _ in range(len1+1)] for cntr1 in range(len1+1): for cntr2 in range(len2+1): if cntr1 == 0 or cntr2 == 0: arr[cntr1][cntr2] = 0 elif str1[cntr1-1] == str2[cntr2-1]: arr[cntr1][cntr2] = 1 + arr[cntr1-1][cntr2-1] else: arr[cntr1][cntr2] = max(arr[cntr1-1][cntr2],arr[cntr1][cntr2-1]) return arr[len1][len2] X = "AGGTAB" Y = "GXTXAYB" # X = "ACCGGTCGAGTGCGCGGAAGCCGGCCGAA" # Y = "GTCGTTCGGAATGCCGTTGCTCTGTAAA" arr = [[-1 for y in range(len(Y)+1)] for x in range(len(X)+1)] print( "lcs_by_memoization: ", lcs_by_memoization(X , Y, len(X), len(Y), arr)) print( "lcs_by_memoization: ", lcs_bottom_up_approach(X , Y))
class BSTNode: data = None parent = None left = None right = None def __init__(self, data=None): self.data = data class BinarySearchTree: def __init__(self): self.root = None self.data_string = "" def insert(self, data=None): new_node = BSTNode(data) y = x = self.root while x != None: y = x if new_node.data < x.data: x = x.left else: x = x.right new_node.parent = y if y == None: self.root = new_node elif new_node.data < y.data: y.left = new_node else: y.right = new_node def in_order(self, node=None): if node != None: self.in_order(node.left) self.data_string += str(node.data) +", " self.in_order(node.right) return self.data_string; def pre_order(self, node=None): if node != None: self.data_string += str(node.data) +", " self.pre_order(node.left) self.pre_order(node.right) return self.data_string; def post_order(self, node=None): if node != None: self.post_order(node.left) self.post_order(node.right) self.data_string += str(node.data) +", " return self.data_string; def tree_walk(self, order): self.data_string = "" if order == "IN": return self.in_order(self.root) elif order == "PRE": return self.pre_order(self.root) elif order == "POST": return self.post_order(self.root) def __transplant(self, u, v): if u.parent == None: self.root = v elif u == u.parent.left: u.parent.left = v else: u.parent.right = v if v != None: v.parent = u.parent def minimum(self, node): while node.left != None: node = node.left return node def maximum(self, node): while node.right != None: node = node.right return node def __delete_node(self, node): if node.left == None and node.right == None: if node == node.parent.left: node.parent.left = None else: node.parent.right = None return if node.left == None: self.__transplant(node, node.right) elif node.right == None: self.__transplant(node, node.left) else: y = self.minimum(node.right) if y.parent != node: self.__transplant(y, y.right) y.right = node.right y.right.parent = y self.__transplant(node, y) y.left = node.left y.left.parent = y def __search_node(self, data_node): return_node = None if self.root != None: current = self.root while current != None: if current.data < data_node.data: current = current.right elif current.data > data_node.data: current = current.left else: return_node = current break return return_node def search_data(self, data): return self.__search_node(BSTNode(data)) != None def remove_data(self, data): data_node = self.__search_node(BSTNode(data)) if data_node != None: self.__delete_node(data_node) else: print("Data not found") def __find_successor(self, data_node): if data_node.right != None: return self.minimum(data_node) y = data_node.parent while y != None and data_node == y.right: data_node = y y = y.parent return y def successor(self, data): data_node = self.__search_node(BSTNode(data)) if data_node != None: return self.__find_successor(data_node) else: print("Data not found") def __find_predecessor(self, data_node): if data_node.left != None: return self.maximum(data_node) y = data_node.parent while y != None and data_node == y.left: data_node = y y = y.parent return y def predecessor(self, data): data_node = self.__search_node(BSTNode(data)) if data_node != None: return self.__find_predecessor(data_node) else: print("Data not found")
""" 作者:北辰 功能:模拟掷骰子 版本:2.0 日期:05/07/2018 2.0新增功能:模拟投掷两个骰子 """ import random def roll_dice(): """ 模拟掷骰子 """ roll = random.randint(1,6) return roll def main(): """ 主函数 """ total_times = 10000 # 初始化次数列表 result_list = [0] * 11 # 初始化点数列表 roll_list = list(range(2,13)) # 结果字典 roll_dict = dict(zip(roll_list,result_list)) # zip()函数将两个列表转换为一个元组 for i in range(total_times): roll1 = roll_dice() roll2 = roll_dice() for j in roll_list: if roll1+roll2 == j: roll_dict[j]+=1 for i,result in roll_dict.items(): print('点数为{}的次数为:{},频率为{}'.format(i,result,result/total_times)) if __name__=='__main__': main()
import random from time import time from sys import getsizeof random.seed(50) def is_prime(n): """ Return True if n is prime else False """ for i in range(2, n//2 + 1): if n % i == 0: return False return True def get_prime(start, count=1, step=1, multiplier=False): """ Returns Prime Number Generator :param start: int -- Starting number to find next prime :param count: int -- Number of primes required (default 1) :param step: int -- Increment number after prime is found, when count > 1 (default 1) :param multiplier: boolean -- Step as multiplier or adder (default False) :return: Generator -- Prime Number Generator """ i = 0 number = start if is_prime(number): number += step while count > i: while True: if number < 2: return if is_prime(number): i += 1 yield number if multiplier: number = number * step + 1 else: number += step break if multiplier: number += 1 else: number += step def linear_insert(table, data): insert_fail = 0 collision = [] size = len(table) for val in data: n = 0 while size > n: key = (val + n) % size if table[key] is None: table[key] = val break else: n += 1 else: insert_fail += 1 collision.append(n) return table, collision, insert_fail def linear_search(table, element): n = 0 size = len(table) while size > n: key = (element + n) % size if table[key] == element: return n+1, key, 'F' else: n += 1 return n, -1, 'NF' def quadratic_insert(table, data): insert_fail = 0 collision = [] size = len(table) stop_size = size//2 for val in data: n = 0 while stop_size > n: key = (val + n*n) % size if table[key] is None: table[key] = val break else: n += 1 else: insert_fail += 1 collision.append(n) return table, collision, insert_fail def quadratic_search(table, element): n = 0 size = len(table) while size > n: key = (element + n * n) % size if table[key] == element: return n+1, key, 'F' else: n += 1 return n, -1, 'NF' def d_hash_insert(table, data): insert_fail = 0 collision = [] size = len(table) prime = next(get_prime(size, 1, -1)) for val in data: n = 0 key = val % size if table[key] is None: table[key] = val else: n = 1 offset = prime - val % prime while n < size: key = (key + offset) % size if table[key] is None: table[key] = val break else: n += 1 else: insert_fail += 1 collision.append(n) return table, collision, insert_fail def d_hash_search(table, element): size = len(table) n = 0 prime = next(get_prime(size, 1, -1)) key = element % size if table[key] == element: return n+1, key, 'F' else: n = 1 offset = prime - element % prime while size > n: key = (key + offset) % size if table[key] == element: return n+1, key, 'F' else: n += 1 return n, -1, 'NF' def rehash_insert(table, data): size = len(table) collision = [0] * len(data) stop_size = size//2 for i, val in enumerate(data): n = 0 if i > len(table)//2: table = [None] * next(get_prime(2*len(table), 1, 1)) size = len(table) stop_size = size//2 _, prior_collision, _ = quadratic_insert(table, data[:i]) for index, count in enumerate(prior_collision): collision[index] += count while stop_size > n: key = (val + n*n) % size if table[key] is None: table[key] = val break else: n += 1 collision[i] += n return table, collision, 0 def rehash_search(table, element): n = 0 size = len(table) while size > n: h = (element + n*n) % size if table[h] == element: return n+1, h, 'F' n += 1 return n, -1, 'NF' def cuckoo_insert(table, data): size = len(table) collisions = [0] * len(data) while True: insert_failed = False hashed = {} next_prime = next(get_prime(size)) for val in data: hashed[val] = [val % size, (val*next_prime) % size] table1 = [None] * size table2 = [None] * size for i, val in enumerate(data): element_to_insert = val count = 0 while element_to_insert: first = hashed[element_to_insert][0] if table1[first] is None: table1[first] = element_to_insert element_to_insert = None else: count += 1 element_to_insert, table1[first] = table1[first], element_to_insert second = hashed[element_to_insert][1] if table2[second] is None: table2[second] = element_to_insert element_to_insert = None else: count += 1 element_to_insert, table2[second] = table2[second], element_to_insert if count > 2*size: insert_failed = True break if insert_failed: index = i collisions[index] += count size = 2 * size break collisions[i] += count if not insert_failed: break return [table1, table2], collisions, 0 def cuckoo_search(table, element): comps = 0 table_size = len(table[0]) h1 = element % table_size comps += 1 if table[0][h1] == element: return comps, h1, 'F' h2 = (element * next(get_prime(table_size))) % table_size comps += 1 if table[1][h2] == element: return comps, h2, 'F' return comps, -1, 'NF' def get_time_taken(time_taken_in_sec): if time_taken_in_sec < 60: return '{:0.2f} S'.format(time_taken_in_sec) time_taken_in_min = time_taken_in_sec / 60 if time_taken_in_min < 60: return '{:0.2f} M'.format(time_taken_in_min) time_taken_in_hour = time_taken_in_min / 60 return '{:0.2f} H'.format(time_taken_in_hour) def get_table_size(table): b = getsizeof(table) b += sum(getsizeof(i) for i in table) if isinstance(table[0], list): for tab in table: b += sum(getsizeof(i) for i in tab) if b < 1024: return '{:0.2f} B'.format(b) kb = b/1024 if kb < 1024: return '{:0.2f} KB'.format(kb) mb = kb/1024 if mb < 1024: return '{:0.2f} MB'.format(mb) gb = mb/1024 return '{:0.2f} GB'.format(gb) def get_lambda_factor(table): table_size = 0 filled_slots = 0 if isinstance(table[0], list): for tab in table: table_size += len(tab) filled_slots += sum(1 for i in tab if i is not None) else: table_size = len(table) filled_slots = sum(1 for i in table if i is not None) lambda_factor = filled_slots/table_size return '{:0.6f}'.format(lambda_factor) def main(): hash_methods = [ ('Linear', linear_insert, linear_search), ('Quadratic', quadratic_insert, quadratic_search), ('Double Hash', d_hash_insert, d_hash_search), ('Rehash', rehash_insert, rehash_search), ('Cuckoo', cuckoo_insert, cuckoo_search), ] for _ in range(90): print('-', end='') print() print('HT:\t\tHashing Technique') print('\t\tL = Linear, Q = Quadratic, D = Double, R = Rehash, C = Cuckoo') print('TIF:\tTotal Insert Failed') print('SR:\t\tSearch Result -> F = Found, NF = Not Found') for _ in range(90): print('-', end='') print() print("{:13s}{:3s}{:17s}{:5s}{:10s}{:15s}{:5s}{:14s}{:8s}" .format('{:>10s}'.format("Table Size"), '{:>2s}'.format("HT"), '{:>15s}'.format("Collisions"), '{:>3s}'.format("TIF"), '{:>8s}'.format("Time"), '{:>12s}'.format("Search Comps"), '{:>3s}'.format("SR"), '{:>10s}'.format("Mem Size"), '{:>8s}'.format("\u03bb"), )) for _ in range(90): print('-', end='') print() for k in get_prime(10, 5, 20, True): data = random.sample(set(range(k * 5)), k) element_to_search = data[k-1] for p, (name, insert_method, search_method) in enumerate(hash_methods): table = [None] * k start = time() table, collision, insert_fail = insert_method(table, data) time_taken = time() - start comps, index, result = search_method(table, element_to_search) if p != 0: size = '' else: size = k print("{:13s}{:3s}{:17s}{:5s}{:10s}{:15s}{:5s}{:14s}{:8s}" .format('{:>10s}'.format(str(size)), '{:>2s}'.format(name[0]), '{:>15s}'.format(str(sum(collision))), '{:>3s}'.format(str(insert_fail)), '{:>8s}'.format(get_time_taken(time_taken)), '{:>12s}'.format(str(comps)), '{:>3s}'.format(result), '{:>10s}'.format(get_table_size(table)), '{:>8s}'.format(get_lambda_factor(table))) ) for _ in range(90): print('-', end='') print() if __name__ == '__main__': main()
import pandas as pd #https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.names # # TODO: Load up the mushroom dataset into dataframe 'X' # Verify you did it properly. # Indices shouldn't be doubled. # Header information is on the dataset's website at the UCI ML Repo # Check NA Encoding # # .. your code here .. X = pd.read_csv("Datasets/agaricus-lepiota.data", header = None) X.columns = ("label", "cap-shape", "cap-surface", "cap-color", "bruises?", "odor", "gill-attachment", "gill-spacing", "gill-size", "gill-color", "stalk-shape", "stalk-root", "stalk-surface-above-ring", "stalk-surface-below-ring", "stalk-color-above-ring", "stalk-color-below-ring", "veil-type", "veil-color", "ring-number", "ring-type", "spore-print-color", "population", "habitat") # INFO: An easy way to show which rows have nans in them print (X[pd.isnull(X).any(axis=1)]) # # TODO: Go ahead and drop any row with a nan # # .. your code here .. X = X.dropna(how = "any") print (X.shape) # # TODO: Copy the labels out of the dset into variable 'y' then Remove # them from X. Encode the labels, using the .map() trick we showed # you in Module 5 -- canadian:0, kama:1, and rosa:2 # # .. your code here .. y = X["label"] X = X.drop("label", axis = 1) y = y.map({'p':0, 'e':1}) # # TODO: Encode the entire dataset using dummies # # .. your code here .. X = pd.get_dummies(X) # # TODO: Split your data into test / train sets # Your test size can be 30% with random_state 7 # Use variable names: X_train, X_test, y_train, y_test # # .. your code here .. from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=7) # # TODO: Create an DT classifier. No need to set any parameters # # .. your code here .. from sklearn import tree DT = tree.DecisionTreeClassifier() # # TODO: train the classifier on the training data / labels: # TODO: score the classifier on the testing data / labels: # # .. your code here .. DT.fit(X_train, y_train) score = DT.score(X_test, y_test) print ("High-Dimensionality Score: ", round((score*100), 3)) # # TODO: Use the code on the courses SciKit-Learn page to output a .DOT file # Then render the .DOT to .PNGs. Ensure you have graphviz installed. # If not, `brew install graphviz. If you can't, use: http://webgraphviz.com/ # # .. your code here .. tree.export_graphviz(DT.tree_, out_file='tree.dot', feature_names=X_train.columns) from subprocess import call #call(['dot', '-T', 'png', 'tree.dot', '-o', 'tree.png'])
import streamlit as st from PIL import Image # Use this if you want a backround image # page_bg_img = ''' # <style> # body { # background-image: url("https://images.unsplash.com/photo-1542281286-9e0a16bb7366");#Put the URL in the quotes # background-size: cover; # } # </style> # ''' # st.markdown(page_bg_img, unsafe_allow_html=True) page = st.sidebar.selectbox("What Page Would you Like to Go To", ("==Select==", "Home", "Classes", "Social Media", "About Us")) if page == "==Select==": 'Select the page you want to go to in the menu on the left' elif page == "Home": 'FHS Computer Club is a club at Franklin High School in Massachussetts' '\n\n\nWe build many different projects and teach others about computer skills such as programming' 'Go to the classes tab to see more!' elif page == "Classes": "FHS Computer Club offers MANY classes to take" "Click on the checkboxes for time, date, and more" if st.checkbox("Python"): st.write(''' #Python Ah, so your interested in Python. No? Well, let me tell you about the possiblilities of Python. This website here, its built completely in Python. Python can do so much more, with a library for almost anything you can think of The classes will start as soon as enough people register, and the date/time will be decided then Instructor: Arav Tyagi(Treasurer, programmer of this website)''' ) # elif page == "Social Media": # st.markdown() # image = Image.open('pictureName.jpg') # st.image(image, width=200, # se_column_width=True)
def selection_sort(list_a): indexing_length = range(0, len(list_a)-1) # [0,1,2] for i in indexing_length: min_value = i # 0 # 1 for j in range(i+1, len(list_a)): if list_a[j] < list_a[min_value]: # 7 < 6 # 0 < 7 min_value = j if min_value != i: list_a[min_value], list_a[i] = list_a[i], list_a[min_value] print(list_a) return list_a print(selection_sort([6,7,0]))
""" CP1404/CP5632 - Practical Student: Siyan Tao Electricity_bill Create an electricity bill estimator """ TARIFF_11 = 0.244618 TARIFF_31 = 0.136928 print("Electricity bill estimator 2.0") tariff = int(input("Which tariff? 11 or 31: ")) daily_use_kwh = float(input("Enter daily use in kwh: ")) days = int(input("Enter number of billing days: ")) if tariff == 11: tariff = TARIFF_11 elif tariff == 31: tariff = TARIFF_31 bill = tariff * daily_use_kwh * days print("Estimated bill: ${:.2f}".format(bill))
""" CP1404/CP5632 - Practical Student: Siyan Tao Shop_calculator """ number_of_items = int(input("Number of items: ")) total = 0 while number_of_items <= 0: print("Invalid number of items") number_of_items = int(input("Number of items: ")) for i in range(number_of_items): price= float(input("Price of item: ")) total += price if total >100: total= total * (1-0.1) print("Total price for", number_of_items, "items is ${:.2f}".format(total))
""" CP1404 - Practical Temperature conversions """ def main(): menu ="""C - Convert Celsius to Fahrenheit\nF - Convert Fahrenheit to Celsius\nQ - Quit""" print(menu) choice = input(">>> ").upper() while choice != "Q": if choice == "C": celsius = float(input("What is your Celsius: ")) fahrenheit = celsius_to_fahrenheit(celsius) print("Result: {} F".format(fahrenheit)) elif choice == "F": fahrenheit = float(input("Wh at is your Fahrenheit: ")) celsius = fahrenheit_to_celsius(fahrenheit) print("Result: {} C".format(celsius)) else: print("Invalid option") print(menu) choice = input(">>> ").upper() print("Thank you for using.") def celsius_to_fahrenheit(celsius): return celsius * 9.0 / 5 + 32 def fahrenheit_to_celsius(fahrenheit): return 5.0 * (fahrenheit - 32) / 9 main()
# 1. # Вх: список чисел, Возвр: список чисел, где # повторяющиеся числа урезаны до одного # пример [0, 2, 2, 3] returns [0, 2, 3]. def rm_adj(nums): return list(set(nums)) # 2. Вх: Два списка упорядоченных по возрастанию, Возвр: новый отсортированный объединенный список def concat_list(list1, list2): result_list = list1 + list2 result_list.sort() return result_list if __name__ == '__main__': # task №1 print("============ task 1 ================") test = rm_adj([0, 2, 2, 3]) print(test) test = rm_adj([1, 3, 3, 4, 1, 3, 4]) print(test) test = rm_adj([30, 22, 2, 2, 1]) print(test) # task №2 print("============ task 2 ================") test = concat_list([8, 10, 242], [9, 10, 11]) print(test)
#Q1 list of songs songs = ["ROCKSTAR", "Do It", "For The Night"] #Q2 print out 1st & 2nd items in list print(songs[0]) print(songs[2]) #Q2 printed "Do It"and "For The Night" print(songs[1:3]) #Q3 update the last element songs[2] = "Treat You Better" print(songs) #Q4 three songs added songs.append("The Man") songs.extend(["Happy"]) songs.insert(0, "Musice Is My Hot Hot Sex") print(songs) #Q4 Delete a song del songs[2] print(songs) #Q6 animals = ["Cat", "Dog", "Bird"] animals.append("Rat") print(animals[2]) del animals[0] for animal in animals: print(animal)
#Herencia Múltiple - MRO #http://www.srikanthtechnologies.com/blog/python/mro.aspx class A: a = 0 def cocinando(self): print("A está cocinando") #[A] + merge(L[O], [O]) #[A, O] class B: a = 1 def cocinando(self): print("B está cocinando") class C(B): a = 2 def cocinando(self): print("C está cocinando") #[C] + merge(L[B], B) #[C] + merge([B, O], B) #[C, B, O] class D(A, B): pass #[D] + merge(L[A], L[B], [A, B]) = #[D] + merge([A, O], [B, O], [A, B]) = #[D] + [A] + merge([O], [B, O], [B]) = #[D, A] + [B] + merge([O], [O]) = #[D, A], B] + [O] = #[D, A, B, O] class E(C, D): pass #[E] + merge(L[C], L[D], [C, D]) #[E] + merge([C, B, O], [D, A, B, O], [C, D]) #[E] + [C] + merge([B, O], [D, A, B, O], [D]) #[E] + [C] + merge([B, O], [D, A, B, O], [D]) #[E] + [C] + [D] + merge([B, O], [A, B, O]) #[E] + [C] + [D] + [A] + merge([B, O], [B, O]) #[E] + [C] + [D] + [A] + [B] + merge([O], [O]) #[E] + [C] + [D] + [A] + [B] + [O] #L[E] = [E, C, D, A, B, O] # Ojito: # En algunos casos no se podra generar una linearización. # Esto ocurre en elcaso de que las cabezas de las listas se encuentren en las colas # de las otras. '''print(D().a) print(D.mro()) print(E().a) print(E.mro())''' obj = D() obj2 = E() obj.cocinando() obj2.cocinando() print(E.mro()) # En python no existe la privacidad, así que se usa: # nombres que comienzan con __ son privados (igual es posible acceder a ellos)
AlphaNum=1 for Alpha in (" Good night !!!") : print ("Letter ", AlphaNum, " is ", Alpha) AlphaNum+=1
# use while to create a loop to calculated investment # This program asks user to enter $ amount for priciple and add annual rate. # To stop the program user needs to entre SENTENIAL flag which is 0 SENTENIAL = 0 years = 1 principle = float(input('What is your principle amount invested?: ')) interestRate = float(input('What is the interest rate year ' + str(years) +' in % :')) balance=principle while interestRate !=SENTENIAL: years+=1 balance += balance*(interestRate *0.01) interestRate = float(input('What is the interest rate year ' + str(years) +' in % :')) print ('At the end of', years, 'years your investment will be ${:,.2f}'.format(balance)) averageIncome = (balance -principle)/ (years -1) print('Your average yearly income is ${:,.2f}'.format(averageIncome))
# Calculate area of triangle using while not and if else # Has UX component to goodBase = False while not goodBase: base = int(input ('Enter the base :')) if base <= 0: print ('Error - the base length must be a positive number. You entered', base) else: goodBase = True goodHeight = False while not goodHeight: height = int(input ('Enter the height :')) if height <= 0: print ('Error - the height length must be a positive number. You entered', height) else: goodHeight = True area = (base*height) / 2 print ('The area of the triangle: ', area)
#!/usr/bin/python def sum_string(str): for i in range(len(str)-2): if int(str[i])+int(str[i+1]) == int(str[i+2]): continue else: return False return True print sum_string("1234566324") print sum_string("12358") print sum_string("112358") print sum_string("01123") print sum_string("123234134124")
#!/usr/bin/python def swap(input,i,j): input[i],input[j]=input[j],input[i] def quick_sort(input,start,end): if start < end: pivot = partition(input,start,end) quick_sort(input,start,pivot-1) quick_sort(input,pivot+1,end) return input def partition(input,start,end): pivot = start left = start + 1 right = end while left < right: while (input[left] < input[pivot]) & (left < end): left = left + 1 while (input[right] > input[pivot]) & (right > start): right = right - 1 swap(input,left,right) left = left + 1 right = right - 1 swap(input,pivot,min(left,right)) return min(left,right) temp = [3,5,2,6,7,3,4,1,0] print quick_sort(temp,0,len(temp)-1)
class Node: def __init__(self,value=None,next=None): self.value = value self.next = next class LinkedList: def __init__(self): self.head = None def add_before_head(self,node): node.next = self.head self.head = node def print_list(self): node = self.head while node != None: print node.value, node = node.next print "\n" def add_after_tail(self,node): temp = self.head while temp.next != None: temp = temp.next temp.next = node self.tail = node def delete_with_key(self,key): node = self.head while node != None: if node.next.value == key: temp = node.next node.next = node.next.next node = node.next def reverse(self): node = self.head prev = None while node != None: curr = node nex = node.next node.next = prev node = nex prev = curr self.head = prev def is_palindrome(self): slow = self.head fast = self.head while fast != None and fast.next != None: slow = slow.next fast = fast.next.next print slow.value,fast.value ll = LinkedList() ll.add_before_head(Node(1)) ll.add_before_head(Node(2)) ll.add_before_head(Node(3)) ll.add_before_head(Node(4)) ll.print_list() ll.is_palindrome() ll.add_before_head(Node(5)) ll.print_list() ll.is_palindrome()
length=6 nlength=length-1 i=1 j=1 for i in range(length): for j in range(i): print("X",end="") print("") for i in range (1,length): for j in range(i,nlength): print("X",end="") print("")
print("Ingrese base y altura de un rectangulo, deben ser mayores a 0 en caso contrario se repetira") while True: base=int(input("Ingrese la base: ")) height=int(input("Ingrese la altura: ")) area=base*height if base>0 and height>0: break print("El area del rectangulo es: ",area)
vector1=[] vector2=[] print("Ingrese 5 numeros en un vector") for i in range(1,6): vector1.append(int(input())) for i in range(1,12): vector2[i]=i*2 print("",vector2[i])
genero=input("Ingrese su genero: ") if genero=="Femenino" or genero=="Masculino": if genero=="Femenino": print("El genero ingresado es femenino") else: print("El genero ingresado no es valido")
num1=int(input("Ingrese 1 numero: ")) num2=int(input("Ingrese 2 numero: ")) num3=int(input("Ingrese 3 numero: ")) if num1<num2 and num1<num3: if num2<num3: print("",num1,"",num2,"",num3) else: print("",num1,"",num3,"",num2) else: if num2<num3 and num2<num1: if num3<num1: print("",num2,"",num3,"",num1) else: print("",num2,"",num1,"",num3) else: if num3<num1 and num3<num2: if num1<num2: print("",num3,"",num1,"",num2) else: print("",num3,"",num2,"",num1)
class Asiento: def __init__(self): self.color = "negro" class Auto: def __init__(self, marca): self.asientos = [ Asiento(), Asiento(), Asiento(), Asiento() ] mi_auto = Auto("Volskwagen") print(mi_auto.asientos[1].color) mi_deportivo = Auto("ferrari") asiento_rojo = Asiento() asiento_rojo.color = "rojo" mi_deportivo.asientos = [asiento_rojo, asiento_rojo] print(len(mi_deportivo.asientos)) print(mi_deportivo.asientos[0].color)
#escribir una funcion que devuelva true si una palabra es palindroma # Metodo 1 palabra = input() palabra_invertida = palabra[::-1] if(palabra == palabra_invertida): print("Es palindroma") else: print("Noes palindroma")
def largest_prime(num): ans, div = num, 1 while div < ans**(1/2.0): if ans % div == 0: ans /= div div += 1 return ans num = 600851475143 print(int(largest_prime(num)))
#ex:3.33 #a string=str(input('Enter the string:')) def reverse_string(string): print(string[::-1]) return reverse_string(string) #b string=str(input('Enter the string:')) reverse_string(string)
#ex:3.8 from math import pi def perimeter(r): result=2*pi*r print(result) return perimeter(1)
#ex:2.27 n=int(input('enter the positive number:')) for i in range(0,4): result=n*i print(result)
from math import sqrt def fast_prime(limit): """Possibly due to the overhead of iterating a list, this method is much much faster at finding primes than the list methods I've been using before""" # Millionth Prime in 216.03 seconds def isPrime(n): if (n == 1): return False elif (n < 4): return True elif (n % 2 == 0): return False elif (n < 9): return True elif (n % 3 == 0): return False else: r = int(sqrt(n)) f = 5 while (f <= r): if (n % f == 0): return False if (n % (f + 2) == 0): return False f += 6 return True primes = 1 candidate = 1 while (primes < limit): candidate += 2 if (isPrime(candidate)): primes += 1 return candidate print fast_prime(1000000)
# Designer Door Mat # Enter your code here. Read input from STDIN. Print output to STDOUT N,M = map(int,input().split()) c = ".|." for i in range(N//2): print((c*((i*2)+1)).center(M, '-')) print(('WELCOME'.center(M,'-'))) for j in range(N//2): print((c*((N-(j*2))-2)).center(M, '-'))
import math; # сигма по нулю taylorSin = lambda x, n: \ (((-1) ** (n) * x ** (2 * n + 1))) / math.factorial(2 * n + 1); # сигма по нулю taylorCos = lambda x, n: \ (((-1) ** (n) * x ** (2 * n))) / math.factorial(2 * n); # сигма по нулю taylorAtan = lambda x, n: \ (((-1) ** (n) * x ** (2 * n + 1))) / (2 * n + 1); def taylor(type: str, x: float, n: int) -> float: while (n >= 0): if (type == "sin"): if (n == 0): return taylorSin(x, 0); else: return taylorSin(x, n) + taylor(type, x, n - 1); elif (type == "cos"): if (n == 0): return taylorCos(x, 0); else: return taylorCos(x, n) + taylor(type, x, n - 1); elif (type == "tan"): return taylor("sin", x, n - 1) / taylor("cos", x, n - 1); elif (type == "atan"): if (n == 0): return taylorAtan(x, 0); else: return taylorAtan(x, n) + taylor(type, x, n - 1); else: pass; # 30 градусов в радианах 0.523599 # 45 градусов в радианах 0.785398 # 60 градусов в радианах 1.0472 print(f"Самописная функция: {taylor('sin', 0.523599, 2)}, библиотечная функция {math.sin(0.523599)}"); print(f"Самописная функция: {taylor('cos', 0.785398, 2)}, библиотечная функция {math.cos(0.785398)}"); print(f"Самописная функция: {taylor('tan', 1.0472, 2)}, библиотечная функция {math.tan(1.0472)}"); print(f"Самописная функция: {taylor('atan', 1, 2)}, библиотечная функция {math.atan(1)}"); print(f"Самописная функция: {taylor('sin', 0.523599, 3)}, библиотечная функция {math.sin(0.523599)}"); print(f"Самописная функция: {taylor('cos', 0.785398, 3)}, библиотечная функция {math.cos(0.785398)}"); print(f"Самописная функция: {taylor('tan', 1.0472, 3)}, библиотечная функция {math.tan(1.0472)}"); print(f"Самописная функция: {taylor('atan', 1, 3)}, библиотечная функция {math.atan(1)}");
distancia = float(input('Qual a distancia total da viagem? ')) print('Voce esta prestes a comecar uma viagem de {:.2f} km'.format(distancia)) '''if distancia <=200: preco = distancia*0.50 else: preco = distancia*0.45''' preco = distancia * 0.50 if distancia <=200 else distancia * 0.45 print('E o preco da sua passagem sera de R${:.2f}'.format(preco))
n = int(input('digite um numero: ')) a = n-1 s = n+1 print('analisando o numero {}, seu antecessor e {} e seu sucessor e {}'.format(n ,a , s))
print('-=-'*20) print(' Vamos analisar um triangulo?') print('-=-'*20) r1 = float(input('Digite um seguimento de reta: ')) r2 = float(input('Digite outro seguimento de reta:')) r3 = float(input('Digite o terceiro seguimento de reta:')) if r1 < r2+r3 and r2 < r1+r3 and r3 < r1+r2: print(' Os tres seguimentos {}, {}, {} formam um triangulo'.format(r1, r2,r3)) else: print('Os seguimentos {}, {}, {} nao podem formar um triangulo'.format(r1, r2, r3))
celcius = float(input('qual a temperatura em graus celcius:')) kelvin = celcius + 273.15 farenheit = ((celcius*9)/5)+32 print('a temperatura de {:.2f}graus celcius corresponde a {:.2f} graus farenheit e a {:.2f} graus kelvin'.format(celcius, farenheit, kelvin))
p = float(input('qual e o preco do produto? R$: ')) porc = p*0.95 print('o produto de R${:.2f} com 5% de desconto ira custar : R$ {:.2f}'.format(p, porc))
def fatorial(n, show=False): """ -> Calcula o fatorial de um número informado. :param n: O número a ser calculado. :param show: Mostra ou não a conta do fatorial. :return:Valor fatorial do número solicitado. """ f = 1 for c in range(n, 0, -1): if show: print(c, end='') if c > 1: print(' x ', end='') else: print(' = ', end='') f *= c return f help(fatorial) num = int(input('Insira um número: ')) print(fatorial(num, show=True))
import random import numpy as np def matrix(m,n): lst = [[random.randint(1,10) for e in range(n)]for e in range(m)] return lst def get_flat_list(lst,m,n): new_lst =[] for i in range(m): if i %2 != 0: reversed(lst[i]) new_lst += lst[i] return new_lst m = int(input("Nhập số hàng: ")) n = int(input("Nhập số cột: ")) lst = matrix(m,n) print(lst) new_list = get_flat_list(lst,m,n) print(new_list)
import random while True: current_number = 1 if random.randint(0, 1) == 0: current_player = "human" else: current_player = "computer" while current_number <= 21: print("The current number is " + str(current_number) + ".") print() if current_player == "human": print("Add 1, 2, or 3. Do not pass 21. The player who lands on 21 loses.") player_choice = "" while player_choice not in ["1", "2", "3"]: player_choice = input("What will you add? ") player_choice = int(player_choice) current_number = current_number + player_choice print() if current_number >= 21: print("The current number is " + str(current_number) + ".") print() print("Sorry, you lose.") break else: current_player = "computer" else: computer_choice = random.randint(1, 3) print("Computer turn. The computer choses " + str(computer_choice) + ".") print() current_number = current_number + computer_choice if current_number >= 21: print("The current number is " + str(current_number) + ".") print() print("Well done, you won!") break else: current_player = "human" play_again = input("Do you want to play again? ") if play_again.lower().startswith("y"): continue else: print("Goodbye") break
import turtle import random as r t = turtle.Turtle() t.hideturtle() t.penup() t.goto(0, -200) t.speed(10) t.pensize(10) t.pencolor("black") t.pendown() t.circle(200) t.penup() t.speed(10) t.shape("turtle") t.pencolor('green') t.goto(0, 0) angle = r.randint(0, 360) t.right(angle) t.showturtle() count = 0 while True: t.speed(1) # rùa chỉ di chuyển một khoảng cách # hơi bé hơn bán kính của hộp tròn là 200 # tránh rùa di chuyển đè lên vạch t.forward(188) # Bắt rùa về vị trí ban đầu, chính giữa hộp tròn t.hideturtle() t.speed(10) t.goto(0, 0) angle = r.randint(0, 360) # Tạo hướng mới cho rùa chạy, thử vận may mới t.right(angle) t.showturtle() # Khi rùa thử đến số lần nào đó thì dừng lại # kết thúc chương trình bằng lệnh break count += 1 if count == 10: break turtle.done()
a= int(input("Nhập số đảo ngược:")) while a != 0: print(a%10, end="") a=a // 10
import turtle t= turtle.Turtle() def draw_polygon(a,b): # a là số cạnh của đa giác # b là cd các cạnh c = 180 - (1 - 2/a)*180 for x in range(a): t.fd(b) t.rt(c) turtle.done() a = int(input("Nhập số cạnh đa giác:")) b = float(input("Nhập độ dài cạnh:")) draw_polygon(a,b)
import turtle import random t = turtle.Turtle() t.shape("turtle") t.hideturtle() t.pensize(3) t.color("blue") t.speed(1) t.penup() t.goto(-400, 0) t.showturtle() dem = 0 while dem < 10: # sinh hai giá trị ngẫu nhiên down = random.randint(20, 50) up = random.randint(20, 50) t.pendown() '''rùa tiến về phía trước với giá trị ngẫu nhiên ở trên, có để lại nét vẽ''' t.forward(down) t.penup() ''' rùa tiến về phía trước với giá trị ngẫu nhiên ở trên, không để lại nét vẽ''' t.forward(up) dem += 1 turtle.done()
class Car(): x=5 n=10 def _init_(self,n,m): self.n=n self.m=m def hai(self): print("this is car") def hello(self,colour): print("this is color",colour) def view(self,colour,number): print("this is number",number,colour) w=Car(7,8) print(w.n) p=Car() p.hai() p.hello("red") p.view("red",6) print(p.x) p.x=p.x+1 print(p.x) q=Car() print(q.x)
a,num = [int(x) for x in input().split()] lista = [] for i in range(a): x = input() lista.append(x) lista.sort() print(lista[num-1])
import helpers def get_available_players(players, my_drafted_players, other_drafted_players, printon): """ Prints a list of undrafted players by their index in players.values() """ available_players = [] for i in range(len(players)): player = players.values()[i] if 'Untracked' not in player.id: if player not in my_drafted_players: if player not in other_drafted_players: if printon: print '%s) %s' % (i, player.id) available_players.append(player) return available_players def get_num_drafted(my_drafted_players, other_drafted_players, untracked_players_drafted): return len(my_drafted_players) + len(other_drafted_players) + untracked_players_drafted def get_team_picks(pick_no, num_rounds, num_teams): picks = [] for round in range(1, num_rounds + 1): # Odd round if round % 2 == 1: round_pick = pick_no # Even round else: round_pick = num_teams - pick_no + 1 overall_pick = round_pick + num_teams*(round - 1) picks.append(overall_pick) return picks def get_remaining_picks(my_drafted_players, other_drafted_players, pick_no, num_rounds, num_teams, untracked_players_drafted): picks = get_team_picks(pick_no, num_rounds, num_teams) num_drafted = get_num_drafted(my_drafted_players, other_drafted_players, untracked_players_drafted) remaining_picks = [pick for pick in picks if pick > (num_drafted + 1)] return remaining_picks def get_players_between_picks(my_drafted_players, other_drafted_players, pick_no, num_rounds, num_teams, untracked_players_drafted): remaining_picks = get_remaining_picks(my_drafted_players, other_drafted_players, pick_no, num_rounds, num_teams, untracked_players_drafted) next_team_pick = remaining_picks[0] num_drafted = get_num_drafted(my_drafted_players, other_drafted_players, untracked_players_drafted) players_drafted_between_picks = next_team_pick - num_drafted - 2 if players_drafted_between_picks == 0: players_drafted_between_picks = num_teams*2 - 2 next_team_pick = remaining_picks[1] return players_drafted_between_picks, next_team_pick def get_prob_avail_after(available_players, my_drafted_players, other_drafted_players, pick_no, num_rounds, num_teams, untracked_players_drafted): prob_avail_after = {} draft_risks = 0 players_drafted_between_picks, next_team_pick = \ get_players_between_picks(my_drafted_players, other_drafted_players, pick_no, num_rounds, num_teams, untracked_players_drafted) sorted_avg_picks = sorted([player.avg_pick for player in available_players]) max_pick_to_eval = sorted_avg_picks[players_drafted_between_picks + 2] for player in available_players: avg_pick = player.avg_pick if avg_pick <= max_pick_to_eval: p_avail = helpers.get_prob_avail_after(players_drafted_between_picks, avg_pick, next_team_pick, width=1.0) prob_avail_after[player] = p_avail if prob_avail_after[player] < 1: draft_risks += 1 else: prob_avail_after[player] = 1 return prob_avail_after, draft_risks
''' TRANSPOSE AND FLATTEN ''' import numpy ''' The for loop in list comprehension just runs n (number of rows) times because we take the input for each row in separate lines (counting for the number of rows or loops iterations) instead of all the elements in one single line in which case the number of times the loop ran should've been n*m ''' def takeInput(): n, m = map(int, input().strip().split()) return ([input().strip().split() for _unused_i in range(n)]) def arrayOperations(someList): array = numpy.array(someList, int) print(array.transpose()) print(array.flatten()) ''' A list can be flattened using a list comprehension like so: someList = [[1,2],[3,4]] flatList = [num for i in range(len(someList)) for num in someList[i]] ''' inputList = takeInput() arrayOperations(inputList)
''' TEXT WRAP ''' import textwrap def wrap(string, max_width): return textwrap.fill(string, max_width) ''' textwrap.wrap(text[, width[, ...]]) Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines. See the TextWrapper.wrap() method for additional details on how wrap() behaves. textwrap.fill(text[, width[, ...]]) Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for "\n".join(wrap(text, ...)) ''' if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
# -*- coding: utf-8 -*- """ Created on Sat Sep 5 20:13:26 2020 @author: satwika """ A=10 print(A) print? print("Anne Satwika Teli") print("Anne","Satwika","Teli",sep='==',end=".....") print("Anne","Satwika","Teli",sep='==') help(print) help("operators") !python --version !pip list a="anne" b=10 c=30.33 type(a) type(b) type(c) Num = int(Number) type(Num) PhoneNum=int(input()) print("phone no is ",PhoneNum) country="India" print("I live in ",country," which is a very good country") print("I live in {0} which is a very good country".format(country)) p=1.11 q=int(a) r=float(q) X=0 Y=1 D= X and Y D E= X or Y E L=15 bool(L) M=0 bool(M) fname="anne" lname="teli" name= fname + " " + lname name len(lname) lname=lname.capitalize() print(lname) lname=lname.upper() print(lname) lname=lname.lower() print(lname) lname=lname.rjust(10) print(lname) lname=lname.center(20) print(lname) name=name.replace('teli','satwika') print(name)
#!/usr/local/bin/python2.7 import random def play_game(num): while True: a = int(raw_input("please input a number:")) if a > num: print "The number is bigger" elif a < num: print "The number is zsmaller" else: print "You are right!" break def if_continue(): num = random.randint(0, 99) while True: c = raw_input("Do you want to play the game once more,please input Y/N:") if c == "Y": play_game(num) elif c == "N": print "Thank you for playing this game, GoodBye!" break else: print "The input is not correct, Please input Y/N only!" def main(): print "----------begin game-----------" num = random.randint(0, 99) play_game(num) if_continue() if __name__ == '__main__': main()
x=input().replace("\r","") y=input().replace("\r","") z=input().replace("\r","") theList=[] theList=x.split(",") print(x.find(y)!=-1) print(x.find(y)) print(theList) print(theList[0]+"--"+theList[1]) print(theList[0]==y) print(theList[-1]==y) print(x.upper()) print(x.title()) print(y.isnumeric()) print(x.replace(y,z))
import search def getPOS(sent, dex): ar = search.toArray(sent,' ') if 'ing' in ar[dex] or 'ed' in ar[dex]: return "verb" if dex < len(sent)-1 and 'ing' in ar[dex+1] or 'ed' in ar[dex+1]: return "noun" return "adj"
#!/usr/bin/env python import sys s = sys.stdin.readlines() i = 0 reverse = [] while i < len(s): characters = s[i].rstrip() reverse.append(characters) i = i + 1 j = 0 while j < len(reverse): print reverse[len(reverse) - j - 1] j = j + 1
#!/usr/bin/env python3 import sys def caps(words): i = 0 while i < len(words): i = 0 while i < len(words): words[i] = words[i][:: - 1] words[i] = words[i].capitalize() words[i] = words[i][:: - 1] i += 1 return words def main(): for line in sys.stdin.readlines(): line = line.strip() line = line.split() print(" ".join(caps(line))) if __name__ == '__main__': main()
#!/usr/bin/env python class Account(object): # A class variable irate = 10.0 def __init__(self, name, balance=0): self.name = name self.balance = balance # self.irate = 2.0 def apply_interest(self): self.balance += self.balance * self.irate / 100 def __str__(self): return '{:s} : {:2f}'.format(self.name, self.balance)
#!/usr/bin/env python total = 0 s = raw_input() while s != "0": total = total + int(s) s = raw_input() print total
#!/usr/bin/env python3 import sys def main(): s = sys.argv[1] ls = list(s) i = 1 while i < len(ls): ls[i - 1], ls[i] = ls[i], ls[i - 1] i += 2 print(''.join(ls) if __name__ == '__main__': main()
#!/usr/bin/env python import sys word = sys.argv[1] i = 0 while i < len(word) - 1: print(word[i] + word[i +1]) i += 1
#!/usr/bin/env python3 import sys def anagram(a, b): for c in a: if c not in b: return False b = b.replace(c, '', 1) return True def main(): a, b = sys.stdin.readline().strip().split() print(anagram(a, b)) if __name__ == '__main__': main()
#!/usr/bin/env python3 def sumup(list_of_numbers): #base case if list_of_numbers == []: return 0 return list_of_numbers[0] + sumup(list_of_numbers[1:]) x = sumup([5, 3, 1, 3]) print(x)
#!/usr/bin/env python new = 0 old = 0 i = 0 while i < 6: n = input() n = old if old < new: old = new print "lower" if old > new: old = new print "higher" if new < old: print "lower" if new > old: print "higher" else: old = new print "equal" i = i + 1
person = { 'name': 'ricky', 'lastN': 'medina', 'age': 3 } print(person['name'], person['age']) print('Hello %(name)s. You have %(age)d years old' %person) print('height' in person) # check for key existance print('age' in person)
""" This problem was asked by Google. Given an array of strictly the characters 'R', 'G', and 'B', segregate the values of the array so that all the Rs come first, the Gs come second, and the Bs come last. You can only swap elements of the array. Do this in linear time and in-place. For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], it should become ['R', 'R', 'R', 'G', 'G', 'B', 'B']. """ from collections import defaultdict import unittest from typing import List, Dict def count_sort(arr: List[str]): counts = defaultdict(lambda: 0) # type: Dict[str, int] for e in arr: counts[e] += 1 ri = 0 gi = counts['R'] bi = counts['R'] + counts['G'] for i in range(ri, counts['R']): if arr[i] is 'G': arr[i], arr[gi] = arr[gi], arr[i] gi += 1 if arr[i] is 'B': arr[i], arr[bi] = arr[bi], arr[i] bi += 1 for i in range(gi, counts['R'] + counts['G']): if arr[i] is 'R': arr[i], arr[ri] = arr[ri], arr[i] if arr[i] is 'B': arr[i], arr[bi] = arr[bi], arr[i] class TestSolution(unittest.TestCase): def test_given(self) -> None: inp = ['G', 'B', 'R', 'R', 'B', 'R', 'G'] count_sort(inp) out = ['R', 'R', 'R', 'G', 'G', 'B', 'B'] self.assertEqual(inp, out) if __name__ == '__main__': unittest.main()
""" This problem was asked by Airbnb. Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. Follow-up: Can you do this in O(N) time and constant space? """ import unittest from typing import List def loop(l: List[int]) -> int: incl = 0 excl = 0 for i in l: new_excl = excl if excl > incl else incl incl = excl + i excl = new_excl return max(incl, excl) def recursion(l: List[int]) -> int: if not l: return 0 if len(l) <= 2: return max(l) return max( recursion(l[2:]) + l[0], recursion(l[3:]) + l[1] ) class TestSolutions(unittest.TestCase): def test_recursion(self: 'TestSolutions'): self.assertEqual(recursion([6]), 6) self.assertEqual(recursion([1, 5]), 5) self.assertEqual(recursion([2, 4, 6, 2, 5]), 13) self.assertEqual(recursion([5, 1, 1, 5]), 10) def test_loop(self: 'TestSolutions'): self.assertEqual(loop([6]), 6) self.assertEqual(loop([1, 5]), 5) self.assertEqual(loop([2, 4, 6, 2, 5]), 13) self.assertEqual(loop([5, 1, 1, 5]), 10) if __name__ == '__main__': unittest.main()
""" This problem was asked by Microsoft. Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox']. Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond']. """ import unittest from typing import List, Optional def reconstruct(words: List[str], s: str, reconstruction: List[str]=[]) -> Optional[List[str]]: if not s: return reconstruction for w in words: w_len = len(w) if w_len <= len(s) and w == s[:w_len]: r = reconstruct(words, s[w_len:], reconstruction + [w]) if r is not None: return r return None class TestSolution(unittest.TestCase): def test_empty_string(self) -> None: words = [] # type: List[str] s = '' expected = [] # type: List[str] self.assertEqual(reconstruct(words, s), expected) def test_given1(self) -> None: words = ['quick', 'brown', 'the', 'fox'] s = 'thequickbrownfox' expected = ['the', 'quick', 'brown', 'fox'] self.assertEqual(reconstruct(words, s), expected) def test_given2(self) -> None: words = ['bed', 'bath', 'bedbath', 'and', 'beyond'] s = 'bedbathandbeyond' expectations = [ ['bedbath', 'and', 'beyond'], ['bed', 'bath', 'and', 'beyond'] ] self.assertTrue( reconstruct(words, s) in expectations ) def test_no_reconstruction(self) -> None: words = ['brown', 'the', 'fox'] s = 'thequickbrownfox' expected = None self.assertEqual(reconstruct(words, s), expected) if __name__ == '__main__': unittest.main()
""" This problem was asked by Facebook. Given a function that generates perfectly random numbers between 1 and k (inclusive), where k is an input, write a function that shuffles a deck of cards represented as an array using only swaps. It should run in O(N) time. Hint: Make sure each one of the 52! permutations of the deck is equally likely. """ import unittest from random import randint from typing import List, Dict from collections import defaultdict def shuffle(deck: List[str]) -> List[str]: n = len(deck) for i in range(n): rand_j = randint(i, n-1) deck[i], deck[rand_j] = deck[rand_j], deck[i] return deck class TestSolution(unittest.TestCase): def test_given(self) -> None: deck = ['Ahearts', 'Kclubs', 'Jdiamonds', '10spades'] perms = defaultdict(lambda: 0) # type: Dict[str, int] for _ in range(1000000): perms[','.join(shuffle(deck))] += 1 self.assertTrue(max(perms.values()) - min(perms.values()) < 1000) if __name__ == '__main__': unittest.main()
""" This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? """ import unittest from functools import reduce from typing import List def division(l: List[int]) -> List[int]: s = reduce(lambda x, y: x * y, l) return [s // v for v in l] def double_loop(l: List[int]) -> List[int]: r = [] for i in range(len(l)): s = 1 for j, v in enumerate(l): if i != j: s *= v r.append(s) return r class TestSolutions(unittest.TestCase): def test_division(self: 'TestSolutions'): self.assertEqual(division([1, 2, 3, 4, 5]), [120, 60, 40, 30, 24]) self.assertEqual(division([3, 2, 1]), [2, 3, 6]) self.assertEqual(division([2, 2, 1]), [2, 2, 4]) def test_double_loop(self: 'TestSolutions'): self.assertEqual(double_loop([1, 2, 3, 4, 5]), [120, 60, 40, 30, 24]) self.assertEqual(double_loop([3, 2, 1]), [2, 3, 6]) self.assertEqual(double_loop([2, 2, 1]), [2, 2, 4]) if __name__ == '__main__': unittest.main()
""" This problem was asked by Facebook. A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minimum cost which achieves this goal. """ import unittest from math import inf from typing import List, Optional def min_cost(matrix: List[List[float]], prev_color: Optional[int]=None) -> float: if len(matrix) == 1: if prev_color is None: return min(matrix[0]) return min(matrix[0][:prev_color] + matrix[0][(prev_color + 1):]) cost = inf for i, r in enumerate(matrix): if i != prev_color: cost = min(cost, r[i] + min_cost(matrix[1:], i)) return cost class TestSolution(unittest.TestCase): def test_one_house(self) -> None: cost_m = [[5.0, 8.0, 3.0]] self.assertEqual(min_cost(cost_m), 3.0) def test_two_houses_two_colors(self) -> None: cost_m = [[5.0, 8.0], [8.0, 5.0]] self.assertEqual(min_cost(cost_m), 10.0) if __name__ == '__main__': unittest.main()
""" This problem was asked by Twitter. Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that s as a prefix. For example, given the query string de and the set of strings [door, deer, deal], return [deer, deal]. Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries. """ import unittest from typing import Optional, List, Dict class TrieNode: def __init__(self, char: str='') -> None: self.char = char self.children = dict() # type: Dict[str, 'TrieNode'] def add(self, word: str) -> None: if not word: return l = word[0] if l not in self.children: self.children[l] = TrieNode(l) self.children[l].add(word[1:]) def get_with_prefix(self, prefix: str) -> Optional['TrieNode']: if not prefix: return self if prefix[0] not in self.children: return None return self.children[prefix[0]].get_with_prefix(prefix[1:]) def get_child_words(self) -> List[str]: if len(self.children) == 0: return [self.char] child_words = [] # type: List[str] for c in self.children.values(): child_words += [self.char + w for w in c.get_child_words()] return child_words def trie_autocomplete(s: str, possible: List[str]) -> List[str]: root = TrieNode() for w in possible: root.add(w) head = root.get_with_prefix(s) if not head: return [] return [s[:-1] + w for w in head.get_child_words()] class TestSolutions(unittest.TestCase): def test_empty_query(self: 'TestSolutions') -> None: self.assertEqual( sorted(trie_autocomplete('', ['door', 'deer', 'deal'])), sorted(['door', 'deer', 'deal']) ) def test_non_matching_query(self: 'TestSolutions') -> None: self.assertEqual( sorted(trie_autocomplete('elbert', ['door', 'deer', 'deal'])), sorted([]) ) def test_given_example(self: 'TestSolutions') -> None: self.assertEqual( sorted(trie_autocomplete('de', ['door', 'deer', 'deal'])), sorted(['deer', 'deal']) ) if __name__ == '__main__': unittest.main()
class Usuario(): def __init__(self, nome, endereco, email, telefone, id): self.nome = nome self.endereco = endereco self.email = email self.telefone = telefone self.id = id class Livro(): def __init__(self, titulo, autor, publicacao, id, area, categoria): self.titulo = titulo self.autor = autor self.publicacao = publicacao self.id = id self.area = area self.categoria = categoria class Avaliacao(): avaliacoes =[] def __init__(self, usuario, livro, dt_avaliacao, nota, comentario): self.usuario = usuario self.livro = livro self.dt_avaliacao = dt_avaliacao self.nota = nota self.comentario = comentario self.avaliacoes.append(self) arthur = Usuario('Artur de Camelote', 'Castelo de camelote', 'artur_rei@email.com', '5674-8901', 1.) livro = Livro('Dive into Python 3', 'Mark Pilgrim', '06/11/2009', 42, 'Ciências Exatas', 'Programação de computadores') avalicacao =Avaliacao(arthur, livro, '15/01/2015', 5, 'Excelente livro pois além de ser gratuito fornece ' + 'armas poderosas para programadores e estudiosos') print(avalicacao.avaliacoes)
def cria_frase( palavras): return ' '.join(palavras) palavra=True frase=[] while palavra: palavra= input('Digite algo, pressione <Enter para sair>' ) frase.append(palavra) print(cria_frase(frase))
class State: def __init__(self, state, parent, cost, move, key): super().__init__() self.state = state self.parent = parent self.cost = cost self.move = move self.key = key if self.state: self.to_string = ''.join(str(ch)+"," for ch in self.state) def __eq__(self, other): return self.to_string == other.to_string def __lt__(self, other): return self.to_string < other.to_string
import subprocess def get_strings_with_offset(file_path): """ Obtains strings from a file Arguments: file_path -- path from the binary to get strings from Returns: strings_with_offset -- strings found. The first word of each string is the offset on the file """ #EXECUTE STRINGS COMMAND process = subprocess.Popen(["strings","--radix=x",file_path], stdout=subprocess.PIPE) strings_with_offset=[] while True: line =process.stdout.readline() if not line: break strings_with_offset.append(line.strip().decode("UTF-8")) return strings_with_offset
str0 = 'BWWWWWBWWWW' def EnRunLength(str0): code = '' connect = 1 for i in range(1, len(str0)): if str0[i] != str0[i-1]: code = code + str(connect) + str0[i-1] connect = 1 else: connect += 1 code = code + str(connect) + str0[len(str0) - 1] return code def DeRunLength(code): connect = '' str0 = '' for i in range(0, len(code)): if code[i].isalpha(): for j in range(0 , int(connect)): str0 += code[i] connect = '' else: connect = connect + code[i] return str0 code = EnRunLength(str0) print(code) print(DeRunLength(code))
# Question 1 import csv file = 'student.csv' # Reading def readData(): print("Student First Name \t Student Last Name \t Grade") with open(file, 'r') as my_file: reader = csv.reader(my_file) sum_csv = 0 count = 0 for row in reader: print("\t\t\t\t".join(row)) sum_csv = sum_csv + int(row[2]) count = count + 1 print("\n") print("Grade average: ", int(sum_csv / count)) my_file.close() # Writing def writeData(): fullName = input("Please enter the student name separated by a space: ") firstName, lastName = fullName.split(" ") grade = input("Please enter a grade: ") data = [firstName, lastName, grade] with open(file, 'a') as my_file: writer = csv.writer(my_file, lineterminator='\n') writer.writerow(data) my_file.close() def menu(): print("\n") print("Welcome to Calvin's Lab Test 2!") print("1) View students") print("2) Add student") print("3) Exit") option = 0 while option != 3: menu() option = int(input("Please select an option from the menu")) if option == 1: readData() elif option == 2: writeData() elif option == 3: print("Goodbye") break else: print("Option not valid!")
#!/usr/bin/env python import random var = random.randint(1,100000) print(" Welcom to Number Guessing Game ") while 1: test= input('Enter a Integer Number of your wish : ') if var == test: print( "You've guessed the correct number") break elif var < test: print( "Your guess is greater then the number") else : print(" Your guess is less than the number ")
# Faça um programa, com uma função que necessite de um argumento. A função retorna o valor de caractere ‘P’, # se seu argumento for positivo, ‘N’, se seu argumento for negativo e ‘0’ se for 0. def funcao(arg1): if arg1 > 0: return 'P' elif arg1 == 0: return 0 else: return 'N' num1 = int(input('digite um numero ')) resposta = funcao(num1) print(resposta)
#DESAFIO - Data com mês por extenso. # Construa uma função que receba uma data no formato DD/MM/AAAA e devolva uma string no formato D de mesPorExtenso de AAAA. # Opcionalmente, valide a data e retorne NULL caso a data seja inválida. # Considere que Fevereiro tem 28 dias e que a cada 4 anos temos ano bisexto, sendo que nesses casos Fevereiro terá 29 dias. import calendar def data(num): return calendar.month_name[mes] resp = input('digite sua data de nascimento no formato DD/MM/AAAA ') dia = int(resp[0:2]) mes = int(resp[3:5]) ano = int(resp[6:]) resp2 = (data(resp)) print('a data do seu nascimento é',dia,'de',resp2, 'de', ano)
""" CS50 AI with Python: Search LECTURE 0: agent: entity that perceives its environment and acts upon that environment. state: configuration of the agent in its environment. initial state: state in which the agent begins. Starting point for search algorithm. actions: choices that can be made in any given state. Actions(s): returns the set of actions that can be executed in state s transition model: a description of what state results from performing any applicable action in any state. RESULT(s,a): returns the state resulting from performing action a in state s. state space: the set of allŚ states reachable from the initial state by any sequence of models. goal test: way to determine whether a given state is a goal state. path cost: numerical cost associated with a given path. each path will be given a numeric cost. rather than finding a solution. find the least expensive cost. Search Problem: initial state: state where we begin actions: action we can take. transition model: define what happens when we go from a state and one action to where we reach. goal test: know if we reached a goal. path cost function: by following a sequence of actions, what's the cost. optimal solution: solution that has the lowest path cost among all solutions. node: data structure that keeps track of - a state - a parent (node that generated this node, parent of this node0 - an action (action applied to parent to get node) - a path cost (from initial state to node) frontier: a set of paths available from a start node expand node: consider possible actions from the state that node is representing. Approach 1) Start with a frontier that contains initial state. 2) Repeat: a) If the frontier is empty, then no solution. b) Remove a node from the frontier. c) if node contains goal state, return the solution. d) Expand node, add resulting nodes to the frontier Revised Approach 1) Start with a frontier that contains the initial state. 2) Start with an empty explored set. 3) Repeat: a) If the frontier is empty, then no solution. b) Remove a node from the frontier. c) if node contains goal state, return the solution. d) Add the node to the explored set e) Expand node, add resulting nodes to the frontier if they aren't already in the frontier or the explored set. What order to remove elements: DFS: Treat frontier like a STACK Stack: last in, first out. last thing added to frontier, first thing to remove from frontier BFS: Treat frontier like a QUEUE Queue: first-in first-out data type. Earlier arrive in the frontier, earlier you get explored. (DFS) Depth-First search: search algorithm that always expands the deepest node in the frontier. (BFS) Breadth-First search: search algorithm tat always explores the shallowest node in the frontier. """ import sys # TODO: learn about list[x:y] # Frontier DFS 40:00 class Node: def __init__(self, state, parent, action): self.state = state self.parent = parent self.action = action class StackFrontier: def __init__(self): self.frontier = [] def add(self, node): self.frontier.append(node) def contains_state(self, state): return any(node.state == state for node in self.frontier) def empty(self): return len(self.frontier) == 0 def remove(self): if self.empty(): raise Exception("empty frontier") else: node = self.frontier[-1] self.frontier = self.frontier[:-1] return node class QueueFrontier(StackFrontier): def remove(self): if self.empty(): raise Exception("empty frontier") else: node = self.frontier[0] self.frontier = self.frontier[1:] """ 52:00 How would you make your AI make smarter decisions uninformed search: search strategy that uses no problem specific knowledge informed search: search strategy that sues problem specific knowledge to find solutions more efficiently (GBFS) greedy best-first search: search algorithm that expands the node that is closest to the goal, as estimated by a heuristic function h(n) heuristic = estimate how close we are to goal h(n) = takes state of input and returns estimate of how close we are to the goal Manhattan distance = geographically how close we are to the goal, no walls. A* search: search algorithm that expands node with lowest value of g(n)[cost to reach node] + h(n)[estimated cost to goal] optimal if: h(n) is admissible (never overestimates true cost) h(n) is consistent (for every node n and successor n' with step cost c, h(n)<=h(n') + c) Search when another agent is actively deterring Agent from reaching goal Minimax: -1,0,1 Assign a value to state of winning/losing MAX aims to maximize score MIN aims to minimize score Game So: initial state PLAYER(s): returns which player to move in state s ACTIONS(s): returns legal move in state s RESULT(s,a): returns state after action a taken in state s TERMINAL(s): checks if state s is a terminal state UTILITY(s): final numerical value for terminal state s Minimax Given a state s: MAX picks action a in ACTIONS(s) that produces highest value of MIN-VALUE(RESULT(s,a)) MIN picks action a in ACTIONS(s) that produces smallest value of MAX-VALUE(RESULT(s,a)) function MAX-VALUE(state): if TERMINAL(state): return UTILITY(state) v = -infinity for action in ACTIONS(state): v = MAX(v,MIN-VALUE(RESULT(state,action))) return v function MIN-VALUE(state): if TERMINAL(state): return UTILITY(state) v = +infinity for action in ACTIONS(state): v = MIN(v,MAX-VALUE(RESULT(state,action))) return v Alpha-Beta Pruning Search efficiently if you remove nodes to optimize space. Makes searches efficient. Depth-Limited Minimax After x number of moves, don't consider any more moves evaluation function: function that estimates the expected utility of the game form a given state """
# 예제 5-4 : 재귀 함수 종료 예제 def recursive_function(i): # 재귀함수 시작 부분에 100번째 출력했을 때 종료되도록 종료 조건 명시 # 의도적으로 무한루프를 이용하는 것이 아니라면, 반드시 종료조건을 통해 언젠가는 프로그램이 정해진 값을 반환하도록 ! if i == 100: return # 종료조건 : 100번째 재귀함수 <- 더 이상 함수가 호출되지 않고 종료 # 이후 차례대로 99번째 재귀함수부터 종료되어 결과적으로 1번째 재귀함수까지 종료 -> 스택에 데이터를 넣었다가 빼는 형태 ! print(i, '번째 재귀 함수에서', i + 1, '번째 재귀 함수를 호출합니다.') recursive_function(i + 1) # 다음 재귀함수 호출 <- 매개변수 i값 증가 print(i, '번째 재귀 함수를 종료합니다.') recursive_function(1)
# 예제 11-1 : 소수의 판별 - 기본적인 알고리즘 # 소수 판별 함수 def is_prime_number(x): # 특정 자연수 x가 소수의 정의를 만족하는지 여뷰를 반복문을 이용하여 하나씩 확인 # 2부터 (x - 1)까지의 모든 수를 확인하며 for i in range(2, x): # x가 해당 수로 나누어 떨어진다면 if x % i == 0: # 입력으로 주어진 수 x가 i로 나누어 떨어지는 경우가 하나라도 존재한다면 return False # 소수가 아님 return True # 소수임 print(is_prime_number(4)) print(is_prime_number(7))
# 실전문제 7-8 : 떡볶이 떡 만들기 def max_height(n, m, h_list): height = 1 while height >= 1: result = 0 for i in range(n): if h_list[i] > height: result += h_list[i] - height else: continue if result == m: return height elif result > m: height += 1 else: height -= 1 # 떡의 개수(N)와 요청한 떡의 길이(M)를 입력받기 n, m = list(map(int, input().split())) # 각 떡의 개별 높이 정보를 입력받기 h_list = list(map(int, input().split())) max_h = max_height(n, m, h_list) print(max_h) """ # 이진 탐색을 위한 시작점과 끝점 설정 <- 탐색 범위 설정 (높이로 설정할 수 있는 값의 범위 국한) start = 0 end = max(array) # 입력으로 들어온 (현재 가지고 있는) 떡의 높이 중 가장 긴 떡의 길이 # 이진 탐색 수행 (반복적) -> 최적의 해 구하기 result = 0 while(start <= end): total = 0 mid = (start + end) // 2 # 매번 현재 탐색 범위를 이용해 중간점 (높이) 설정 for x in array: # 잘랐을 때의 떡의 양 계산 -> 현재 높이로 떡을 잘랐을 때의 전체 떡의 양 if x > mid: # 현재 떡의 길이가 높이보다 더 클 때에만 실제로 떡을 얻을 수 있기에 total += x - mid # 잘린 부분의 떡을 total 변수에 담기 (전체 떡을 잘랐을 때의 떡의 양 정보) # 탐색 범위 바꾸기 1) 2) # 1) 떡의 양이 부족한 경우 더 많이 자르기 (왼쪽 부분 탐색) # 높이 값이 줄어드는 방향으로 탐색 범위를 조절하여 더 많은 떡을 얻을 수 있도록 업데이트 if total < m: end = mid - 1 # 끝점 위치 조정 # 2) 떡의 양이 충분한 경우 덜 자르기 (오른쪽 부분 탐색) # 높이 값을 늘리는 방향으로 탐색 범위를 조절하여 떡을 덜 자를 수 있도록 업데이트 else: result = mid # 최대한 덜 잘랐을 때가 정답이므로, 여기에서 result에 기록 # 떡의 양이 충분한 경우 (m 이상의 떡을 얻을 수 있는 경우) -> result의 값을 높이 값으로 갱신 # 최종적으로 가장 마지막에 기록된 높이 값 출력 start = mid + 1 # 시작점 위치 조정 # 정답 출력 print(result) """
#time Complexit O(n*k) n is the no of elements in array and s is the length of the string class Solution(object): def groupAnagrams(self, strs): primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] d = {} if not strs: return [] else: for i in strs: p = self.calculate(i,primes) if p not in d: d[p] = [] d[p].append(i) else: d[p].append(i) return d.values() def calculate(self,string,primes): mult = 1 for i in range(0,len(string)): mult = mult * primes[ord(string[i])-ord('a')] return mult """ :type strs: List[str] :rtype: List[List[str]] """
# menu_text.py # # simple python menu # https://stackoverflow.com/questions/19964603/creating-a-menu-in-python # city_menu = { '1': 'Chicago', '2': 'New York', '3': 'Washington', 'x': 'Exit'} month_menu = {'0': 'All', '1': 'January', '2': 'February', '3': 'March', '4': 'April', '5': 'May', '6': 'June', 'x': 'Exit'} weekday_menu = {'0': 'All', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', '7': 'Sunday', 'x': 'Exit'} def get_menu_item(menu): while True: print('------------') print('Menu Options') print('------------') options = list(menu.keys()) options.sort() for entry in options: print( entry, menu[entry] ) selection = input("Please Select: ") # in case X entered for exit if selection.isupper(): selection = selection.lower() if selection in options: #print(menu[selection]) break else: print( "Unknown Option Selected!" ) return selection def main(): city_selected = get_menu_item(city_menu) print('\n Selected Selected City: ', city_menu[city_selected]) month_selected = get_menu_item(month_menu) print('\n Selected Month: ', month_menu[month_selected]) print("month", month_selected) day_selected = get_menu_item(weekday_menu) print('\n Selected Weekday: ', weekday_menu[day_selected]) if __name__ == "__main__": main()
#https://stackoverflow.com/questions/35166633/how-do-i-multiply-each-element-in-a-list-by-a-number/35166717 width = input("Width of multiplication table: ") height = input ("Height of multiplication table: ") w=(int(width)+1) h=int(height) t = "X" b=list(range(0,w)) a=range(0,h) for j in a: meg="" j+=1 c=list(range(1,w)) d = [i * (j) for i in c] for k in d: meg = meg + str(k) + " " print(meg) #print((d), end = ' ' ) #print(" ")