text
stringlengths
37
1.41M
# 有效的字母异位词 # 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。 # 说明: # 你可以假设字符串只包含小写字母。 class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ # ranking 54%:转换成列表,然后排序,比较两个排序后的列表是否相同 if len(s) != len(t): return False else: s1 = list(s) t1 = list(t) s1.sort() t1.sort() return s1 == t1
# 位1的个数 # 编写一个函数,输入是一个无符号整数, # 返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ # 参考:http://www.cnblogs.com/klchang/p/8017627.html MAX_INT = 4294967295 # 按位与运算 # 对整数的二进制表示的每一位与 1 求与,统计结果为非 0 的个数 # 需要移位的次数至少为整数的二进制表示中,数字 1 所在的最高位的位次,不够高效 count, bit = 0, 1 while n and bit <= MAX_INT + 1: if bit & n: count += 1 n -= bit # 左移1位 bit = bit << 1 return count # 快速算法 # 用整数 i 与这个整数减 1 的值 i - 1,按位求与 # 如此可以消除整数的二进制表示中最低位的 1 count = 0 while n: count += 1 n = n & (n-1) return count # 吴老师做法 count = 0 while n: count += 1 n -= n & (-n) return count # 不用与运算的做法(味精喵贡献) # 对2取余,再整除2 count = 0 while n > 0: count += n % 2 n = n / 2 return count
# 颠倒整数 # 给定一个 32 位有符号整数,将整数中的数字进行反转。 # 注意:假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。 # 根据这个假设,如果反转后的整数溢出,则返回 0。 class Solution: def reverse(self, x): """ :type x: int :rtype: int """ if x == 0 or x>2**31: return 0 else: l = list(str(x)) if l[0] == '-': del l[0] l.reverse() l.insert(0,'-') else: l.reverse() while l[0] == '0': del l[0] x = int("".join(l)) if (x < -2**31) or (x > 2**31 - 1): return 0 else: return x
# 字谜分组 # 给定一个字符串数组,将字母异位词组合在一起。 # 字母异位词指字母相同,但排列不同的字符串。 class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ # 字典,key为每一个单词排序后的字符串 # https://juejin.im/pin/5ad07aa5092dcb5883283ffc bucket = {} for ele in strs: key = "".join(sorted(ele)) if key not in bucket.keys(): bucket[key] = [ele] else: bucket[key].append(ele) strs_new = [value for value in bucket.values()] return strs_new
# 爬楼梯 # 假设你正在爬楼梯。需要 n 步你才能到达楼顶。 # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # 注意:给定 n 是一个正整数。 class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ # https://blog.csdn.net/guoziqing506/article/details/51646800 # 走到第i级台阶的走法:f[i] = f[i - 1] + f[i - 2] record = [1,1] if n >= 2: for i in range(2, n + 1): record.append(record[i - 1] + record[i - 2]) return record[n]
# -*- coding: utf-8 -*- """ Created on Tue Sep 22 17:25:44 2020 @author: aksha """ import mysql.connector mydb = mysql.connector.connect( host="localhost", user="akshay", password="Cstar_2033", database="naticus" ) cursor = mydb.cursor() #DISPLAYS RESULT DIRECTLY cursor.execute("CREATE DATABASE naticus") cursor.execute("DROP TABLE applications") cursor.execute("CREATE TABLE applications (app_id INTEGER PRIMARY KEY AUTO_INCREMENT, app_name VARCHAR(255), app_about LONGTEXT, app_perms LONGTEXT, app_classification VARCHAR(10))") #FETCHES RESULT cursor.execute("SHOW TABLES") cursor.execute("SHOW COLUMNS FROM applications") cursor.execute("SELECT * from applications") result = cursor.fetchall() for x in result: print(x) print("\n")
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 import sys import argparse import os """ Learning Argparse """ #TODO - Use this function to validate the input def dir_arg(arg): if os.path.isdir(arg): return arg else: msg = '%s is not a directory' %arg raise argparse.ArgumentTypeError(msg) def main(): print 'this is main' if __name__ == "__main__": #TODO- Add choice parser = argparse.ArgumentParser(description='Inspects and report on the Python test cases.',prog='testimony') #Positional arguments (mandatory arguments) parser.add_argument('square', type=int, help='square a number', nargs='+') #parser.add_argument('fyra', type=int, help='square a number', nargs='+') #parser.add_argument('trice', type=int, nargs='+', help='a list of paths to look for tests cases') #optional argument. Needs one value parser.add_argument('-r','--rank',help ='tell the rank') #optional argument. More than one value can be given. parser.add_argument('-f','--friends',type=str, help ='tell the rank', nargs='+') #optional argument with option, action = 'store_true' which stores the value, true or false. Store_true can be used only with optional arguments. #If this option is not given, value is false parser.add_argument( '-n', '--nocolor', action='store_true', help='Do not use color option') #optional argument with option, choices parser.add_argument('-c','--choi', type=int, choices=[1,2,3],help='optional argument with the option choices') args = parser.parse_args() if args.square: print 'you entered the option square' print '%s'%(args.square) #if args.trice: #print 'you entered the option thrice' #print '%s'%(args.trice) if args.friends: print 'Friends - %s' %(args.friends) if args.choi: print 'your choice -%s' %(args.choi) if args.nocolor: print 'you picked no color -%s' %(args.nocolor) main()
""" The goal of Artificial Intelligence is to create a rational agent (Artificial Intelligence 1.1.4). An agent gets input from the environment through sensors and acts on the environment with actuators. In this challenge, you will program a simple bot to perform the correct actions based on environmental input. Meet the bot MarkZoid. It's a cleaning bot whose sensor is a head mounted camera and whose actuators are the wheels beneath it. It's used to clean the floor. The bot here is positioned at the top left corner of a 5*5 grid. Your task is to move the bot to clean all the dirty cells. Input Format The first line contains two space separated integers which indicate the current position of the bot. The board is indexed using Matrix Convention 5 lines follow representing the grid. Each cell in the grid is represented by any of the following 3 characters: 'b' (ascii value 98) indicates the bot's current position, 'd' (ascii value 100) indicates a dirty cell and '-' (ascii value 45) indicates a clean cell in the grid. Note If the bot is on a dirty cell, the cell will still have 'd' on it. Output Format The output is the action that is taken by the bot in the current step, and it can be either one of the movements in 4 directions or cleaning up the cell in which it is currently located. The valid output strings are LEFT, RIGHT, UP and DOWN or CLEAN. If the bot ever reaches a dirty cell, output CLEAN to clean the dirty cell. Repeat this process until all the cells on the grid are cleaned. Sample Input #00 0 0 b---d -d--d --dd- --d-- ----d Sample Output #00 RIGHT Resultant state -b--d -d--d --dd- --d-- ----d Sample Input #01 0 1 -b--d -d--d --dd- --d-- ----d Sample Output #01 DOWN Resultant state ----d -d--d --dd- --d-- ----d Task Complete the function next_move that takes in 3 parameters posr, posc being the co-ordinates of the bot's current position and board which indicates the board state to print the bot's next move. The codechecker will keep calling the function next_move till the game is over or you make an invalid move. Scoring Your score is (200 - number of moves the bot makes)/40. CLEAN is considered a move as well. Once you submit, your bot will be played on four grids with three of the grid configurations unknown to you. The final score will be the sum of the scores obtained in each of the four grids. Education Links Introduction to AI by Stuart Russell and Peter Norvig Motor cognition """ #!/usr/bin/python # Head ends here def next_move(posr, posc, board): if board[posr][posc] == 'd': return print('CLEAN') for i in range(1, 5): min_r = max(0, posr - i) min_c = max(0, posc - i) max_r = min(4, posr + i) max_c = min(4, posc + i) if board[posr][min_c] == 'd': return print('LEFT') if board[posr][max_c] == 'd': return print('RIGHT') if board[min_r][posc] == 'd': return print('UP') if board[max_r][posc] == 'd': return print('DOWN') for j in range(1, i+1): col = max(min_c, posc-j) if board[min_r][col] == 'd': return print('LEFT') if board[max_r][col] == 'd': return print('LEFT') col = min(max_c, posc+j) if board[min_r][col] == 'd': return print('RIGHT') if board[max_r][col] == 'd': return print('RIGHT') row = max(min_r, posr-j) if board[row][min_c] == 'd': return print('UP') if board[row][max_c] == 'd': return print('UP') row = min(max_r, posr+j) if board[row][min_c] == 'd': return print('DOWN') if board[row][max_c] == 'd': return print('DOWN') print("") # Tail starts here if __name__ == "__main__": # pos = [int(i) for i in input().strip().split()] # board = [[j for j in input().strip()] for i in range(5)] # next_move(pos[0], pos[1], board) # pos = 0, 0 # board = ['b---d', '-d--d', '--dd-', '--d--', '----d'] # next_move(pos[0], pos[1], board) # pos = 0, 1 # board = ['-b--d', '-d--d', '--dd-', '--d--', '----d'] # next_move(pos[0], pos[1], board) pos = 1, 1 board = ['-----', '-b---', '---d-', '---d-', '--d-d'] next_move(pos[0], pos[1], board)
""" You need to construct a feature in a Digital Camera, which will auto-detect and suggest to the photographer whether the picture should be clicked in day or night mode, depending on whether the picture is being clicked in the daytime or at night. You only need to implement this feature for cases which are directly distinguishable to the eyes (and not fuzzy scenarios such as dawn, dusk, sunrise, sunset, overcast skies which might require more complex aperture adjustments on the camera). Input Format A 2D Grid of pixel values will be provided (in regular text format through STDIN), which represent the pixel wise values from the images (which were originally in JPG or PNG formats). Each pixel will be represented by three comma separated values in the range 0 to 255 representing the Blue, Green and Red components respectively. There will be a space between successive pixels in the same row. Input Constraints None of the original JPG or PNG images exceeded 20kB in size. The 2D grids of pixels representing these images will not exceed 1MB. Sample Input This is for the purpose of explanation only. The real inputs will be much larger than this. 0,0,200 0,0,10 10,0,0 90,90,50 90,90,10 255,255,255 100,100,88 80,80,80 15,75,255 The above is an image represented by 3x3 pixels. For each pixel the Blue, Green and Red values are provided, separated by commas. The top left pixel has (Blue=0,Green=0,Red=200). The top-right pixel has (Blue=10,Green=0,Red=0). The bottom-right pixel has (Blue=15,Green=75,Red=255). The bottom-left pixel has (Blue=100,Green=100, Red=88). Output Format Just one word: 'day' or 'night'. Do NOT include the single quote marks. Sample Output (Please note that the sample input shown above does not actually represent a full fledged image!) day A Note on the Test Cases and Sample Tests The test cases have been generated from the 16 images out of which 12 have been shown in the pictures at the top. The two test cases which run as sample test cases when you compile and test, are the pictures marked as img01day.jpg and img09night.jpg respectively. Libraries Libraries available in our Machine Learning/Real Data challenges will be enabled for this contest and are listed here. Please note, that occasionally, a few functions or modules might not work in the constraints of our infrastructure. For instance, some modules try to run multiple threads (and fail). So please try importing the library and functions and cross checking if they work in our online editor in case you plan to develop a solution locally, and then upload to our site. """ def autodetect(data): row = len(data) col = len(data[0].split(' ')) sum = 0.0 num = 0 for i in range(30): line = data[i].split(' ') for j in range(col): r, g, b = line[j].split(',') sum += (int(r) + int(g) + int(b))/3 num += 1 avg = sum/num if avg > 90: print('day') else: print('night') return 0 # data = [] # while True: # try: # line = input() # except EOFError: # break # data.append(line) # data = [ # '0,0,200 0,0,10 10,0,0', # '90,90,50 90,90,10 255,255,255', # '100,100,88 80,80,80 15,75,255', # ] f = open('input00.txt') data = [] for line in f: data.append(line) print('Done') autodetect(data)
# -*- coding: utf-8 -*- """ Created on Sat Nov 23 11:28:44 2019 @author: JUFRI """ import re def arkademy(k): a=re.findall("[a-zA-Z]", k) if a: print("Ini Bukan Angka!") else: x=int(k) print (x) i=1 while i<=x: if i%3!=0 and i%7!=0: print (i) elif i%3==0 and i%7==0: print("Arkademy") elif i%3==0: print("Arka") elif i%7==0: print("Demy") i += 1 arkademy(input("Masukan Angaka disini: "))
# -*- encoding: utf-8 -*- """A module for seeing if you have the right amount of parantheses.""" def proper_parens(string): """Test if the number of "(" matches the number of ")".""" status = 0 for char in string.strip(): if char == "(": status += 1 elif char == ")": status -= 1 if status: return status / abs(status) else: return status
""" 两个字符串是变位词 描述 笔记 数据 评测 写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。 您在真实的面试中是否遇到过这个题? 样例 给出 s = "abcd",t="dcab",返回 true. 给出 s = "ab", t = "ab", 返回 true. 给出 s = "ab", t = "ac", 返回 false. """ class Solution: """ @param s: The first string @param b: The second string @return true or false """ def anagram(self, s, t): lengths, lengtht = len(s), len(t) if lengths != lengtht: return False elif lengths == 0 and lengtht == 0: return True dicts, dictt = {}, {} for i in s: if i not in dicts: dicts[i] = 1 else: dicts[i] += 1 for j in t: if j not in dictt: dictt[j] = 1 else: dictt[j] += 1 if dicts == dictt: return True else: return False
""" 最大数 给出一组非负整数,重新排列他们的顺序把他们组成一个最大的整数。 最后的结果可能很大,所以我们返回一个字符串来代替这个整数。 样例 给出 [1, 20, 23, 4, 8],返回组合最大的整数应为8423201。""" ###https://docs.python.org/2/howto/sorting.html#sortinghowto class Solution: #@param num: A list of non negative integers #@return: A string def largestNumber(self, num): length = len(num) if num == [0]*length: return '0' tempstr = '' num = sorted([str(i) for i in num], cmp = self.helper, reverse=True) for i in num: tempstr += i return tempstr def helper(self, x, y): if (x + y) > (y + x): return 1 else: return -1
""" 给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历。 您在真实的面试中是否遇到过这个题? 样例 对于如下矩阵: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10, 11, 12] ] 返回 [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12] """ class Solution: # @param: a matrix of integers # @return: a list of integers def printZMatrix(self, matrix): row = len(matrix) result = [] if row == 0: return None if row == 1: return matrix[0] col = len(matrix[0]) if col == 1: for i in xrange(row): result.append(matrix[i][0]) return result length = row* col result.append(matrix[0][0]) i, j = 0, 0 while i< row and j< col: #right if (j+ 1)< col: result.append(matrix[i][j+ 1]) j += 1 #down elif (i+ 1)< row: result.append(matrix[i+ 1][j]) i += 1 #downleft while (i+ 1)< row and (j- 1)> -1: result.append(matrix[i+ 1][j- 1]) i += 1 j -= 1 #down if (i+ 1)< row: result.append(matrix[i+ 1][j]) i += 1 #right elif (j+ 1)< col: result.append(matrix[i][j+ 1]) j += 1 #upright while (i- 1)> -1 and (j+ 1)< col: result.append(matrix[i- 1][j+ 1]) i -= 1 j += 1 if i == row- 1 and j == col- 1: break return result
""" 跳跃游戏 II 给出一个非负整数数组,你最初定位在数组的第一个位置。 数组中的每个元素代表你在那个位置可以跳跃的最大长度。    你的目标是使用最少的跳跃次数到达数组的最后一个位置。 样例 给出数组A = [2,3,1,1,4],最少到达数组最后一个位置的跳跃次数是2(从数组下标0跳一步到数组下标1,然后跳3步到数组的最后一个位置,一共跳跃2次)""" #://leetcode.com/discuss/422/is-there-better-solution-for-jump-game-ii?show=422#q422 """ In DP, if you use an array to track the min step at [i], not only will you know the minimum steps needed to get to the destination, but also how to get there. With simple calculation on your array, you can find every optimal road to the end. This unnecessary information lead to unnecessary cost. What we really need to do is to calculate: with k steps, what's the furthest point I can reach. public static int jump(int[] A){ // Jump Game II if(null == A || A.length <= 1) return 0; int minSteps = 0; int furthest = 0; int toCheck = 0; while(furthest < A.length - 1){ int endIndex = furthest; while(toCheck <= endIndex){ furthest = Math.max(furthest, toCheck + A[toCheck]); toCheck++; } if(furthest == endIndex) return -1; // this.time.furthest == last.time.furthest: we're trapped, which means the destination cannot be reached. minSteps++; } return minSteps; } """ class Solution: # @param A, a list of integers # @return an integer def jump(self, A): length = len(A) if length <= 0: return 0 steps, maxjump, i = 0, 0, 0 while maxjump < length- 1: temp = maxjump while i<= temp: maxjump = max(maxjump, i+ A[i]) i += 1 if maxjump == temp: return False steps += 1 return steps
""" 给定一个文档(Unix-style)的完全路径,请进行路径简化。 您在真实的面试中是否遇到过这个题? Yes 样例 "/home/", => "/home" "/a/./b/../../c/", => "/c" 挑战 你是否考虑了 路径 = "/../" 的情况? 在这种情况下,你需返回"/"。 此外,路径中也可能包含双斜杠'/',如 "/home//foo/"。 在这种情况下,可忽略多余的斜杠,返回 "/home/foo"。""" class Solution: # @param {string} path the original path # @return {string} the simplified path def simplifyPath(self, path): length = len(path) if length == 0: return None temp = path.split('/') stack = [] for i in temp: if (i == '.') or (len(i) == 0): continue elif i == '..': if len(stack) != 0: stack.pop() else: stack.append(i) result = '' if len(stack) == 0: return '/' for j in stack: result += '/'+ j return result
def mergeSort(aList): if len(aList)<= 1: return aList mid= len(aList)/ 2 left= mergeSort(aList[:mid]) right= mergeSort(aList[mid:]) return merge(left,right) def merge(left,right): result= [] i,j= 0,0 while i< len(left) and j< len(right): if left[i]<= right[j]: result.append(left[i]) i+= 1 else: result.append(right[j]) j+= 1 result+= left[i:] result+= right[j:] return result if __name__=='__main__': a = [2, 7, 1, 9, -7, 12, 100, 4, 7, 0, 11, -2, 3] print mergeSort(a)
""" 对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。 说明 在面试中我是否需要实现KMP算法? 不需要,当这种问题出现在面试中时,面试官很可能只是想要测试一下你的基础应用能力。当然你需要先跟面试官确认清楚要怎么实现这个题。 样例 如果 source = "source" 和 target = "target",返回 -1。 如果 source = "abcdabcdefg" 和 target = "bcd",返回 1。""" class Solution: def strStr(self, source, target): if source is None and target != "": return -1 if source and target is None: return -1 lengths, lengtht = len(source), len(target) i = 0 if source == " " and target == " ": return 0 if target not in source: return -1 while i < lengths- lengtht + 1: if source[i: i+ lengtht] == target: return i i += 1
texto = 'Hello world' # Nos muestra todo lo que podemos hacer con este tipo de datos. # dir(texto) print(dir(texto)) print(texto.upper()) print(texto.lower()) print(texto.swapcase()) print(texto.capitalize()) print(texto.replace('Hello', 'bye')) print(texto.count('l')) # output 3 porque la "l" sale 3 veces en el texto. print(texto.startswith('Hello')) print(texto.endswith('world')) print(texto.split()) # === print(texto.split(' ')) print(texto.find('o')) # return la posicion donde encontro el caracter # len(text) length print(len(texto)) # Index: Retorna la posicion del caracter. print(texto.index('e')) print(texto.isnumeric()) print(texto.isalpha()) print(texto[4]) print(texto[-1]) # Comienza a lo contrario. name = 'Luis' print('My name is ', name) print('My name is ' + name) print(f'My name is {name}')
x=int(input("1st value")) y=int(input("2nd value")) z=int(input("3rd value")) print(max(x,y,z)) print(min(x,y,z))
for i in range(1,50): if i<=7: print("square of the no.",i*i)
from sys import argv # Python program opening files script, filename = argv with open(filename) as txt: print(f"Here's your file {filename}") print(txt.read()) print("Type the filename again") file_again = input(">") with open(filename) as txt_again: print(txt_again.read())
# This code is contributed by PranchalK """Another AVL tree implementation with inversion count incorporated.""" # An AVL Tree based Python program to # count inversion in an array from typing import Any, List, Optional class Node: """New Node.""" # Allocates a new # Node with the given key and NULL left # and right pointers. def __init__(self, key: Any): self.key: Any = key self.left: Optional[Node] = None self.right: Optional[Node] = None self.height: int = 0 self.size: int = 1 def display_keys(self: Node, space: str = '\t', level: int = 0) -> None: """Display all the keys in a Node horizontally for clear visualization. For AVL trees, also display each node's height. """ # if the node is empty, print the empty set symbol if self is None: print(space * level + '∅') return # if the node is a leaf, print node.key if self.left is None and self.right is None: print(space * level, str(self.key), str(self.height)) return # if the node has children, show right subtree up, left subtree down display_keys(self.right, space, level + 1) print(space * level, str(self.key), str(self.height)) display_keys(self.left, space, level + 1) def height(N: Optional[Node]) -> int: """Get the height of the tree rooted with N.""" if N is None: return 0 return N.height def size(N: Optional[Node]) -> int: """Get the size of the tree rooted with N.""" if N is None: return 0 return N.size def balance_factor(N: Optional[Node]) -> int: """Get Balance factor of Node N.""" if N is None: return 0 return height(N.left) - height(N.right) def right_rotate(y: Node) -> Node: """Right rotate a subtree rooted with y.""" x = y.left T2 = x.right # Perform rotation x.right = y y.left = T2 # Update heights y.height = max(height(y.left), height(y.right)) + 1 x.height = max(height(x.left), height(x.right)) + 1 # Update sizes y.size = size(y.left) + size(y.right) + 1 x.size = size(x.left) + size(x.right) + 1 # Return new root return x def left_rotate(x: Node) -> Node: """Left rotate a subtree rooted with x.""" y = x.right T2 = y.left # Perform rotation y.left = x x.right = T2 # Update heights x.height = max(height(x.left), height(x.right)) + 1 y.height = max(height(y.left), height(y.right)) + 1 # Update sizes x.size = size(x.left) + size(x.right) + 1 y.size = size(y.left) + size(y.right) + 1 # Return new root return y def insert(node: Optional[Node], key: Any, inversion_count: List) -> Node: """Insert a new key to the tree rooted with `node`. Meanwhile, update `inversion_count`. Note ---- `inversion_count` is typed as a `List` since we need it to be mutable so that its value can be changed after each recursion call (while `int` is immutable). """ # 1. Perform the normal BST rotation if node is None: return Node(key) if key < node.key: node.left = insert(node.left, key, inversion_count) # To count inversions, for each inserted node, we need to find number of # elems greater than `key` that have been inserted before `key`. # Whenever inserting key < node, we go down left a level, so inversion_count # increases by 1(node) + node.right. # Note: Here we only consider first-time insertion of a list into an # empty tree. Subsequent delete/insert does not alter inversion_count. inversion_count[0] += size(node.right) + 1 else: node.right = insert(node.right, key, inversion_count) # 2. Update height and size of this ancestor node node.height = max(height(node.left), height(node.right)) + 1 node.size = size(node.left) + size(node.right) + 1 # 3. Get the balance factor of this ancestor # node to check whether this node became # unbalanced balance = balance_factor(node) # If this node becomes unbalanced, # then there are 4 cases # Left Left Case if (balance > 1 and key < node.left.key): return right_rotate(node) # Right Right Case if (balance < -1 and key > node.right.key): return left_rotate(node) # Left Right Case if balance > 1 and key > node.left.key: node.left = left_rotate(node.left) return right_rotate(node) # Right Left Case if balance < -1 and key < node.right.key: node.right = right_rotate(node.right) return left_rotate(node) # return the (unchanged) node pointer return node def get_inversion_count(_list: List) -> int: """Count inversions in a list.""" root = None # Create empty AVL Tree inversion_count = [0] # Initialize inversion_count # Starting from first element, insert all # elements one by one in an AVL tree. for item in _list: # Note that address of inversion_count is passed # as insert operation updates inversion_count by # adding count of elements greater than # _list[i] on left of _list[i] root = insert(node=root, key=item, inversion_count=inversion_count) return inversion_count[0] # Driver Code if __name__ == '__main__': _list = [ (23, "23"), (4, "4"), (30, "30"), (11, "11"), (7, "7"), (34, "34"), (20, "20"), (24, "24"), (22, "22"), (1, "1"), ] # Count inversions print("Number of inversions count are :", get_inversion_count(_list)) # Display tree structure root: Node = None inversion_count = [0] for item in _list: root = insert(node=root, key=item[0], inversion_count=inversion_count) # Note: the following displayed tree is different from that from avl_tree.py. # Both are valid AVL trees, but the structures are different due to code # implementation discrepencies. display_keys(root)
# Licensed under MIT License. # See LICENSE in the project root for license information. """Timsort implementation.""" # This algorithm finds subsequences that are already ordered (called "runs") and uses # them to sort the remainder more efficiently. It is a hybrid of insertion sort and # merge sort, taking advantage of the merits of both sorting techniques. # For a detailed introduction, cf. # https://svn.python.org/projects/python/trunk/Objects/listsort.txt # The complete C implementation code of this algorithm in Python source can be found: # https://hg.python.org/cpython/file/tip/Objects/listobject.c from typing import List, Sequence import copy import random def find_minrun(n: int) -> int: """Compute a good value for the minimum run length. Natural runs shorter than this are boosted artificially via binary insertion. """ r = 0 # Becomes 1 if any bits are shifted off assert n >= 0 while n >= 64: # The target of this while-loop: # If n is an exact power of 2, return 32; # otherwise, return int k in [32,64] such that n/k is close to, but strictly # less than, an exact power of 2 that is larger than 2^1=2. # | is `OR by bits`, & is `AND by bits`. ie r = r|(n&1). # The next two lines of code work as follows: # 1. If n is an exact power of 2, then for all loops, n&1=0, r=r|0=0|0=0, # and n is halved, until n=64 and is halved to 32, with r=0, so returns 32. # 2. Otherwise, then there must be at least one `1` among the second to the # last digits of n's binary form, eg.10010000. We scan from the rightmost digit # to the left, and whenever a 1 is met, r is 1. n will decrease to the n//2^k # that is closest to but less than 64. The target is met. # # In essence, this procedure is simply taking the first 6 bits of n, and add # 1 if any of the remaining bits is 1 (we call a bit that is 1 a "set bit"). r |= n & 1 n >>= 1 # move n's binary form all 1 digit to the right, ie n = n // 2 # If n < 64, just return n, since it is too small to bother with fancy stuff return n + r def insertion_sort(li: Sequence, left: int, right: int) -> List: """Sort [left, right) of a list in non-decreasing order using insertion sort in-place.""" # Keep the initial portion sorted, and insert the remaining elems one by one at # the right position. # Time complexity: O(N^2) (a little faster than bubble sort), space complexity: O(N) for i in range(left+1, right): # list.pop(i) removes and returns the ith elem current = li[i] j = i - 1 while j >= left and current < li[j]: li[j+1] = li[j] j -= 1 # When current >= nums[j], this is the place to be. # Note: list.insert(k) inserts BEFORE the kth elem li[j+1] = current def merge(li: Sequence, left_index: int, mid_index: int, right_index: int) -> None: """Merge two sorted sublists into one sorted list in-place. The two sorted sublists are: `li[l:m]`, `li[m:r]`. """ left_li = li[left_index : mid_index] right_li = li[mid_index : right_index] i, j, k = 0, 0, left_index while i < len(left_li) and j < len(right_li): if left_li[i] <= right_li[j]: li[k] = left_li[i] i += 1 else: li[k] = right_li[j] j += 1 k += 1 # Copy the remainders while i < len(left_li): li[k] = left_li[i] i += 1 k += 1 while j < len(right_li): li[k] = right_li[j] j += 1 k += 1 def tim_sort(li: Sequence) -> List: """Tim sort a list and return a new list, leaving the original one intact.""" minrun = find_minrun(len(li)) for start in range(0, len(li), minrun): # Note that insertion_sort sorts [left, right) end = min(start + minrun, len(li)) insertion_sort(li, start, end) size = minrun while size < len(li): for left in range(0, len(li), 2 * size): # Since [left : left+size] and [left+size : left+2*size] have been sorted # (when size=minrun, these two have been sorted by insertion_sort; when # size is doubled, they are sorted by the previous loop), we can use merge. mid = min(left + size, len(li)) right = min(left + 2 * size, len(li)) merge(li, left, mid, right) size *= 2 def _count_run(li: Sequence, lo: int, hi: int) -> int: """Count the length of the run beginning at lo, in the slice [lo, hi). lo < hi is required on entry. """ # "A run" is either the longest non-decreasing sequence, or the longest strictly # decreasing sequence. `descending` is False in the former case, True in the latter. # Note: This function is not required by tim_sort(), so we make it internal. assert lo < hi # descending = False lo += 1 if lo == hi: return 1 n = 2 # run count if li[lo] < li[lo-1]: # descending = True for lo in range(lo+1, hi): if li[lo] >= li[lo-1]: break n += 1 else: for lo in range(lo+1, hi): if li[lo] < li[lo-1]: break n += 1 return n ######################### # Driver code sample_list = random.sample(range(1, 2000), 1000) # sample_list = [-1,5,0,-3,11,9,-2,7,0] print("Count run:", _count_run(sample_list, lo=1, hi=len(sample_list))) # Note: in the next line, using `orig = sample_list` won't work (orig will be changed). # This is because we don't have two lists; this assignment just copies the REFERENCE to # sample_list, not the actual list object. Use li.copy() or list(li) instead. orig_sample = sample_list.copy() # orig_sample = list(sample_list) tim_sort(sample_list) # Note: sorted() is not in-place; it produces a new list, leaving the original intact sorted_by_python = sorted(sample_list) assert sample_list == sorted_by_python # Demonstrate that only copy.deepcopy() is totally reliable. # For an non-nested list, use li.copy() or list(li). For a nested list (that has lists as its elems), we can only use `import copy; copy.deepcopy(li)` to do copying properly. sample_list = [[-1,5,0],-3,11,9,-2,7,0] copied = {} copied['.copy()'] = sample_list.copy() copied['list()'] = list(sample_list) copied['*1'] = sample_list * 1 copied['copy.copy()'] = copy.copy(sample_list) copied['copy.deepcopy()'] = copy.deepcopy(sample_list) sample_list[0].append(11) print("Sample:", sample_list) print("Copied:") # Note that dict.items() is only an iterator for dict [print(key, ":", value) for key, value in copied.items()]
# Licensed under MIT License. # See LICENSE in the project root for license information. """Linked list implementation.""" from typing import Any class Node: """Node in a linked list.""" def __init__(self, data: Any) -> None: self.data = data self.next = None class LinkedList: """Linked list.""" def __init__(self) -> None: self.head = None def __len__(self): """Length of a linked list; 0 if empty. Usage like `len(linkedlist)`.""" result = 0 current = self.head while current is not None: result += 1 current = current.next return result def __getitem__(self, position): """Get the element at `position` (starting from 0); if not found, return `None`. Usage like `linkedlist[2]`. """ i = 0 current = self.head while current is not None: if i == position: return current.data current = current.next i += 1 return None def append(self, value: Any) -> None: """Append an item to the end of the linked list.""" # `append` Node(value) to `self` by setting self.head.next to # current_node & if current_node is None, if self.head is None: self.head = Node(value) else: current_node = self.head while current_node.next is not None: current_node = current_node.next current_node.next = Node(value) def show_elements(self) -> None: """Show elements in a linked list.""" current = self.head outlist = [] while current is not None: outlist.append(current.data) current = current.next print(outlist) # # the brute force method to make a linked list # list1 = LinkedList() # list1.head = Node(2) # list1.head.next = Node(3) # list1.head.next.next = Node(4) # print(list1.head.next.next.data) # make a linked list using `append` method defined in class list2 = LinkedList() list2.append(2) list2.append(3) list2.append(5) list2.append(9) print("length of list2: ", len(list2)) print("get element #2 (1st being #0): ", list2[2]) print("get element #11 (non-existent): ", list2[11]) # Reverse a linked list # # Check an example. To reverse (2,3,5) to (5,3,2), ie to change # `None.next = 2 = old list head, 2.next = 3, 3.next = 5, 5.next = None` to # `None.next = 5 = new list head, 5.next = 3, 3.next = 2, 2.next = None`, # as Step1: set prev = None, current = 2, next_node = 3 = 2(current).next; # Step2, do the reversion: set 2(current).next = None(prev); # Step3, move one elem down the list -- # Notice that in order to use a while-loop, we need to move prev to 2(current) # and current to 3(next_node) for the iteration to move farther down the list. # So now that prev & current have been moved, set next_node = 5 = current.next, # and do the `current.next = prev` again (ie 3.next = 2). # It's obvious that what we need to loop over (ie put in the while-loop) is: # `next_node = current.next; current.next = prev; prev = current; current = # next_node`. # Iterate till current is None, and prev is 5. Outside the loop, assign 5(prev) # as the new list head. The code is completedt. def reverse_linked_list(list): """Reverse a linked list.""" # for empty list, the reverse is empty, too if list.head is None: return current = list.head prev = None while current is not None: # track the next node next_node = current.next # modify the current node current.next = prev # update prev & current prev = current current = next_node list.head = prev # show orig list2 list2.show_elements() reverse_linked_list(list2) # show reversed list2 list2.show_elements()
import random def MAGIC_NUMBER_CONSOLE_TITLE(): print("\n====MAGIC NUMBERS====") print("---------------------") print("= Try to guess the ==") print("= magic number in ==") print("= {} chances or less = ".format(chances)) print("=====================") # generates a list of random, positive integers # @param1 number of integers # @param2 inclusive upper random range # @return list of numbers def r_number_gen(count, max_int): my_number = [random.randint(0,max_int)] if count > 1: my_number.extend(r_number_gen(count-1,max_int)) return my_number def magic_number_program(chances): #difficulty settings TOTAL_NUMBERS = 3 MAX_INT = 9 magic_numbers = r_number_gen(TOTAL_NUMBERS,MAX_INT) correct_guess = False previous_guess = [] attempt = 0 while attempt<chances: #get the user's guess attempt_string = "\n==========\nThis is attempt {} of {}".format(attempt+1,chances) user_number = int(input("{}\nEnter a number between 0 and {} (inclusive): ".format(attempt_string,MAX_INT))) #check the user's previous guesses to avoid repeat if user_number in previous_guess: print("\nYou've already guessed that number!") else: if user_number in magic_numbers: print("\n{} is a magic number!".format(user_number)) print("Congratulations! You've won!") return else: print("\n{} was not the correct number.".format(user_number)) if attempt+1==chances: print("OOOOOOH, YOU HAVE FAILED!!!!") previous_guess.append(user_number) attempt+=1 magic_number_program(3)
def foo (): width = int (input ("Введите ширину: ")) height = int (input ("Введите высоту: ")) s = input ("Из чего состоит рамка: ") if (width < height): #Если ширина меньше высоты j=1 i=0 for i in range(0, width-1): print(s, end='') while (i < height): while (j < width): print (s, end=" "*(width-2)) print (s) j+=1 i+=1 for i in range(0, width-1): print(s, end='') if (width > height): #Если высота меньше ширины j=0 i=1 for i in range(0, width-1): print(s, end='') while (i < width): while (j < height): print (s, end=" "*(width-2)) print (s) j+=1 i+=1 for i in range(0, width-1): print(s, end='') return s print (foo())
"""Simple model building blocks.""" import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class PositionAwareAttention(nn.Module): """ A position-augmented attention layer where the attention (adapted from https://github.com/yuhaozhang/tacred-relation/blob/master/model/layers.py#L42) weight is a = T' . tanh(Ux) where x is the input Args: input_size: input size attn_size: attention size feature_size: features size """ def __init__(self, input_size, attn_size, feature_size): super(PositionAwareAttention, self).__init__() self.input_size = input_size self.feature_size = feature_size self.attn_size = attn_size self.ulinear = nn.Linear(input_size, attn_size) if feature_size > 0: self.wlinear = nn.Linear(feature_size, attn_size, bias=False) else: self.wlinear = None self.tlinear = nn.Linear(attn_size, 1) self.init_weights() def init_weights(self): """Initialize weights. Returns: """ self.ulinear.weight.data.normal_(std=0.001) if self.wlinear is not None: self.wlinear.weight.data.normal_(std=0.001) self.tlinear.weight.data.zero_() # use zero to give uniform attention at the beginning def forward(self, x, mask, f=None): """Model forward. Args: x: B x seq_len x input_size mask: B x seq_len (True is for valid elements, False is for padded ones) f: B x seq_len x feature_size Returns: averaged output B x seq_len x attn_size """ batch_size, seq_len, _ = x.size() x_proj = self.ulinear(x.contiguous().view(-1, self.input_size)).view( batch_size, seq_len, self.attn_size ) if self.wlinear is not None: f_proj = ( self.wlinear(f.view(-1, self.feature_size)) .contiguous() .view(batch_size, seq_len, self.attn_size) ) projs = [x_proj, f_proj] else: projs = [x_proj] scores = self.tlinear(torch.tanh(sum(projs)).view(-1, self.attn_size)).view( batch_size, seq_len ) # mask padding scores.data.masked_fill_(~mask.data, -float("inf")) weights = F.softmax(scores, dim=1) # weighted average input vectors outputs = weights.unsqueeze(1).bmm(x).squeeze(1) return outputs class Attn(nn.Module): """Attention layer, with option for residual connection. Args: size: input size dropout: dropout perc num_heads: number of heads residual: use residual or not """ def __init__(self, size, dropout, num_heads, residual=False): super(Attn, self).__init__() self.norm_q = torch.nn.LayerNorm(size) self.norm = torch.nn.LayerNorm(size) self.dropout = nn.Dropout(dropout) self.attn_layer = nn.MultiheadAttention(size, num_heads) self.residual = residual def forward(self, q, x, key_mask, attn_mask): """Model forward. Args: q: query (L x B x E) x: key/value (S x B x E) key_mask: key mask (B x S) attn_mask: attention mask (L x S) Returns: output tensor (L x B x E), attention weights (B x L x S) """ y = self.norm(x) # print(q.shape, y.shape, y.shape) assert y.shape[1] == q.shape[1], "Dimensions are wrong for attention!!!!!" output, weights = self.attn_layer( self.norm_q(q), y, y, key_padding_mask=key_mask, attn_mask=attn_mask ) res = self.dropout(output) if self.residual: res += q return res, weights class SelfAttn(nn.Module): """Self-attention layer, with option for residual connection. Args: size: input size dropout: dropout perc num_heads: number of heads residual: use residual or not """ def __init__(self, size, dropout, num_heads, residual=False): super(SelfAttn, self).__init__() self.norm = torch.nn.LayerNorm(size) self.dropout = nn.Dropout(dropout) self.attn_layer = nn.MultiheadAttention(size, num_heads) self.residual = residual def forward(self, x, key_mask, attn_mask): """Model forward. Args: q: query/key/value (L x B x E) key_mask: key mask (B x L) attn_mask: attention mask (L x L) Returns: output tensor (L x B x E), attention weights (B x L x L) """ y = self.norm(x) output, weights = self.attn_layer( y, y, y, key_padding_mask=key_mask, attn_mask=attn_mask ) res = self.dropout(output) if self.residual: res += x return res, weights class Feedforward(nn.Module): """Applies linear layer with option for residual connection. By default, adds no dropout. Args: size: input size output: output size dropout: dropout perc residual: use residual or not activation: activation function """ def __init__(self, size, output, dropout=0.0, residual=False, activation=None): super(Feedforward, self).__init__() self.norm = torch.nn.LayerNorm(size) self.dropout = nn.Dropout(dropout) self.linear_layer = nn.Linear(size, output) self.residual = residual self.activation = activation def forward(self, x): """Apply residual connection to any sublayer with the same size. Args: x: input tensor (*, input size) Returns: output tensor (*, output size) """ res = self.linear_layer(self.norm(x)) if self.activation is not None: res = self.activation(res) res = self.dropout(res) if self.residual: res += x return res class AttnBlock(nn.Module): """Attention layer with FFN (like Transformer) Args: size: input size ff_inner_size: feedforward intermediate size dropout: dropout perc num_heads: number of heads """ def __init__(self, size, ff_inner_size, dropout, num_heads): super(AttnBlock, self).__init__() self.attn = Attn(size, dropout, num_heads, residual=True) self.ffn1 = Feedforward( size, ff_inner_size, dropout, residual=False, activation=torch.nn.ReLU() ) self.ffn2 = Feedforward( ff_inner_size, size, dropout, residual=False, activation=None ) def forward(self, q, x, key_mask, attn_mask): """Model forward. Args: q: query (L x B x E) x: key/value (S x B x E) key_mask: key mask (B x S) attn_mask: attention mask (L x S) Returns: output tensor (L x B x E), attention weights (B x L x L) """ out, weights = self.attn(q, x, key_mask, attn_mask) out = out + self.ffn2(self.ffn1(out)) return out, weights class SelfAttnBlock(nn.Module): """Self-attention layer with FFN (like Transformer) Args: size: input size ff_inner_size: feedforward intermediate size dropout: dropout perc num_heads: number of heads """ def __init__(self, size, ff_inner_size, dropout, num_heads): super(SelfAttnBlock, self).__init__() self.attn = SelfAttn(size, dropout, num_heads, residual=True) self.ffn1 = Feedforward( size, ff_inner_size, dropout, residual=False, activation=torch.nn.ReLU() ) self.ffn2 = Feedforward( ff_inner_size, size, dropout, residual=False, activation=None ) def forward(self, x, key_mask, attn_mask): """Model forward. Args: q: query/key/value (L x B x E) key_mask: key mask (B x L) attn_mask: attention mask (L x L) Returns: output tensor (L x B x E), attention weights (B x L x L) """ out, weights = self.attn(x, key_mask, attn_mask) out = out + self.ffn2(self.ffn1(out)) return out, weights class MLP(nn.Module): """Defines a MLP in terms of the number of hidden units, the output dimension, and the total number of layers. Args: input_size: input size num_hidden_units: number of hidden units (None is allowed) output_size: output size num_layers: number of layers dropout: dropout perc residual: use residual activation: activation function """ def __init__( self, input_size, num_hidden_units, output_size, num_layers, dropout=0.0, residual=False, activation=torch.nn.ReLU(), ): super(MLP, self).__init__() assert num_layers > 0 if num_hidden_units is None or num_hidden_units <= 0: assert ( num_layers == 1 ), f"You must provide num_hidden_units when more than 1 layer" self.layers = [] in_dim = input_size for _ in range(num_layers - 1): self.layers.append( Feedforward(in_dim, num_hidden_units, dropout, residual, activation) ) in_dim = num_hidden_units # The output layer has no residual connection, no activation, and no dropout self.layers.append( Feedforward( in_dim, output_size, dropout=0.0, residual=False, activation=None ) ) self.layers = nn.ModuleList(self.layers) def forward(self, x): """Model forward. Args: x: (*, input size) Returns: tensor (*, output size) """ out = x for i in range(len(self.layers)): out = self.layers[i](out) return out class CatAndMLP(nn.Module): """Concatenate and MLP layer. Args: size: input size num_hidden_units: number of hidden unites output_size: output size num_layers: number of layers """ def __init__(self, size, num_hidden_units, output_size, num_layers): super(CatAndMLP, self).__init__() self.proj = MLP( size, num_hidden_units, output_size, num_layers, dropout=0, residual=False, activation=torch.nn.ReLU(), ) def forward(self, x, dim=3): """Model forward. Args: x: List of (*, *) tensors dim: Dim to concatenate Returns: tensor (*, output size) """ y = torch.cat(x, dim) res = self.proj(y) return res class NormAndSum(nn.Module): """Layer norm and sum embeddings. Args: size: input size """ def __init__(self, size): super(NormAndSum, self).__init__() self.norm = torch.nn.LayerNorm(size) def forward(self, in_tensors): """Model forward. Args: in_tensors: List of input tensors (D, *) Returns: output tensor (*) """ out_tensor = torch.stack(in_tensors, dim=0) out_tensor = self.norm(out_tensor) out_tensor = out_tensor.sum(dim=0) return out_tensor class PositionalEncoding(nn.Module): """Positional encoding. Taken from https://nlp.seas.harvard.edu/2018/04/03/attention.html. Args: hidden_dim: hiddem dim max_len: maximum position length """ def __init__(self, hidden_dim, max_len=5000): super(PositionalEncoding, self).__init__() # Compute the positional encodings once in log space. pe = torch.zeros(max_len, hidden_dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp( torch.arange(0, hidden_dim, 2) * -(math.log(10000.0) / hidden_dim) ) pe[torch.arange(0, max_len), 0::2] = torch.sin(position * div_term) # If hidden dim is odd, 1::2 will contain floor(hidden_dim/2) indexes. # div_term, because it starts at 0, will contain ceil(hidden_dim/2) indexes. # So, as cos is 1::2, must remove last index so the dimensions match. if hidden_dim % 2 != 0: pe[torch.arange(0, max_len), 1::2] = torch.cos(position * div_term)[:, :-1] else: pe[torch.arange(0, max_len), 1::2] = torch.cos(position * div_term) # raw numerical positional encodinf # pe = torch.stack(hidden_dim*[torch.arange(max_len)]).transpose(0,1).long() # Add one for PAD positional for unknown aliases # There were some weird bugs by doing assignment from dims 0 to # hidden_dim if making pe original have an extra column of zeros pe = torch.cat([pe, torch.zeros(1, hidden_dim).float()]) pe = pe.unsqueeze(0) # This allows the tensor pe to be saved in state dict but not trained self.register_buffer("pe", pe) def forward(self, x, spans): """Model forward. Args: x: tensor (*,*) spans: spans to index into positional embedding to add to x Returns: tensor (*,*) """ x = x + Variable(self.pe[:, spans], requires_grad=False) x = x.squeeze(0) return x
""" Module provides datastructures for tabular data, and function for reading csv files. """ from collections import defaultdict import csv import numbers class DataTable: """ Two-dimensional, potentially heterogeneous tabular data. Can be thought of as a dict-like container for List objects, where the key represents the column name and value is of type list, with each element in list holding data for each row for that column. Data representation: For example, for input tabular data: -------------- A,B,C,D 1,'x', 5.0, 3 2,'y', 8.2, 4 -------------- can be represented as follows: { 'A': [1, 2], 'B': ['x', 'y'], 'C': [5.0, 8.2], 'D': [3, 4] } Attributes: data_table: A dictionary holding tabular data. """ def __init__(self, data_table: dict): """ Creates an instance of Datatable.. Given a dictionary, with keys as column names, and values as list with each element in list as row value for that column. Args: data_table: Dictionary containing data to be stored in this data table. """ self.data_table = data_table def __getitem__(self, col_name: str) -> list: """ Gets column data as list for the input column name. Validates input column name to ensure it exists in the data and returns the corresponding row values as list. Args: col_name: Name of the column for which data values need to be returned. Returns: A list containing row values for the input column. For example: ['A', 'B', 'C'] Raises: ValueError: If the column name does not exist in this DataTable. """ self._validate_col_name(col_name) return self.data_table[col_name] def __setitem__(self, col_name: str, values: list): """ Sets column data given a column name and list with row values. Args: col_name: Name of the column for which data values need to be saved. values: Row values for the column. Returns: """ self.data_table[col_name] = values def _validate_col_name(self, col_name: str): """ Validates input column name. Args: col_name: Name of the column to be validated. Raises: ValueError: If the column name does not exist in this DataTable. """ if col_name not in self.data_table: raise ValueError("Invalid column name: {}, valid values are: {}" .format(col_name, self.data_table.keys())) def count(self, group_by: str) -> dict: """ Counts the number of rows for each value in a given column. Args: group_by: Name of the column by which the rows must be grouped. Returns: A dict mapping group_by column value to the number of rows with it. example: {'A': 2, 'B': 3} Raises: ValueError: If the column name does not exist in this DataTable. """ self._validate_col_name(group_by) result = defaultdict(int) group_by_values = self.data_table[group_by] for group_by_value in group_by_values: result[group_by_value] += 1 return result def sum(self, col_name: str, group_by: str) -> dict: """ Calculates sum of values in a column, grouped by another column. Args: col_name: Name of the column for which values must be added. group_by: Name of the column by which the rows must be grouped. Returns: A dict mapping group_by column value to the sum of values from another column. example: {'A': 45, 'B': 36} Raises: ValueError: If the column name does not exist in this DataTable. """ self._validate_col_name(col_name) self._validate_col_name(group_by) result = defaultdict(int) col_values = self.data_table[col_name] group_by_values = self.data_table[group_by] for col_value, group_by_value in zip(col_values, group_by_values): if not isinstance(col_value, numbers.Number): raise TypeError("Column data must be of numeric type, but found: {}." .format(type(col_value)) ) result[group_by_value] += col_value return result def avg(self, col_name: str, group_by: str) -> dict: """ Calculates average of values in a column, grouped by another column. Args: col_name: Name of the column for which values must be averaged. group_by: Name of the column by which the rows must be grouped. Returns: A dict mapping group_by column value to the average of values from another column. example: {'A': 45.3, 'B': 36.2} Raises: ValueError: If the column name does not exist in this DataTable. """ self._validate_col_name(col_name) self._validate_col_name(group_by) sum = self.sum(col_name, group_by) count = self.count(group_by) return {k: sum[k]/count[k] for k in sum.keys()} def map(self, col_name: str, func): """ Maps each value in a given column with the mapping function. Args: col_name: Name of the column for which values must be added. func: Mapping function that takes one argument, and maps the intput row values. Raises: ValueError: If the column name does not exist in this DataTable. """ self._validate_col_name(col_name) self.data_table[col_name] = [func(x) for x in self.data_table[col_name]] def read_csv(filepath: str) -> DataTable: """ Reads input file in CSV format, with header in first line. Args: filepath: Input file path that should be read. Returns: An instance of DataTable containing data from the input file. For example, for input file: -------------- A,B,C,D 1,'x', 5.0, 3 2,'y', 8.2, 4 -------------- will create instance of DataTable using following dict: { 'A': ['1', '2'], 'B': ['x', 'y'], 'C': ['5.0', '8.2'], 'D': ['3', '4'] } The dictionary used for creating DataTable will contain all row values as str data-type. Raises: ValueError: If the column count is not consistent in all rows, including header. """ col_names = {} data = {} row_num = 1 with open(filepath, 'r') as file: for row_values in csv.reader(file): if row_num == 1: for idx, col_name in enumerate(row_values): col_names[idx] = col_name data[idx] = [] else: if len(row_values) != len(col_names): raise ValueError("Mismatch found in column count:{} and row values count:{}, row: {}." .format(len(col_names), len(row_values), row_values)) for idx, col_value in enumerate(row_values): data[idx].append(col_value) row_num += 1 data_with_header = {col_names[idx]: data[idx] for idx in range(len(col_names))} return DataTable(data_with_header)
a, b = 23, 21 c = 2**8-1 # To show what happens when you select a bad set of values, # set c = 2**8 and watch what happens to 'x % 2' # It will always flip between 0 and 1 -- i.e. is 100% predictable def lcg_generate(x): return (a * x + b) % c # This generates a full set of cards: each suit with each type # To understand the syntax, Google for "list comprehensions" cards = [s+n for s in "SDHC" for n in "A23456789XJQK"] # The list comprehension above is equivalent to the for loops below # cards = [] # for suit in 'SDHC': # for card_type in "A23456789XJQK": # cards.append(suit + card_type) if __name__ == "__main__": x = 19 print("Starting the LCG with seed =", x) for i in range(15): x = lcg_generate(x) print("%s (%d %d)" % (cards[x % 52], x, x % 2))
# Instead of writing it ourselves, let's use a pre-written one from PyCrypto # PyCrypto is the library we'll be using for the project # To start with, let's import the XOR cipher from Crypto.Cipher import XOR # We'll also use their random to get random bits for our key from Crypto.Random import get_random_bytes m = "Jerry Seinfeld will be chosen to star in the new Microsoft commercial".encode("ascii") key = get_random_bytes(16) print(m) # Create a new cipher object and pass in the key to be used # For PyCrypto, the key must be between 1 and 32 bytes -- likely to discourage real world usage cipher = XOR.new(key) c = cipher.encrypt(m) print(c) # We need to reset the cipher as, by default, the cipher would continue from where it left off # (i.e. it assumes you're going to continue encrypting or decrypting) cipher = XOR.new(key) m_dash = cipher.decrypt(c) print(m_dash)
import sys def validate(month, day): halloween = (month == "OCT" and day == 31) christmas = (month == "DEC" and day == 25) return (halloween or christmas) input = sys.stdin.readline().rstrip().split(' ') month = input[0] day = int(input[1]) if (validate(month, day)): print("yup") else: print("nope")
from __future__ import annotations from typing import List class Polynomial: def __init__(self, coeffs: List[float]): self.coeffs = coeffs self.deg = len(coeffs) def __str__(self) -> str: output = "" for i in reversed(range(self.deg)): output += f"{self.coeffs[i]}x^{i} " return output def derivative(self) -> Polynomial: """Получить производную полинома. Returns: Полином, являющийся производной данного. """ return Polynomial([deg * coeff for deg, coeff in enumerate(self.coeffs[1:], start=1)]) def calc(self, x: float) -> float: """Вычислить полином в точке. Args: x: точка, в которой вычисляется значение полинома Returns: Значение данного полинома в точке x. """ res = .0 for i in range(self.deg): res += (x ** i) * self.coeffs[i] return res def integrate(self, x1: float, x2: float) -> float: """Вычисление интеграла Римана полинома по формуле Ньютона-Лейбница. Args: x1 (float): нижний предел x2 (float): верхний предел Returns: Значение интеграла. """ new_coeffs = [coeff / (deg + 1) for deg, coeff in enumerate(self.coeffs)] new_coeffs.insert(0, .0) antiderivative = Polynomial(new_coeffs) return antiderivative.calc(x2) - antiderivative.calc(x1) def multiply(self, poly: Polynomial) -> Polynomial: """Умножить этот полином на другой. Args: poly (Polynomial): полином, на который будет умножен текущий полином Returns: Новый полином, являющийся результатом умножения двух полиномов. """ new_polynom = [] size = max(self.deg, poly.deg) for i in range(size): new_polynom.append(self.coeffs[i] * poly.coeffs[i]) return Polynomial(new_polynom)
from math import floor def recursive_merge_sort(A, p, r): if p >= r: return A else: q = floor((p + r) / 2) recursive_merge_sort(A, p, q) recursive_merge_sort(A, q + 1, r) merge(A, p, q, r) def merge(A, p, q, r): n1 = q - p + 1 n2 = r - q B = A[p:q+1] B.append(1024) C = A[q+1:r+1] C.append(1024) i, j = 0, 0 for k in range(p, r+1): if B[i] <= C[j]: A[k] = B[i] i += 1 else: A[k] = C[j] j += 1 return A if __name__ == '__main__': A = [12, 9, 3, 7, 14, 11] n = len(A) p = 0 r = n - 1 print(A) recursive_merge_sort(A, p, r) print(A)
text = input() words=text.split() wordslen=len(words) letter=0 for l in words: letter+= len(l) print(letter/wordslen)
# Tutorial: "A tour of Data Assimilation methods" # Model: Lorenz-63 # DA Methods: Nudging, 3D-Var, 4D-Var, Particle Filter, EnKF, Hybrid # # Purpose: # Tutorial 1 focuses on generating the nature run, free run, and # Lyapunov Exponents of the nature system, the Lorenz-63 model. # # import numpy as np from class_lorenz63 import lorenz63 from class_state_vector import state_vector from class_obs_data import obs_data from class_da_system import da_system #----------------------------------------------------------------------- # Tutorial 1: # # Exercises: # (1) Compute a nature run # (2) Compute a free run with perturbed initial conditions # (3) Compute the Jacobian of the system for its entire trajectory # (4) Compute the Lyapunov exponents of the nature system # (5) Compute the observations to be used by the data assimilation system # # Additional exercises: # (1) Repeat with different model parameters # (2) Compute the forward and backward Lyapunov vectors # (3) Compute the Covariant Lyapunov Vectors #----------------------------------------------------------------------- #----------------------------------------------------------------------- # Step 1a: #----------------------------------------------------------------------- # Run the python program: # python generate_nature_run.py # # This will generate a file containing the nature run as a 'state_vector' # object. The object contains the nature run trajectory as well as other # important information about the nature run and its model parameters, # similarly to a netcdf file. # # Run the python program: # plot_nature_run.py # # Explore the dataset. # #----------------------------------------------------------------------- # Step 1b: #----------------------------------------------------------------------- # Generate a free run. # # In generate_nature_run.py, Add a small perturbation to the initial # conditions to investigate the impacts on the entire model trajectory. # # Use the default model parameters, and change the name of the new # output file from 'x_nature' to 'x_freerun' # # Run the python program: # python generate_nature_run.py # # Run the python program: # plot_nature_plus_freerun.py # # Explore the datasets and compare. # #----------------------------------------------------------------------- # Step 2: #----------------------------------------------------------------------- # # By hand, determine the Jacobian of the Lorenz-63 system. # # Run the python program: # python generate_nature_Mhist.py # # This will generate a file containing the same nature run state vector # with the addition of a history of linear propagator matrices estimated # by M = I + Df*dt. Different estimates of the linear propagator # may produce different results due to numerical errors. # # Examine the output of the computed M matrices and compare to your # analytic derivation of the Jacobian matrix. # #----------------------------------------------------------------------- # Step 3: #----------------------------------------------------------------------- # Run the python program: # python generate_nature_QR.py # # This will compute a QR decomposition of the linear propagators M = QR # for a specified time interval over the span of the nature run trajectory # (Mhist), and store a history of the Q and R matrices (Qhist, Rhist). # #----------------------------------------------------------------------- # Step 4: #----------------------------------------------------------------------- # Run the python program: # python generate_nature_LEs.py # # This will generate the Lyapunov Exponents of the system using the # information stored in Rhist, the history of R matrices from the QR # decomposition of the TLM #----------------------------------------------------------------------- # Interlude: (optional) #----------------------------------------------------------------------- # # Further investigation: # Go back and repeat the process using different model parameters. # Try a much longer and a much shorter run of the model. # How do these modifications impact the Lyapunov exponents? # #----------------------------------------------------------------------- # Step 5: #----------------------------------------------------------------------- # Run the python program: # python generate_observations.py # # This will generate a set of observations at every point along the # trajectory of the nature run by sampling the nature run and applying # noise scaled relative the the climatological variability of each # state element. # #----------------------------------------------------------------------- # Step 6: (optional) #----------------------------------------------------------------------- # Run the python program: # python generate_nature_CLVs.py # # This will generate the Lyapunov Vectors of the system using the # information stored in Qhist and Rhist, the history of Q and R matrices # from the QR decomposition of the TLM #
#5 - Crie uma função que receba parâmetro uma lista, com valores de qualquer tipo #A função deve imprimir todos os elementos da lista, enumerando - os. imprime_lista = ["abacate", "feijao", "arroz", "laranja", "banana", "carne"] for i,j in enumerate(imprime_lista, 1): print(i,j)
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or len(matrix[0]) == 0: return False def binarySearch(array, target): left, right = 0, len(array) - 1 while left <= right: mid = int((left + right) / 2) if array[mid] == target: return True elif array[mid] < target: left = mid + 1 else: right = mid - 1 return False for row in matrix: if row[0] <= target <= row[-1]: return binarySearch(row, target) return False
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: ans = None def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if p is None or q is None: return # depth first search def dfs(root): if root is None or self.ans is not None: return False # ancestor node with p or q if root.val == p.val or root.val == q.val: if dfs(root.left) == True or dfs(root.right) == True: self.ans = root return True # ancestor node without p or q left, right = dfs(root.left), dfs(root.right) if left or right: if left and right: self.ans = root return True return False dfs(root) return self.ans
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or len(matrix[0]) == 0: return False def binarySearch(array, target, left=None, right=None): if left is None: left, right = 0, len(array) - 1 if left > right: return False mid = int((left + right) / 2) if array[mid] == target: return True elif array[mid] < target: return binarySearch(array, target, mid + 1, right) else: return binarySearch(array, target, left, mid - 1) # def binarySearch(array, target): # left, right = 0, len(array) - 1 # while left <= right: # mid = int((left + right) / 2) # if array[mid] == target: # return True # elif array[mid] < target: # left = mid + 1 # else: # right = mid - 1 # return False for row in matrix: if row[0] <= target <= row[-1] and binarySearch(row, target): return True return False #################################################################################################### # BFS will cost more time in this case ''' search_array = [(0,0)] while len(search_array) > 0: current_point = search_array[0] search_array = search_array[1:] if current_point[0] < len_x and current_point[1] < len_y: if matrix[current_point[0]][current_point[1]] == target: return True elif matrix[current_point[0]][current_point[1]] < target: search_array.append((current_point[0] + 1, current_point[1])) search_array.append((current_point[0], current_point[1] + 1)) return False '''
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ max_reach = 0 index = 0 while index <= max_reach and index < len(nums): jump = index + nums[index] if max_reach < jump: max_reach = jump index += 1 if index == len(nums): return True else: return False
# 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 """ def recursive(head): if head is None: return head next = recursive(head.next) if head.next is not None and head.val == head.next.val: if next is not None: if next == head.next: return next.next else: return next else: return None head.next = next return head return recursive(head)
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # initialize the answer list with only one element ans = [] for num in nums: ans.append([num]) for _ in range(len(nums) - 1): # every iteration -> append a new element # combination task current = [] for element in ans: for num in nums: if num not in element: current.append(element + [num]) ans = current.copy() return ans
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: ans_head = ListNode(0) def recursiveVisit(head): if head is None: return if head.next is not None: recursiveVisit(head.next).next = head else: ans_head.next = head head.next = None return head recursiveVisit(head) return ans_head.next
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.cache = set() if not root: self.stack = [] else: self.stack = [root] self.cache.add(root) def next(self): """ @return the next smallest number :rtype: int """ ans = -1 if len(self.stack) > 0: while self.stack[-1].left is not None and self.stack[-1].left not in self.cache: self.cache.add(self.stack[-1].left) self.stack.append(self.stack[-1].left) node = self.stack.pop() if node.right is not None and node.right not in self.cache: self.stack.append(node.right) ans = node.val return ans def hasNext(self): """ @return whether we have a next smallest number :rtype: bool """ return len(self.stack) > 0 # Your BSTIterator object will be instantiated and called as such: # obj = BSTIterator(root) # param_1 = obj.next() # param_2 = obj.hasNext()
# 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 flipEquiv(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rtype: bool """ def dfs(root1, root2): if root1 is None or root2 is None: if root1 is None and root2 is None: return True else: return False if root1.val != root2.val: return False pos1 = dfs(root1.left, root2.left) and dfs(root1.right, root2.right) pos2 = dfs(root1.right, root2.left) and dfs(root1.left, root2.right) return pos1 or pos2 return dfs(root1, root2)
class Solution: def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) - 1 check_list = [False for x in range(n + 1)] ans = None for element in nums: if check_list[element] == False: check_list[element] = True else: ans = element break return ans
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ # Breadth First Search data = '' queue = [root] while len(queue) > 0: next_node = queue[0] queue = queue[1:] if next_node is None: data += 'x ' else: data += str(next_node.val) + ' ' queue.append(next_node.left) queue.append(next_node.right) return data def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ index = 0 root = None queue = [] while index < len(data): if root is None: if data[index] == 'x': return else: num = '' while data[index] != ' ': num += data[index] index += 1 index += 1 root = TreeNode(int(num)) queue.append(root) else: current_node = queue[0] queue = queue[1:] if data[index] == 'x': current_node.left = None index += 2 else: num = '' while data[index] != ' ': num += data[index] index += 1 index += 1 current_node.left = TreeNode(int(num)) queue.append(current_node.left) if data[index] == 'x': current_node.right = None index += 2 else: num = '' while data[index] != ' ': num += data[index] index += 1 index += 1 current_node.right = TreeNode(int(num)) queue.append(current_node.right) return root # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ # check the length if len(s) == len(t): # use hash table to count the characters is_valid = True hash_table = {} for character in s: if character not in hash_table.keys(): hash_table[character] = 1 else: hash_table[character] += 1 for character in t: if character not in hash_table.keys() or hash_table[character] == 0: is_valid = False break hash_table[character] -= 1 if is_valid: return True else: return False else: return False
# import all the classes from vehicle_class import * from car_class import * from plane_class import * # create 2 vehicle instances vehicle1 = Vehicle(10,200) vehicle2 = Vehicle(2,30) # call methods and attributes to test print('accelerate for vehicle 1 ', 'vehicle 2 cargo size', 'vehicle 1 breaking:') print(vehicle1.accelerate()) print(vehicle2.cargo_size) print(vehicle1.breaking(),'\n') # create 2 car instances car1 = Car(5,300,'Ford Mustang',410, '155 mph') car2 = Car(2,300,'lamborghini aventador',566, '218 mph') # make car accelerate and make them break print('car 2 breaking and accelerating:') print(car2.accelerate()) print(car2.breaking(),'\n') # make car honk and park print('car 1 honk and park:') print(car1.honk()) print(car1.park(),'\n') # create 2 plane instances here plane1 = Plane(550,25200,'Boeing 777',110000, '1036 kmph') plane2 = Plane(868,93000,'Airbus A380',180000, '1385 kmph') # make plane accelerate and make them break print('plane is accelerating and breaking:') print(plane1.accelerate()) print(plane1.breaking(),'\n') # make plane fly and land print('plane is taking off and landing:') print(plane2.take_off()) print(plane1.touchdown(),'\n')
#!/usr/bin/env python file = open("students.csv") for line in file: l = line.strip() print("DEBUG: ", l) student = l.split(",") print(student) print("FULLNAME is ", student[0]) print("GENDER is ", student[1]) print("COURSE is ", student[2]) print("DEPARTMENT_CODE is ", student[3]) print("COLLEGE is ", student[4]) print("DATE_OF_VISIT is ", student[5])
num = [2,4,6,8] for i in range(len(num)-1,-1,-1): print(num[i]) num = num + [10,12,14] print("List after append") for i in range(len(num)-1,-1,-1): print(num[i]) print(num)
class EmployeeRecords: def __init__(self, n, i, r): self.n = n self.i = i self.r = r def main(): rec = EmployeeRecords("Mary", 2148, 10.50) print(rec.n,"",rec.i,"",rec.r) main()
def linear_equation(a, b): while True: x=yield print('Expression, %s*x^2 + %s, with x being %s equals %s' % (a,b,x,(a*(x**2)+b))) equation1 = linear_equation(3,4) next(equation1) equation1.send(6)
from math import sqrt num = eval(input()) print("Sqrt is:",sqrt(num))
class cryptography: def encrypt(self, numbers): min_val = min(numbers) inx = numbers.index(min_val) numbers[inx]+=1 result = 1 for item in numbers: result = result * item return result def main(): cry = cryptography() numbers = [1000,999,998,997,996,995] print(cry.encrypt(numbers)) if __name__ == "__main__": main()
class Cell: SIZE = 12 ALIVE = 1 DEAD = 0 def __init__(self, state, rect): if state is not self.ALIVE and state is not self.DEAD: raise Exception("Cell state is excepting a boolean. Given value is: {}".format(state)) self.state = state self.rect = rect self.next_state = None def swap_state(self): if self.state is self.ALIVE: self.state = self.DEAD else: self.state = self.ALIVE def save_next_state(self, next_state): if next_state is not self.ALIVE and next_state is not self.DEAD: raise Exception("Cell state is excepting a boolean. Given value is: {}".format(next_state)) self.next_state = next_state def apply_next_state(self): if self.next_state is not None: self.state = self.next_state self.next_state = None
# 1.write a python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers inputs = input("your input here:" ) lists = inputs.split(",") print(lists) tuples = tuple(lists) print(tuples) # 2.write a python program to accept a filename from the user and print the extension of that filename = input("input the filename:") extensions = filename.split(".") print("the file extension is",extensions[-1]) # 3.write a python program to display the first and last colors from the following list color_list = ["Red","Green","White","Black"] first_color = color_list[0] last_color = color_list[-1] print("first_color:",first_color) print("last color:",last_color) # 4.write a python program to display the examination schedule.(extract the date from exam_st_date) exam_st_date = (11,12,2014) print("exam date is:" + str(exam_st_date[0])+"/"+str(exam_st_date[1])+"/"+str(exam_st_date[2])) # or print("exam date is:%i/%i/%i"%exam_st_date) # 5.write a python program that accepts an integer(n) and computes the value of n+nn+nnn. n = int(input("your input here:")) n1 = int("%i"%n) n2 = int("%i%i"%(n,n)) n3 = int("%i%i%i"%(n,n,n)) value = n1+n2+n3 print("the value of n+nn+nnn:",str(value)) # 6.write a python program to print the documents(syntax,description etc.)of python built-in function(s). print(abs.__doc__) print(list.__doc__) # 7.write a program to print the calender of a given month and year. import calendar y = int(input("input the year:")) m = int(input("input the month:")) print(calendar.month(y,m)) # 8.write a python program to print the following here document print(""" a string that you "don't" have to escape This is a .......multi-line heredoc string --------> example """) # 9.write a python program to calculate number of days between two dates from datetime import date dt1 = date(2014,7,2) dt2 = date(2014,7,11) difference = dt2 - dt1 print("The number of days between date1 and date2:",difference.days) # 10.write a python program to get the volume of a sphere with radius 6 from math import pi voulme = 4/3*(pi*6**3) print("the volume of sphere with radius 6:",voulme)
# 1) Создать класс автомобиля. Создать классы легкового автомобиля # и грузового. Описать в основном классе базовые атрибуты и методы # для автомобилей. Будет плюсом если в классах наследниках # переопределите методы базового класса. class Car: def __init__(self, brand: str, model: str, year: int, max_speed: int): self._brand = brand self._model = model self._max_speed = max_speed self._year_model = year @property def brand(self) -> str: return self._brand @brand.setter def brand(self, value: str): self._brand = value @property def model(self) -> str: return self._model @model.setter def model(self, value: str): self._model = value @property def year(self) -> int: return self._year_model @year.setter def year(self, value: int): self._year_model = value @property def max_speed(self) -> int: return self._max_speed @max_speed.setter def max_speed(self, value: int): self._max_speed = value def print_description(self): return f"Current car: \nBrand: {self.brand}\nModel: {self.brand}\nYear of production: {self.year} \nMax speed: {self.max_speed}" class Sedan(Car): __car_body_type = 'Sedan' def print_description(self): return f"Current car type is {self.__car_body_type}: \nBrand: {self.brand}\nModel: {self.model}\nYear of " \ f"production: {self.year} \nMax speed: {self.max_speed} " class SUV(Sedan): __car_body_type = 'SUV' gs350 = Car('Lexus', 'GS 350', 2020, 260) is500 = Sedan('Lexus', 'IS 500', 2019, 270) rx450 = SUV('Lexus', 'RX 450h', 2020, 220) print(gs350.print_description()) print(is500.print_description()) print(rx450.print_description()) print('*' * 30) # 2) Создать класс магазина. Конструктор должен инициализировать # значения: «Название магазина» и «Количество проданных # товаров». Реализовать методы объекта, которые будут увеличивать # кол-во проданных товаров, и реализовать вывод значения # переменной класса, которая будет хранить общее количество # товаров проданных всеми магазинами. class Store: total_sales: int = 0 def __init__(self, name: str, qty: int = 0): self._name = name self._soldQty = qty self.__class__.total_sales = qty def get_name(self) -> str: return self._name def add_qty(self, qty: int): self._soldQty += qty self.__class__.total_sales += qty @classmethod def get_all_sold_product(cls): return cls.total_sales def get_store_sold_product(self): return self._soldQty store1 = Store('Adidass', 200) store1.add_qty(300) store1.add_qty(3) print(store1.get_name()) print(store1.get_store_sold_product()) print(store1.get_all_sold_product()) store2 = Store('Puma', 2000) store2.add_qty(200) store2.add_qty(20) print(store2.get_name()) print(store2.get_store_sold_product()) print(store2.get_all_sold_product()) print('*' * 30) # 3 Создать класс точки, реализовать конструктор который # инициализирует 3 координаты (Class): Определенный программистом тип данных.x, y, z). # Реалзиовать методы для ). Реалзиовать методы для получения и изменения каждой из координат. # Перегрузить для этого класса методы сложения, вычитания, деления умножения. # Перегрузить один любой унарный метод. # Ожидаемый результат: умножаю точку с координатами 1,2,3 на # другую точку с такими же координатами, получаю результат 1, 4, 9. class Dot: def __init__(self, x: int = 1, y: int = 1, z: int = 1): self._z = z self._y = y self._x = x @property def x(self) -> int: return self._x @x.setter def x(self, value: int): self._x = value @property def y(self) -> int: return self._y @y.setter def y(self, value: int): self._y = value @property def z(self) -> int: return self._z @z.setter def z(self, value: int): self._z = value def __add__(self, other): self._z += other.z self._y += other.y self._x += other.x return self def __iadd__(self, other): self._z += other.z self._y += other.y self._x += other.x return self def __isub__(self, other): self._z -= other.z self._y -= other.y self._x -= other.x return self def __sub__(self, other): self._z -= other.z self._y -= other.y self._x -= other.x return self def __imul__(self, other): self._z *= other.z self._y *= other.y self._x *= other.x return self def __mul__(self, other): self._z *= other.z self._y *= other.y self._x *= other.x return self def __ifloordiv__(self, other): self._z *= other.z self._y *= other.y self._x *= other.x return self def __truediv__(self, other): try: self._z *= other.z self._y *= other.y self._x *= other.x except ZeroDivisionError: return 'Zero division error. You can do that.' return self def __str__(self): return 'Coordinates of point: X: {}, Y: {}, Z: {}'.format(self._x, self._y, self._z) dot1 = Dot(2, 4, 8) dot2 = Dot(2, 4, 8) print(dot1) dot1 *= dot2 print(dot1) dot1 = dot1 + dot2 print(dot1) dot1 = dot1 - dot2 print(dot1)
## @file menu.py # Source file for the menu object # # Project: Minesweeper # Author: Ayah Alkhatib # Created: 09/08/18 from executive import Executive ## @class Menu # @brief Prints menu and rules; Manages Executive instance class Menu: ## Constructor; initializes class variables # @author: Ayah def __init__(self): ## @var choice # flag for replay choice self.choice = 0 ## @var myGame # instance of the executive class self.myGame = Executive() ## Handles any type error in users input # @author: Ayah # @returns user input when entered correctly def type_error_handler(self): while True: try: check = int (input()) break except: print ("Please enter a valid choice: ") print ("Play[1], Quit[2]") return check ## Keep the game running until user chose to quit # @authors: Ayah def game_menu(self): play_again = 1 while not self.myGame.game_over: print("Please, chose from the menu:") print("""1. Play the Game 2. Quit""") self.choice = self.type_error_handler() if self.choice == 1: self.myGame.setup() self.myGame.play() elif self.choice == 2: print("Goodbye! See you later!") break else: print("Please enter a valid choice:") while play_again != 2: print("Play[1], Quit [2]") play_again = self.type_error_handler() if play_again == 1: self.myGame = Executive () self.myGame.setup() self.myGame.play() elif play_again != 2: print("Please enter a valid choice") print("Goodbye! See you later!") return ## Prints the game instructions # @author: Ayah def game_rules(self): print("""Welcome to Minesweepers! Here are the game instructions: The game will provid players a square board with a number of hidden mines and similar number of flags. Player has three choices of action: - Flag: to flag squares that might have mines. - Unflag: to unflag if player changed mind. - Reveal: to see what squares have underneath. When player chose to reveal: - If the square has a mine -> Gameover! - If not a mine, it will show spaces and numbers to tell player the number of mines around the chosen square. The goal is to flag all mines until the counter of flags equals to zero without revealing any mine. Good Luck! """)
#https://www.hackerrank.com/challenges/botcleanr/problem #!/usr/bin/python # Head ends here def distance_to_dirt(bot_x, bot_y, board): for x_idx in range(5): for y_idx in range(5): if board[x_idx][y_idx] != 'd': continue dirt_x = x_idx dirt_y = y_idx break return bot_x - dirt_x, bot_y - dirt_y def nextMove(posx, posy, board): x_dist, y_dist = distance_to_dirt(posx, posy, board) if x_dist == 0 and y_dist == 0: print('CLEAN') elif y_dist == 0: print('UP' if x_dist > 0 else 'DOWN') else: print('LEFT' if y_dist > 0 else 'RIGHT') # Tail starts here if __name__ == "__main__": pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] nextMove(pos[0], pos[1], board)
from abc import ABC, abstractmethod from typing import Dict, List class BaseTaggingManager(ABC): @classmethod @abstractmethod def get_tags_dict_from_text( cls, plain_text: str ) -> Dict[str, List[str]]: """ Return mapping of words and tags in the next format: { 'The': ['AT', 'RB'], 'now': ['RB'], ... } !!! IMPORTANT: single word can has more than one tag """ pass @classmethod @abstractmethod def get_tagged_text_from_plain_text( cls, plain_text: str ) -> str: """ Return tagged text where every word has it's own tags set concatenated with special delimiter. Example of tagged text with double underscore delimiter: "The__AT__RB now__RB" !!! IMPORTANT: single word can has more than one tag """ pass @classmethod @abstractmethod def get_plain_text_from_tagged_text( cls, tagged_text: str ) -> str: """ Get rid of all word tags and returns plain text preserving words order Example: "The__AT__RB now__RB" --> "The now" """ pass @classmethod @abstractmethod def tags_dict_from_tagged_text( cls, tagged_text: str ) -> Dict[str, List[str]]: """ Parse tagged text and return mapping of words and tags in the next format: { 'The': ['AT', 'RB'], 'now': ['RB'], ... } """ pass
# # import itertools # # number_set = set() # # # def add_number(dice, sequence, idx, number): # if idx == len(sequence): # number_set.add(number) # return # # for n in dice[sequence[idx]]: # add_number(dice, sequence, idx+1, number+str(n)) # # # # # # # print([1] + [2]) # # # def solution(dice): # answer = 0 # # n = len(dice) # # for i in range(1, len(dice)+1): # perm = list(itertools.permutations([x for x in range(n)], i)) # for p in perm: # add_number(dice, p, 0, '') # # print(list(number_set)) # number_arr = list(set([int(x) for x in list(number_set)])) # # i = 0 # for idx, number in enumerate(number_arr): # if idx > 0 and idx != number: # return idx # # # # print(list(itertools.permutations([0,1,2,3], 3))) # c = solution([[1, 6, 2, 5, 3, 4], [9, 9, 1, 0, 7, 8]] ) # b = solution([[0, 1, 5, 3, 9, 2], [2, 1, 0, 4, 8, 7], [6, 3, 4, 7, 6, 5]]) # print(c) # res = False # def check_rule(string: str): # global res # if string == 'a': # res = True # return # # elif string.startswith('a'): # # if string.endswith('b'): # check_rule(string[1:]) # # elif string.endswith('a'): # # if string.startswith('b'): # check_rule(string[:-1]) # # elif string.startswith('b') and string.endswith('b'): # check_rule(string[1:-1]) # else: # return # # # # def check_rule(string: str): print(string) # print() a_idx = -1 for i in range(len(string)): if string[i] == 'a': a_idx = i break else: return False a_cnt = string.count('a') print(a_cnt) b_cnt = string.count('b') string_arr = list(string) while string_arr and a_cnt: print(string_arr) while string_arr[0] == 'a': string_arr.pop(0) print('asd') a_cnt -= 1 while string_arr[-1] == 'a': string_arr.pop() a_cnt -= 1 i = 0 while i < a_cnt: s, e = string_arr[0], string_arr[-1] if s == 'b' and e == 'b': string_arr.pop(0) string_arr.pop() else: break print() if string_arr == ['arr']: return True else: return False # # # l_cnt, r_cnt = string[:a_idx+1].count('b'), string[a_idx+1:].count('b') # print(a_idx) # print(l_cnt, r_cnt) # print(a_idx, len(string)) # for i in range(a_idx, len(string)): # if string[i] == 'a' and l_cnt == r_cnt: # return True # # if string[i] == 'b': # l_cnt += 1 # r_cnt -= 1 # # return False def solution(a: list): answer = [] for s in a: answer.append(check_rule(s)) return answer a = solution(["abab","bbaa","bababa","bbbabababbbaa", "baabaabab", "abbaa"]) print(a) # arr = [1,2 , 3] # print(arr[:-1])
months, days = ( '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12' ), ('31', '29', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31') for m, d in zip(months, days): for i in range(1, int(d)+1): dd = int(m+str(i).zfill(2)) if 219 <= dd <= 520: sm = 'SPRING' elif 521 <= dd <= 822: sm = 'SUMMER' elif 823 <= dd <= 1121: sm = 'FALL' else: sm = 'WINTER' string = f", ('{m+str(i).zfill(2)}', '{sm}')" print(string)
import heapq def minus_arg(node): node.arg1 -= 2 return node class Node: def __init__(self, arg1: int, arg2: str, arr): self.arg1 = arg1 self.arg2 = arg2 self.arr = arr def __lt__(self, other): if self.arg1 < other.arg1: return True elif self.arg1 == other.arg1: if len(self.arr) > len(other.arr): return True else: return False else: return False def __str__(self): return f'arg1: {self.arg1} // arg2: {self.arg2}, arr: {self.arr}' a = Node(1, 'a', [1, 2, 3]) b = Node(8, 'b', [1, 2, 3]) c = Node(5, 'c', [1, 2, 3]) d = Node(6, 'd', [1, 2, 3]) e = Node(7, 'e', [1, 2, 3]) f = Node(3, 'f', [1, 2, 3, 4]) g = Node(3, 'g', [1, 2, 3, 4, 5]) h = Node(2, 'h', [1, 2, 3]) i = Node(8, 'i', [1, 2, 3,2,2,2,2]) ''' a h f g c d e b ''' # print(a) hq = [] heapq.heappush(hq, a) heapq.heappush(hq, b) heapq.heappush(hq, c) heapq.heappush(hq, d) heapq.heappush(hq, e) heapq.heappush(hq, f) heapq.heappush(hq, g) heapq.heappush(hq, h) heapq.heappush(hq, i) n = heapq.heappop(hq) if n.arg1 > 0: heapq.heappush(hq, n) while hq: print(heapq.heappop(hq)) heapq.heappush(hq, a) heapq.heappush(hq, b) heapq.heappush(hq, c) heapq.heappush(hq, d) heapq.heappush(hq, e) heapq.heappush(hq, f) heapq.heappush(hq, g) heapq.heappush(hq, h) heapq.heappush(hq, i) for h in hq: h = minus_arg(h) print('==========') n2 = heapq.heappop(hq) if n2.arg1 > 0: heapq.heappush(hq, n2) while hq: print(heapq.heappop(hq))
def robot(x, y, count, percent): global per if visited[x][y] == True: per += percent return if count == n: return if east: visited[x][y] = True robot(x, y+1, count+1, percent*east) visited[x][y] = False if west: visited[x][y] = True robot(x, y-1, count+1, percent*west) visited[x][y] = False if south: visited[x][y] = True robot(x+1, y, count+1, percent*south) visited[x][y] = False if north: visited[x][y] = True robot(x-1, y, count+1, percent*north) visited[x][y] = False # for i in range(len(dx)): # if dx[i] == 0 and dy[i] == 1: # if east == 0: # continue # elif visited[x][y+1] == True: # per += percent # return # else: # visited[x][y] = True # robot(x, y+1, count+1, percent * east, visited) # # elif dx[i] == 0 and dy[i] == -1: # if west == 0: # continue # elif visited[x][y-1] == True: # per += percent # return # else: # visited[x][y] = True # robot(x, y-1, count+1, percent * west, visited) # # elif dx[i] == 1 and dy[i] == 0: # if south == 0: # continue # elif visited[x+1][y] == True: # per += percent # return # else: # visited[x][y] = True # robot(x+1, y, count+1, percent * south, visited) # # # elif dx[i] == -1 and dy[i] == 0: # # if north == 0: # # continue # # elif visited[x -1][y] == True: # # per += percent # # return # # else: # # visited[x][y] = True # # robot(x -1, y, count + 1, percent * north, visited) # for i in range(len(dx)): # if dx[i] == 0 and dy[i] == 1 and east != 0: # visited[x][y] = True # robot(x, y+1, count+1, percent * east) # # elif dx[i] == 0 and dy[i] == -1 and west != 0: # visited[x][y] = True # robot(x, y-1, count+1, percent * west) # # elif dx[i] == 1 and dy[i] == 0 and south != 0: # visited[x][y] = True # robot(x+1, y, count+1, percent * south) # # elif dx[i] == -1 and dy[i] == 0 and north != 0: # visited[x][y] = True # robot(x-1 , y, count+1, percent * north) n, east, west, south, north = map(int, input().split()) east /= 100 west /= 100 south /= 100 north /= 100 dx, dy = [0, 0, 1, -1], [1, -1, 0, 0] visited = [] for i in range(30): temp = [False] * 30 visited.append(temp) count = 0 per = 0 robot(14, 14, 0, 1) print('%0.10f'%(1-per)) ''' 10 1 25 25 25 25 2 25 25 25 25 7 50 0 0 50 14 50 50 0 0 14 25 25 25 25 6 0 46 16 38 1 10 36 35 19 14 36 30 21 13 3 25 19 20 36 14 35 15 37 13 ''' ''' #1 1.0000000000 #2 0.7500000000 #3 1.0000000000 #4 0.0001220703 #5 0.0088454932 #6 0.5705340928 #7 1.0000000000 #8 0.0089999035 #9 0.5832200000 #10 0.0506629797 '''
def mergeSort(arr, p, r): q = int((p + r) / 2) # print("p : {}, r : {}, q : {}".format(p, r, q)) if p < r: mergeSort(arr, p, q) mergeSort(arr, q+1, r) return merge(arr, p, q, r) else: return arr def merge(arr, p, q, r): i = p # 첫번째 배열 시작 j = q+1 # 첫번째 배열 끝 k = 0 # 두번째 배열 시작 temp = [0] * (r-p+1) while i <= q and j <= r: print("p : {}, r : {}, q : {}".format(p, r, q)) print('i : {} , j : {}, len_arr : {}'.format(i, j , len(arr))) if arr[i] < arr[j]: temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 while i <= q: temp[k] = arr[i] k += 1 i += 1 while j <= r: temp[k] = arr[j] k += 1 j += 1 for x in range(r-p+1): arr[p+x] = temp[x] return arr arr1 = [6,5,4,3,2,1] print(mergeSort(arr1, 0, len(arr1)-1))
def switch(arg): if arg == 1: return 0 elif arg == 0: return 1 else: return switch_len = int(input()) switch_list = list(map(int, input().split())) student_num = int(input()) # 1 2 3 4 5 6 7 8 # 0 1 0 1 0 0 0 1 # 남학생 : 스위치 번호가 내가 받은 번호의 배수라면 스위치 변경 # 여학생 : 내가 받은 번호를 중심으로 양 옆이 대칭이 되는 경우를 조사해 대칭이 되는 범위만큼 스위치 변경 for i in range(student_num): gender_num = list(map(int, input().split())) gender, num = gender_num[0], gender_num[1] # 1 3 if gender == 1: # print('gender: 1') for j in range(len(switch_list)): if (j+1) % num == 0: switch_list[j] = switch(switch_list[j]) elif gender == 2: compare = 1 switch_list[num-1] = switch(switch_list[num-1]) while num-1-compare >= 0 and num-1+compare < switch_len: # print(num-1+compare, num-1-compare) if switch_list[num-1+compare] == switch_list[num-1-compare]: switch_list[num-1+compare] = switch(switch_list[num-1+compare]) switch_list[num-1-compare] = switch(switch_list[num-1-compare]) compare += 1 else: break count = 0 for j in range(switch_len): if count == 20: print() count = 0 print(switch_list[j], end=' ') count += 1 # 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
# 재귀 함수 : 자기 자신을 호출하는 함수 # 재귀 호출 : 재귀적 정의(점화식)을 구현하기 위해 사용 # 그래프의 길이 우선 탐색, 백트래킹 시 자주 사용한다. # 기본 개념은 반복, for나 while을 사용하지 않고 반복을 사용할 수 있다. # for i in range(3): # print('hello?') >> 보통의 반복문 # 재귀함수의 조건. 몇번 반복할것인가? # >> 매개변수를 counting하는 조건으로 주어 반복횟수를 조절한다. # count = 0 # def hello(count): # if count < 3: # print('hello') # hello(count + 1) # hello(0) # def hello(count, n): # if count == n: # print('------------') # return # else: # hello(count + 1, n) # print(count, '> hello') # # hello(count + 1, n) # # hello(2, 8) # 집에 가서 해볼것. cnt = 0 # 전역변수가 하나 있다. def hello(count, n): global cnt if count == n: cnt += 1 print('------------') return else: hello(count + 1, n) hello(count + 1, n) print(count, '> hello') # hello(count + 1, n) hello(0, 3) print(cnt)
def is_prime_number(number): for i in range(2, number): if not number % i: return 0 return 1 def encode_num(number, n): if number < n: return str(number) s = encode_num(number//n, n) return s + str(number % n) print(encode_num(11, 2)) def solution(n, k): answer = 0 encoded_number = encode_num(n, k) splited_number = encoded_number.split('0') for number in splited_number: if number and int(number) >= 2: answer += is_prime_number(number) return answer solution(437674, 3) solution(110011, 10)
# def bishop(s, e, count): # global max_count # t = 0 # for i in range(s, b_len): # result2 = True # x, y = b_list[i][0], b_list[i][1] # for k in range(len(dx)): # if result2 == False: break # d_x, d_y = dx[k], dy[k] # while 0 <= x + d_x < n and 0 <= y + d_y < n: # if chess[x + d_x][y + d_y] == 'B': # result2 = False # break # d_x += dx[k] # d_y += dy[k] # if result2 == True: # t += 1 # # print(t) # # t : 앞으로 둘 수 있는 최대 bishop # if t + count <= max_count: # return # # # if count + (b_len - s) <= max_count: # # # print('return', count + (b_len - s + 1)) # # return # # if s == e: # # print('max_count : ', max_count) # # print('count + (b_len - s+1)', count + (b_len - s+1)) # # for i in range(n): # # print(chess[i]) # # print() # max_count = max(max_count, count) # return # # if s == e: # # count = 0 # # for i in range(n): # # print(chess[i]) # # print() # # result = True # # for i in range(n): # # if result == False: break # # for j in range(n): # # if chess[i][j] == 'B': # # count += 1 # # x, y = i, j # # for k in range(len(dx)): # # if result == False: break # # delta_x, delta_y = dx[k], dy[k] # # while 0 <= x + delta_x < n and 0 <= y + delta_y < n: # # if chess[x+delta_x][y+delta_y] == 'B': # # result = False # # break # # delta_x += dx[k] # # delta_y += dy[k] # # if count <= max_count: # # return # # if result == True: # # max_count = max(max_count, count) # # print('max : ', max_count) # # return # # else: # # return # # # # x, y = b_list[s][0], b_list[s][1] # result = True # for k in range(len(dx)): # x, y = b_list[s][0], b_list[s][1] # if result == False: break # d_x, d_y = dx[k], dy[k] # while 0 <= x + d_x < n and 0 <= y + d_y < n: # if chess[x+d_x][y+d_y] == 'B': # result = False # break # d_x += dx[k] # d_y += dy[k] # if result: # # print('x, y : , count : , ',x, y, count+1) # chess[x][y] = 'B' # # for i in range(n): # # print(chess[i]) # # print() # bishop(s+1, e, count+1) # chess[x][y] = 1 # # for i in range(n): # # print(chess[i]) # # print() # bishop(s+1, e, count) # # visited[i] = False # else: # bishop(s+1, e, count) # # # if chess[b_list[i][0]][b_list[1][1]] == 'B': continue # # else: # # chess[b_list[i][0]][b_list[i][1]] = 'B' # # bishop(s+1 , e, count+1) # # chess[b_list[i][0]][b_list[i][1]] = 1 # # bishop(s+1, e, count) # # # # # n = int(input()) # chess = [list(map(int, input().split())) for _ in range(n)] # b_list = [] # visited = [] # for i in range(n): # for j in range(n): # if chess[i][j] == 1: # b_list.append([i, j]) # visited.append(False) # # print(b_list) # b_len = len(b_list) # dx, dy = [-1, 1, -1, 1], [1, -1, -1, 1] # max_count = 0 # bishop(0, b_len, 0) # print(max_count) def bishop(s, e, count): global max_count # t = 0 # for i in range(s, b_len): # result2 = True # x, y = b_list[i][0], b_list[i][1] # for k in range(len(dx)): # if result2 == False: break # d_x, d_y = dx[k], dy[k] # while 0 <= x + d_x < n and 0 <= y + d_y < n: # if chess[x + d_x][y + d_y] == 'B': # result2 = False # break # d_x += dx[k] # d_y += dy[k] # if result2 == True: # t += 1 # # print(t) # # t : 앞으로 둘 수 있는 최대 bishop # if t + count <= max_count: # return if s == e: max_count = max(max_count, count) return x, y = b_list[s][0], b_list[s][1] if visited[x][y] == False: # 둘 수 있고 1인 곳 print('s, e : ',s, e) print('visited : ', x, y) visited[x][y] = False bishop(s+1, e, count) visited[x][y] = True # 더 이상 둘 수 없도록 for i in range(len(dx)): d_x, d_y = dx[i], dy[i] while 0 <= x + d_x < n and 0 <= y + d_y < n: if chess[x+d_x][y+d_y] == 1 and visited[x+d_x][y+d_y] == False: visited[x+d_x][y+d_y] = True d_x += dx[i] d_y += dy[i] for i in range(n): print(visited[i]) print() bishop(s+1, e, count+1) else: bishop(s+1, e, count) n = int(input()) chess = [list(map(int, input().split())) for _ in range(n)] b_list = [] visited = [] for i in range(n): temp = [False] * n for j in range(n): if chess[i][j] == 1: b_list.append([i, j]) visited.append(temp) print('visited start') print('b_list : ',b_list) for i in range(n): print(visited[i]) b_len = len(b_list) dx, dy = [-1, 1, -1, 1], [1, -1, -1, 1] max_count = 0 bishop(0, b_len, 0) print(max_count)
def sort_and_tuple(arr): return tuple(sorted(arr)) def check(coor_1, coor_2, board, flag): n = len(board) move_list = [[(0, -1), (0, 1)], [(-1, 0), (1, 0)]] if flag == 'horizontal': move_list.reverse() move_ver, move_hor = move_list[0], move_list[1] result = [] for move in move_ver: # dx, dy = move[0], move[1] for x, y in coor_1, coor_2: if not 0 <= x + dx < n or not 0 <= y + dy < n or board[x+dx][y+dy]: break else: new_coor1 = (coor_1[0]+dx, coor_1[1]+dy) new_coor2 = (coor_2[0]+dx, coor_2[1]+dy) for coor in [[coor_1, new_coor1], [new_coor2, coor_2], [new_coor1, new_coor2]]: result.append(sort_and_tuple(coor)) for move in move_hor: dx, dy = move[0], move[1] x_1, y_1, x_2, y_2 = coor_1[0], coor_1[1], coor_2[0], coor_2[1] if 0 <= x_1+dx < n and 0 <= y_1+dy < n and 0 <= x_2+dx < n and 0 <= y_2+dy < n and \ not board[x_1+dx][y_1+dy] and not board[x_2+dx][y_2+dy]: new_coor1 = (x_1+dx, y_1+dy) new_coor2 = (x_2+dx, y_2+dy) result.append((new_coor1, new_coor2)) return result def solution(board): n = len(board) dist_dict = {} for i in range(n): for j in range(n-1): if 0 <= i < n and 0 <= j < n: dist_dict[((i, j), (i, j + 1))] = 0xffffff for i in range(n - 1): for j in range(n): if 0 <= i < n and 0 <= j < n: dist_dict[((i, j), (i + 1, j))] = 0xffffff key = tuple(sorted([(0, 0), (0, 1)])) dist_dict[key] = 0 robot = [((0, 0), (0, 1))] while robot: direction = robot.pop(0) x1, y1, x2, y2 = direction[0][0], direction[0][1], direction[1][0], direction[1][1] if x1 == x2: result = check((x1, y1), (x2, y2), board, 'horizontal') else: result = check((x1, y1), (x2, y2), board, 'vertical') if result: for r1, r2 in result: if dist_dict.get((r1, r2)) > dist_dict.get(direction)+1: dist_dict[(r1, r2)] = dist_dict.get(direction)+1 robot.append((r1, r2)) return min(dist_dict.get(((n-1, n-2), (n-1, n-1))), dist_dict.get(((n-2, n-1), (n-1, n-1)))) print(solution([[0, 0, 0, 1, 1],[0, 0, 0, 1, 0],[0, 1, 0, 1, 1],[1, 1, 0, 0, 1],[0, 0, 0, 0, 0]]))
class BSTree: def __init__(self): self.root = None def inorder(self): return self.root.inorder() if self.root else [] def min(self): return self.root.min() if self.root else None def max(self): return self.root.max() if self.root else None # lookup의 입력 인자 : key # lookup의 반환 값 : 찾은 Node와 그 부모 Node(부모는 삭제 연산을 하기 위해 필요함) def lookup(self, key): return self.root.lookup(key) if self.root else None, None def insert(self, key, data): if self.root: self.root.insert(key, data) else: self.root = Node(key, data) def remove(self, key, data): node, parent = self.lookup(key) if node: return True else: # 없애야 하는 Node가 존재하지 않으면 삭제할 Node도 없음. return False class Node: def __init__(self, key, data): self.key = key self.data = data self.left = None self.right = None def inorder(self): traversal = [] if self.left: traversal += self.left.inorder() traversal.append(self) if self.right: traversal += self.right.inorder() return traversal def min(self): if self.left: return self.left.min() else: return self def max(self): if self.right: return self.right.max() else: return self def lookup(self, key, parent=None): if key < self.key: if self.left: return self.left.lookup(key, parent=self) else: return None, None elif key > self.key: if self.right: return self.right.lookup(key, parent=self) else: return None, None else: return self, parent def insert(self, key, data): if key < self.key: if self.left: self.left.insert(key, data) else: self.left = Node(key, data) elif key > self.key: if self.right: self.right.insert(key, data) else: self.right = Node(key, data) else: if key == self.key: raise KeyError # 삭제 연산 # 삭제되는 원소가 leaf node인 경우 -> 그냥 삭제 # 자식을 하나 가지고 있는 경우 -> 자기 자리에 자식을 올림 # 자식을 둘 가지고 있는 경우 ->
def solution(board, moves): answer = 0 basket = [] for m in moves: i = 0 while i < len(board): doll1 = board[i][m-1] if doll1 != 0: if not basket: basket.append(doll1) else: doll2 = basket[-1] if doll1 == doll2: print(basket) print(doll1, doll2) basket.pop() answer += 2 else: basket.append(doll1) board[i][m-1] = 0 break i += 1 return answer print(solution([[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]], [1,5,3,5,1,2,1,4]))
import sys sys.stdin = open('1_input.txt', 'r') t = int(input()) for i in range(1, t+1): word = input() word_len = len(word) # print(word_len) result = 'Exist' for j in range(0, word_len//2): # print(word[j], word[word_len-j-1]) if word[j] == '?' or word[word_len-j-1] == '?' or word[j] == word[word_len-j-1]: continue elif word[j] != word[word_len-j-1]: result = 'Not exist' break print('-------------') print('#{} {}'.format(i, result))
def get_subset(arr): n = len(arr) result = [] for i in range(1 << n): temp = [] for j in range(n): if i & (1 << j): temp.append(j) temp_arr = arr[:] for idx in temp: temp_arr[idx] = '-' result.append(' '.join(temp_arr)) return result def get_answer_by_binary_search(score, arr): if not arr: return 0 start, end = 0, len(arr) mid = (start + end) // 2 while start < end: mid = (start + end) // 2 value = arr[mid] if value >= score: end = mid else: start = mid+1 return len(arr) - end def solution(info, query): answer = [] answer_dict = {} for i in info: i = i.split(' ') for res in get_subset(i[:-1]): answer_dict[res] = answer_dict.get(res, []) answer_dict[res].append(int(i[-1])) for value in answer_dict.values(): if value: value.sort() for q in query: q_list = q.split(' ') score = int(q_list.pop()) q_list = [word for idx, word in enumerate(q_list) if idx%2 == 0] condition = ' '.join(q_list) answer.append(get_answer_by_binary_search(score, answer_dict.get(condition))) return answer print(solution(["java backend junior pizza 150","python frontend senior chicken 210","python frontend senior chicken 150","cpp backend senior pizza 260","java backend junior chicken 80","python backend senior chicken 50"],["java and backend and junior and pizza 100","python and frontend and senior and chicken 200","cpp and - and senior and pizza 250","- and backend and senior and - 150","- and - and - and chicken 100","- and - and - and - 150"] ))
"""Simple exercise file where the kid must write code. Control the LED light in the finch robot with this small exercise. The code doesn't run as it is because a kid is supposed to complete the exercise first. NAO will open this file in an editor. """ from exercises.finch.finch import Finch from time import sleep finch = Finch() switcher = {'blue': '#0000FF', 'yellow': '#FFFF00', 'green': '#008000'} ############################################################################### # Write your code here. Your code asks the user for a color from the ones # defined above # CODE: color = raw_input('color:') color = raw_input('color:') ############################################################################### colorIsValid = False finchColor = switcher.get(color) while(finchColor is None): print('Invalid color. Valid colors are: ' + ', '.join(switcher.keys())) finchColor = switcher.get(raw_input('color:')) finch.led(finchColor) sleep(5)
# -*- coding: utf-8 -*- from sys import stdin PERFECT = 0 ABUNDANT = 1 DEFICIENT = 2 NUMBER_TYPES = { PERFECT: u'Perfect', ABUNDANT: u'Abundant', DEFICIENT: u'Deficient' } def get_divisors(num): """ Get the divisors of a number 'num', except itself :param num: the number to get divisors :return: (generator) list of divisors """ yield 1 for i in range(2, num / 2 + 1): if not num % i: yield i def get_number_type(num): """ Get the type of the current number (PERFECT, ABUNDANT or DEFICIENT) :param num: The number to be processed :return: (int) The type of the number PERFECT(0), ABUNDANT(1) or DEFICIENT(2) """ print list(get_divisors(num)) divisors_sum = sum(list(get_divisors(num))) return PERFECT if divisors_sum == num else ABUNDANT if divisors_sum > num else DEFICIENT if __name__ == "__main__": while True: try: print u'Please, enter a number (0 to exit): ' num = abs(int(stdin.readline())) if num == 0: break number_type = get_number_type(num) print u'The number {} is {}.'.format(num, NUMBER_TYPES[number_type]) except ValueError: print u'Invalid number'
# Name - Sidharth Raj##### # importing all the necessary libraries # socket library is used to create and handle various sockets # easygui library is used to create gui import socket import random import json from easygui import * request = "GET / HTTP/1.1\r\nHost: \r\n\r\n" # Client function to send the encoded JSON object to the server def client(info): s.send(info.encode()) print("Data sent") # Function to generate random integer between 5 and 15 def randtime(): number = random.randint(5, 15) return number # specifying the host as localhost so that the server and clients both connect to the same node host = '' port = 8888 # A socket is created where the first argument refers to the IPV4 addressing scheme and the second argument refers to the TCP protocol try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print("Fail to connect\n") print("Socket Created\n") # Connect the socket to the LocalHost s.connect((host, port)) # Pop-up dialog box for user to enter the username c_name = enterbox(msg="Please enter username: ", title= "Enter User Name", default= "") # c_name = raw_input("Enter Username for the client: ") number = randtime() # Dumping JSON object into DATA container data = json.dumps({"name12": c_name, "samay": number}) print("Username and wait interval value collected") # Calling function CLIENT() client(data) choice = buttonbox('Choose an option:', "Client", ["Wait request", "Disconnect"], None, None, "Disconnect") # if choice == 'Disconnect': # break s.close()
# -*- coding: utf-8 -*- # @Time : 19-5-20 上午10:34 # @Author : Redtree # @File : insert_shell.py # @Desc : 希尔排序 #----希尔排序---- def dosort(L): #初始化gap值,此处利用序列长度的一般为其赋值 gap = (int)(len(L)/2) #第一层循环:依次改变gap值对列表进行分组 while (gap >= 1): #下面:利用直接插入排序的思想对分组数据进行排序 #range(gap,len(L)):从gap开始 for x in range(gap,len(L)): #range(x-gap,-1,-gap):从x-gap开始与选定元素开始倒序比较,每个比较元素之间间隔gap for i in range(x-gap,-1,-gap): #如果该组当中两个元素满足交换条件,则进行交换 if L[i] > L[i+gap]: temp = L[i+gap] L[i+gap] = L[i] L[i] =temp #while循环条件折半 gap = (int)(gap/2) return L
class SnakeDead(Exception): pass class Snake: def __init__(self, pos, x_direction, y_direction): self.body = [pos] self._alive = True self.x_direction = x_direction self.y_direction = y_direction @property def alive(self): return self._alive def iter(self): for n in self.body: yield n def __iter__(self): return self.iter() def __contains__(self, item): return item in self.body @property def head(self): return self.body[-1] @property def tail(self): return self.body[0] def __len__(self): return len(self.body) @property def length(self): return len(self) @staticmethod def compare_direction(a, b): return a != b and abs(a) != abs(b) def kill(self): self._alive = False def turn_to(self, x_direction, y_direction): if not (self.compare_direction(self.x_direction, x_direction) and self.compare_direction(self.y_direction, y_direction)): return False self.x_direction = x_direction self.y_direction = y_direction return True def slide(self, ls, rs, ts, bs): if not self.alive: raise SnakeDead() x, y = self.head x += self.x_direction y += self.y_direction self._alive = (x, y) not in self and ls < x < rs and ts < y < bs self.eat(x, y) return self.body.pop(0) def eat(self, x, y): self.body.append((x, y)) def __str__(self): return str(self.body)
import socket from SocketWrapper import * from sql import * username = "null" password = "null" con_pass = "null" IP = '0.0.0.0' PORT = 8822 incorrect_message = "one of the details is incorrect" class server: def receive_client_request(self): command = self.socket_wrapper.read_with_len() username = self.socket_wrapper.read_with_len() password = self.socket_wrapper.read_with_len() if command == "login": self.login(username, password) elif command == "signon": self.signup(username, password) def login(self, username, password): result = self.db.get_user(username) if result == None: self.socket_wrapper.send_with_len(incorrect_message) else: if password == result[1]: self.socket_wrapper.send_with_len("user logged in sucessfully") else: self.socket_wrapper.send_with_len(incorrect_message) def signup(self, username, password): result = self.db.insert_user(username, password) if result == True: self.socket_wrapper.send_with_len("user inserted sucessfully") else: self.socket_wrapper.send_with_len("user logged in sucessfully") def __init__(self): self.db = DB() self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind((IP, PORT)) self.server_socket.listen(1) print("Server is up and running") while True: (client_socket, client_address) = self.server_socket.accept() print("client connected") self.socket_wrapper = socket_wrapper(client_socket) self.receive_client_request() client_socket.close() self.server_socket.close() def main(): server() if __name__ == '__main__': main()
def FactorialRecursion(n): ''' 阶乘的递归实现 :param n:正整数 :return:阶乘结果 ''' if n == 1: return 1 else: return n * FactorialRecursion(n - 1) def Factorial_Iter(n): ''' 阶乘的迭代实现 :param n: 正整数 :return: 阶乘结果 ''' result = n for i in range(1, n): result *= i return result
import math def search_min_fun(x, fx): min = fx[0] min_x = x[0] for i in range(len(fx)): if fx[i] < min: min = fx[i] min_x = x[i] return min_x, min def passive_search_N(a, b, Eps): return math.ceil((b - a) / Eps - 1) def passive_search_count(N, a, b): x, fx = [], [] for i in range(N): x.append(a + ((b - a) / N) * (i + 1)) fx.append(-2 * math.sqrt(x[i]) * math.sin(0.5 * x[i])) return x , fx def input_Eps(): Eps = input() while str(Eps).isdigit == False: print("Type Eps (float)") Eps = input() return float(Eps) def golnden_search_count(Eps, a, b): i, lk = 1, b - a x1 = a + (1 - 1 / tau) * lk x2 = a + 1 / tau * lk fx1 = -2 * math.sqrt(x1) * math.sin(0.5 * x1) fx2 = -2 * math.sqrt(x2) * math.sin(0.5 * x2) print("x" + str(i) + ",1 = " + str(x1),"x" + str(i) + ",2 = " + str(x2)) print("f(x" + str(i) + ",1) = " + str(fx1), "f(x" + str(i) + ",2) = " + str(fx2)) i += 1 while lk > Eps: if fx1 > fx2: a, b = x1, b lk = b - a x1 = x2 x2 = a + 1 / tau * lk fx2 = -2 * math.sqrt(x2) * math.sin(0.5 * x2) print("x" + str(i) + ",1 = " + str(x1),"x" + str(i) + ",2 = " + str(x2)) print("f(x" + str(i) + ",1) = " + str(fx1), "f(x" + str(i) + ",2) = " + str(fx2)) else: a, b = a, x2 lk = b - a x2 = x1 x1 = a + (1 - 1 / tau) * lk fx1 = -2 * math.sqrt(x1) * math.sin(0.5 * x1) print("x" + str(i) + ",1 = " + str(x1),"x" + str(i) + ",2 = " + str(x2)) print("f(x" + str(i) + ",1) = " + str(fx1), "f(x" + str(i) + ",2) = " + str(fx2)) print(lk) i += 1 return i # def golnden_search_count(Eps, a, b): # i, lk = 1, b - a # while lk > Eps: # lk = b - a # x1 = a + (1 - 1 / tau) * lk # x2 = a + 1 / tau * lk # fx1 = -2 * math.sqrt(x1) * math.sin(0.5 * x1) # fx2 = -2 * math.sqrt(x2) * math.sin(0.5 * x2) # if fx1 > fx2: # a, b = x1, b # else: # a, b = a, x2 # print("x" + str(i) + ",1 = " + str(x1),"x" + str(i) + ",2 = " + str(x2)) # print("f(x" + str(i) + ",1) = " + str(fx1), "f(x" + str(i) + ",2) = " + str(fx2)) # i += 1 # return i # f = -2 * math.sqrt(x) * math.sin(0.5 * x) a, b = 2, 6 tau = (1 + math.sqrt(5)) / 2 Eps = input_Eps() # N = passive_search_N(a, b, Eps) # x, fx = passive_search_count(N, a, b) # min_x, min = search_min_fun(x, fx) # print(min_x, min) i = golnden_search_count(Eps, a, b) print(i)
import argparse import sys import words import frequency import key ENCODE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' class Crib: def __init__(self): self.cribwords = [] def load(self, filename): with open(filename, 'r') as f: for line in f: self.cribwords.append(line.strip()) def search(self, text): hits = {} frequent_hits = {} for i in range(len(text)): for crib in self.cribwords: testword = text[i:i+len(crib)] cribcode = words.wordcode(crib) testcode = words.wordcode(testword) if cribcode == testcode: if crib in hits: if testword in hits[crib]: # We have hit this sequence already if crib in frequent_hits: if testword in frequent_hits[crib]: frequent_hits[crib][testword] += 1 else: frequent_hits[crib] = {testword: 2} else: frequent_hits[crib] = {testword: 2} hits[crib].append(testword) else: hits[crib] = [testword] return frequent_hits, hits def stripciphertext(ciphertext): outtext = '' for c in ciphertext: if c in ENCODE_CHARS: outtext += c return outtext def main(): # Set up the commandline arguments parser = argparse.ArgumentParser() parser.add_argument("-i", "--infile", required=True, help="ciphertext input file") parser.add_argument("-o", "--outfile", help="output file") parser.add_argument("-d", "--dictionary", default='dictionary.txt', help="dictionary file") parser.add_argument("-c", "--crib", default='cribwords.txt', help="cribwords file") parser.add_argument("-s", "--stripciphertext", action="store_true", help="should we strip the ciphertext of spaces and" "punctuation before we start to attempt decode") # Parse the commandline arguments args = parser.parse_args() outtext = '' ciphertext = '' # Read in the ciphertext` if args.infile is not None: with open(args.infile, 'r') as f: for line in f: ciphertext += line # Strip if requested if args.stripciphertext: ciphertext = stripciphertext(ciphertext) # Initialise the key k = key.Key() # Do the frequency analysis freq = frequency.frequency() freq.add(ciphertext) freqlist = freq.freq_list() print(str(freqlist)) # Assume e is the most frequent and t is the second most frequent letters c, n = freqlist[0] k.set(c, 'e', 'Frequency') e = c c, n = freqlist[1] k.set(c, 't', "Frequency") t = c # Now we know 't' and 'e', try to find the h from 'the' c, n = freq.h_spotter(t, e, ciphertext) k.set(c, 'h', 'h spotter') # get the partially decrypted ciphertext pd = k.decipher(ciphertext) # Use the cribs to try and get a start on the cracking crib = Crib() crib.load(args.crib) frequent_hits, hits = crib.search(ciphertext) for cribword in frequent_hits: for match in frequent_hits[cribword]: score = frequent_hits[cribword][match] / len(hits[cribword]) if score > 0.1: k.set_string(match, cribword, "Cribword: " + cribword) outtext += str(hits) + '\n' outtext += str(frequent_hits) + '\n' for cribword in frequent_hits: outtext += cribword + '\n' for match in frequent_hits[cribword]: score = frequent_hits[cribword][match]/len(hits[cribword]) outtext += '\t' + match + ":\t " + str(score) + '\n' outtext += '\n\n' + k.decipher(ciphertext) + '\n\n' outtext += '\n' + str(k.key) + '\n' outtext += '\n' + str(k.history) + '\n' if args.outfile is not None: with open(args.outfile, 'w') as f: f.write(outtext) else: print(outtext) def main2(): # Set up the commandline arguments parser = argparse.ArgumentParser() parser.add_argument("-i", "--infile", required=True, help="ciphertext input file") parser.add_argument("-o", "--outfile", help="output file") parser.add_argument("-d", "--dictionary", default='dictionary.txt', help="dictionary file") parser.add_argument("-c", "--crib", default='cribwords.txt', help="cribwords file") parser.add_argument("-s", "--stripciphertext", action="store_true", help="should we strip the ciphertext of spaces and" "punctuation before we start to attempt decode") parser.add_argument("-t", "--cribthreshold", default=0.1, help="Thresholds for us to use the cribwords", type=float) # Parse the commandline arguments args = parser.parse_args() outtext = '' ciphertext = '' # Read in the ciphertext` if args.infile is not None: with open(args.infile, 'r') as f: for line in f: ciphertext += line # Strip if requested if args.stripciphertext: ciphertext = stripciphertext(ciphertext) # Initialise the key k = key.Key() # Do the frequency analysis freq = frequency.frequency() freq.add(ciphertext) freqlist = freq.freq_list() print(str(freqlist)) # Assume e is the most frequent and t is the second most frequent letters c, n = freqlist[0] k.set(c, 'e', 'Frequency') e = c c, n = freqlist[1] k.set(c, 't', "Frequency") t = c # Now we know 't' and 'e', try to find the h from 'the' c, n = freq.h_spotter(t, e, ciphertext) k.set(c, 'h', 'h spotter') # Use the cribs to try and get a start on the cracking crib = Crib() crib.load(args.crib) frequent_hits, hits = crib.search(ciphertext) for cribword in frequent_hits: for match in frequent_hits[cribword]: score = frequent_hits[cribword][match] / len(hits[cribword]) if score > args.cribthreshold: k.set_string(match, cribword, "Cribword: " + cribword) # get the partially decrypted ciphertext print(k.decipher(ciphertext)) # Start an interactive loops while True: cmd = input("\n:> ") # Check to see whether we entered an integer try: # If so then lets use it to # go back in time... i = int(cmd) k.history = i except: if len(cmd) == 1: if cmd.upper() in ENCODE_CHARS: p = input("Plaintext :> ") k.set(cmd, p, 'User') elif cmd == 'key': print('\n' + str(k.key) + '\n') elif cmd == 'freq': print(str(freqlist)) elif cmd == 'quit': break elif cmd == 'history': print(k.history) print('\n' + k.decipher(ciphertext)) outtext = '' for cribword in frequent_hits: outtext += cribword + '\n' for match in frequent_hits[cribword]: score = frequent_hits[cribword][match]/len(hits[cribword]) outtext += '\t' + match + ":\t " + str(score) + '\n' outtext += '\n\n' + k.decipher(ciphertext) + '\n\n' outtext += '\n' + str(k.key) + '\n' outtext += '\n' + str(k.history) + '\n' if args.outfile is not None: with open(args.outfile, 'w') as f: f.write(outtext) else: print(outtext) if __name__ == '__main__': main2()
def insertion_sort(l: list) -> list: if len(l) <= 1: return l # Pick one item, then find the right place in the list to put it in for unsorted in range(len(l)): hold = l[unsorted] i = unsorted - 1 while i >= 0 and hold < l[i]: l[i + 1] = l[i] i -= 1 l[i + 1] = hold return l
def alternating_characters(s): temp = s[0] res = 0 for i in s[1:]: if i == temp: res += 1 else: temp = i return res if __name__ == '__main__': with open("testCase/alternating_characters.txt") as f: f.readline() li = f.read().split("\n") for st in li: print(alternating_characters(st))
class Solution: def convertToBase7(self, num: int) -> str: s = '' neg = False if(num < 0): num *= -1 neg = True while num != 0: s = str(num % 7) + s num = num // 7 if neg == True: s = '-' + s return int(s) s = Solution() print(s.convertToBase7(-100))
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: if (not head) or (not head.next): return head slow = head fast = head.next while (fast and fast.next): slow = slow.next fast = (fast.next).next second = slow.next slow.next = None lista = self.sortList(head) listb = self.sortList(second) return self.merge(lista, listb) def merge(self, a : ListNode, b: ListNode) -> ListNode: if a is None: return b if b is None: return a final = ListNode() head = final while a and b: if a.val < b.val: head.next = a a = a.next else: head.next = b b= b.next head = head.next if a: head.next=a elif b: head.next = b return final.next s = Solution() h = a = ListNode(4, None) a.next = ListNode(2, None) a = a.next a.next = ListNode(1, None) a = a.next a.next = ListNode(3,None) print(s.sortList(h))
# 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 balanceBST(self, root: TreeNode) -> TreeNode: l = self.inorderTraversal(root) start = 0 end = len(l)-1 return self.build(start,end,l) def build(self,start,end, l: list): if start > end: return None if start == end: return TreeNode(l[start], None, None) if end-start == 2: mid = (end-start)//2 root = TreeNode(l[start], None, None) left = TreeNode(l[mid], None, None) right = TreeNode(l[end], None, None) root.left = left root.right = right return root elif end-start == 1: root = TreeNode(l[start],None,None) right = TreeNode(l[end], None, None) root.right = right return root else: mid = (end+start) // 2 root = TreeNode(l[mid], None,None) root.left = self.build(start,mid-1,l) root.right = self.build(mid+1,end,l) return root def inorderTraversal(self, root): l = [] if root is None: return l if root.left: l.extend(self.inorderTraversal(root.left)) l.append(root.val) if root.right: l.extend(self.inorderTraversal(root.right)) return l #[1,null,15,14,17,7,null,null,null,2,12,null,3,9,null,null,null,null,11] s = Solution() #t = TreeNode(1, None, TreeNode(2, None, TreeNode(3, None, TreeNode(4, None, None)))) t = TreeNode(1,None,None) t.right = TreeNode(15,None,None) t.right.left = TreeNode(14,None,None) t.right.right = TreeNode(17,None,None) t.right.left.left = TreeNode(7,None,None) t.right.left.left.left = TreeNode(2,None,None) t.right.left.left.right = TreeNode(12,None,None) t.right.left.left.left.right = TreeNode(3,None,None) t.right.left.left.right.left = TreeNode(9,None,None) t.right.left.left.right.left.right = TreeNode(11,None,None) l = [] #print(s.inorderTraversal(t)) print(s.balanceBST(t))
from typing import List class Solution: def runningSum(self, nums: List[int]) -> List[int]: sumNums = [] for i in range(len(nums)): sumNum = 0 for j in range(i+1): sumNum += nums[j] sumNums.append(sumNum) return sumNums s = Solution() print(s.runningSum([1,2,3,4]))
# Definition for a Node. class Node: def __init__(self, x: int, y: int, next: 'Node' = None, prev: 'Node' = None): self.key = int(x) self.val = int(y) self.next = next self.prev = prev def __str__(self): return "Node key: " + str(self.key) def __repr__(self): return "Node key: " + self.key class LRUCache: def __init__(self, capacity: int): self.cur_capacity = 0 self.full_capacity = capacity self.start = None self.end = None self.loc = {} def get(self, key: int) -> int: if key in self.loc: # replace end to node of list cur = self.loc[key] if cur != self.end: if cur.next and cur.prev: cur.prev.next = cur.next cur.next.prev = cur.prev if cur == self.start: self.start = cur.next self.end.next = cur cur.prev = self.end self.end = cur cur.next = None if(self.start.prev): self.start.prev = None return (self.loc[key]).val return -1 def put(self, key: int, value: int) -> None: if key in self.loc: # replace end to node of list cur = self.loc[key] if cur != self.end: cur.val = value if cur.next and cur.prev: cur.prev.next = cur.next cur.next.prev = cur.prev if cur == self.start: self.start = cur.next if cur == self.end: pass else: self.end.next = cur cur.prev = self.end self.end = cur cur.next = None if(self.start.prev): self.start.prev = None else: self.end.val = value elif self.start is None: self.start = self.end = Node(key,value, None, None) self.cur_capacity += 1 elif self.cur_capacity < self.full_capacity: self.end.next = Node(key, value, None, self.end) self.end = self.end.next self.loc[key] = self.end self.cur_capacity += 1 else: #full cache with new item, evict last used self.end.next = Node(key, value, None, self.end) self.end = self.end.next temp = self.start self.start = self.start.next self.start.prev = None self.loc.pop(temp.key) del temp self.loc[key] = self.end l = LRUCache(2) print(l.put(1,1)) print(l.put(2,2)) print(l.get(1)) print(l.put(3,3)) print(l.get(2)) print(l.put(4,4)) print(l.get(1)) print(l.get(3)) print(l.get(4) ) # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
from typing import List #TODO class Solution: def search(self, nums: List[int], target: int) -> int: high = len(nums)-1 low = 0 while high >= low: # return self.searchIn(nums, 0, len(nums)-1, target) # def searchIn(self, nums: List[int], low: int, high: int, target: int): # mid = (high - low) // 2 # if nums[mid] == target: # return mid # elif target < nums[mid] : # return self.searchIn(nums, low, mid-1, target) # elif target > nums[mid]: # return self.searchIn(nums, mid+1, high, target) # return -1 s = Solution() #print(s.search([-1,0,3,5,9,12], 2)) print(s.search([-1,0,3,5,9,12], 9))
# 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 mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: t3 = TreeNode() if (t1 is None) and (t2 is None): return None elif t1 is None: return t2 elif t2 is None: return t1 t3.val = t1.val + t2.val t3.right = self.mergeTrees(t1.right, t2.right) t3.left = self.mergeTrees(t1.left, t2.left) return t3
def prompt(message, errormessage, isvalid): """Prompt for input given a message and return that value after verifying the input. Keyword arguments: message -- the message to display when asking the user for the value errormessage -- the message to display when the value fails validation isvalid -- a function that returns True if the value given by the user is valid """ res = None while res is None: res = input(str(message)+': ') if not isvalid(res): print str(errormessage) res = None return res """ Can be used with validation functions as shown below""" import re import os.path api_key = prompt( message = "Enter the API key to use for uploading", errormessage= "A valid API key must be provided. This key can be found in your user profile", isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v)) filename = prompt( message = "Enter the path of the file to upload", errormessage= "The file path you provided does not exist", isvalid = lambda v : os.path.isfile(v)) dataset_name = prompt( message = "Enter the name of the dataset you want to create", errormessage= "The dataset must be named", isvalid = lambda v : len(v) > 0)
marks=int(input("Enter the marks")) if(marks>85 and marks<=100): print("Congrats Your Score A"); elif(marks>60 and marks<=85): print("Congrats Your Score B+"); elif(marks>40 and marks<=60): print("Congrats Your Score B"); elif(marks>30 and marks<=40): print("Congrats Your Score C"); else: print("Oops Fail! ..)")
# (8) SUM OF NUMBERS # Michael Manzzella # Oct 11 20:06 # Write a program with a loop that asks the user to enter a series of positive numbers. The user should enter a negative # number to signal the end of the series. After all the positive numbers have been entered, the program should display their # sum. total = 0 num = 0 print('Enter a negative number to escape') while num >= 0: if num >= 0: total = total + num num = int(input('Enter a positve number: ')) print('Sum = ',total)
# Michael Manzella # 22-Sep-20 # # (1) Bug Collector # A bug collector collects bugs every day for five days. Write a program that keeps a running total of the number of bugs # collected during the five days. The loop should ask for the number of bugs collected for each day, and when the loop is # finished, the program should display the total number of bugs collected. # loop five times # display day and ask how many bugs collected # add to bug total # # display total bugs collected total = 0 for day in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']: print('Enter bugs for',day,':', end=' ') bugs = int(input('')) total = total + bugs print(total,'Bugs collected this week') # Enter bugs for Monday : 1 # Enter bugs for Tuesday : 1 # Enter bugs for Wednesday : 1 # Enter bugs for Thursday : 1 # Enter bugs for Friday : 1 # 5 Bugs collected this week
print(""" # Crie um programa que leia o nome completo de uma pessoa e mostre: > O nome com todas as letras maiúsculas > O nome com todas as letras minusculas > Quantas letras ao todo (sem considerar os espaços) > Quantas letras tem o primeiro nome """) nome = str(input('Digite seu nome completo:')).strip() # strip() elimina os espaços antes e depois da string print('Analisando seu nome...') print('Seu nome em maiusculas é: {} '.format(nome.upper())) # coloca todos os caracteres da string em maiúscula print('Seu nome em minúsculas é: {} '.format(nome.lower())) # coloca todos os caracteres da string em minúscula) print('Seu nome tem ao todo {} letras'.format(len(nome) - nome.count(' '))) # elimina os espaços dentro da string print('Seu primeiro nome tem {} letras'.format(nome.find(' '))) # nesta lógica ele encontra o primeiro espaço que está logo após o primeiro nome e como ele não considera o índice onde está o espaço da certo separa = nome.split() # split() cria listas as strings entre os espaços print('Seu primeiro nome é {} e ele tem {} letras'.format(separa[0], len(separa[0])))
# Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. sal = float(input('Qual o salário do Funcionário? R$ ')) aum = sal + (sal * 15 / 100) print('Um funcionário que ganhava {:.2f}, com 15% de aumento, passa a receber {:.2f} de salário.'.format(sal, aum))