text
stringlengths
37
1.41M
# Understanding of Data Pre-processing for given dataset 1 using Spyder (Python) import numpy as np import pandas as pd dataset= pd.read_csv('dataset1.csv') dataset.shape dataset.info() X=dataset.iloc[:,:-1].values X Y=dataset.iloc[:,-1].values Y # 2. Replace Missing values by below imputation strategy. from sklearn.impute import SimpleImputer X = dataset.iloc[:,:-1].values imputer= SimpleImputer(missing_values = np.nan , strategy = 'mean') #mean imputer= imputer.fit(X[:,1:3]) X[:,1:3]= imputer.transform(X[:,1:3]) X X = dataset.iloc[:,:-1].values imputer= SimpleImputer(missing_values = np.nan , strategy = 'median') #median imputer= imputer.fit(X[:,1:3]) X[:,1:3]= imputer.transform(X[:,1:3]) X X = dataset.iloc[:,:-1].values imputer= SimpleImputer(missing_values = np.nan , strategy = 'most_frequent') #mostfrequent imputer= imputer.fit(X[:,1:3]) X[:,1:3]= imputer.transform(X[:,1:3]) X X = dataset.iloc[:,:-1].values imputer = SimpleImputer(missing_values = np.nan, strategy = 'constant',fill_value='IshikaShah') # using constant imputer = imputer.fit(X[:, 1:3]) X[:,1:3] = imputer.transform(X[:, 1:3]) X X = dataset.iloc[:,:-1].values # again storing a value dataset to X imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean') # using mean imputer = imputer.fit(X[:, 1:3]) X[:,1:3] = imputer.transform(X[:, 1:3]) X Y from sklearn.preprocessing import LabelEncoder labelencoder_X = LabelEncoder() X[:,0] = labelencoder_X.fit_transform(X[:,0]) X """ suppose, data = 5, 2, 1, 6, 3 here MinMax Scaler is Min_Max_Scaler = x - minx / (maxx - minx) here in our case = (5-1)/(6-1)=4/5 ~= 0.8 and like wise for other data! 0.8, 0.2, 0, 1, 0.4 similarly for standard scaler, Standard_Scaler = (x-u) / s u = mean = 17/5 = 3.4 s = standard daviation = sqrt ((1.6^2 + 1.4^2 + ....)/5)""" from sklearn.model_selection import train_test_split X_train , X_test , Y_train , Y_test = train_test_split(X,Y,test_size = 0.2,random_state= 0) # Feature Scaling by Standard Scaler from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) X_train X_test # Feature Scaling by MinMax Scaler from sklearn.preprocessing import MinMaxScaler sc_X = MinMaxScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) X_train X_test #DATASET2 dataset2 = 'dataset2.csv' ds = pd.read_csv(dataset2) ds x = ds.iloc[:,:].values x from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.compose import ColumnTransformer transform = ColumnTransformer([("Col 0",OneHotEncoder(),[0])],remainder = 'passthrough') x = transform.fit_transform(x) x transform = ColumnTransformer([("Column 4 converted",OneHotEncoder(),[4])],remainder = 'passthrough') x = transform.fit_transform(x) x transform = ColumnTransformer([("Outlook_OL0_OL1",OneHotEncoder(),[6])],remainder = 'passthrough') x = transform.fit_transform(x) print(x.astype(int))
a, b, c = map(int, raw_input().split()) def any_odd(x, y, z): if x % 2 or y % 2 or z % 2: return True else: return False def exchange(a, b, c): new_a = b // 2 + c // 2 new_b = a // 2 + c // 2 new_c = a // 2 + b // 2 return new_a, new_b, new_c if a == b == c and (a + b + c) % 3 == 0 and not any_odd(a, b, c): print -1 else: k = 0 while not any_odd(a, b, c): a, b, c = exchange(a, b, c) k += 1 print k
#!/usr/bin/env python # coding: utf-8 # In[1]: # Importing libraries to be used. import turtle import time import random delay = 0.1 # Delay variable which will be used for the delay of the screen. score = 0 # Storing current score of your game. high_score = 0 # Storing high score of your game. win = turtle.Screen() # Creating window for the game. win.title("Snake Game") # Creating the title of the game. win.bgcolor("green") # Setting background color of the game. win.setup(width=600, height=600) # Size of the window. win.tracer(0) # To avoid any updates in the game. snake = turtle.Turtle() # Object snake. snake.speed(0) # To avoid in change in speed. snake.shape("square") # Shape of the snake. snake.color("yellow") # Color of the snake. snake.penup() # To avoid any animations. snake.goto(0,0) # Initial position in the window. snake.direction = "stop" # Same thing as for food. food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("blue") food.penup() food.goto(0,100) segments = [] # Creating list for the body of snake. # Things for the scoreboard. pen = turtle.Turtle() pen.speed(0) pen.shape("square") pen.color("black") pen.penup() pen.hideturtle() # Hiding the turtle. pen.goto(0, 260) pen.write("Score: 0 High Score: 0", align="center", font=("Comic Sans MS", 24, "normal")) # Functions for movement. def go_up(): if snake.direction != "down": snake.direction = "up" def go_down(): if snake.direction != "up": snake.direction = "down" def go_left(): if snake.direction != "right": snake.direction = "left" def go_right(): if snake.direction != "left": snake.direction = "right" # Move function. def move(): if snake.direction == "up": y = snake.ycor() snake.sety(y + 20) if snake.direction == "down": y = snake.ycor() snake.sety(y - 20) if snake.direction == "left": x = snake.xcor() snake.setx(x - 20) if snake.direction == "right": x = snake.xcor() snake.setx(x + 20) # For taking input from keyboard. win.listen() win.onkeypress(go_up, "w") win.onkeypress(go_down, "s") win.onkeypress(go_left, "a") win.onkeypress(go_right, "d") while True: win.update() # Condition for player to lose. if snake.xcor()>290 or snake.xcor()<-290 or snake.ycor()>290 or snake.ycor()<-290: time.sleep(0.8) # For stopping window for sometime. snake.goto(0,0) snake.direction = "stop" for segment in segments: segment.goto(1000, 1000) segments.clear() score = 0 delay = 0.1 pen.clear() # For changing the socres.(avoiding overlapping of scores) pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Comic Sans MS", 24, "normal")) # Condition for eating the food. if snake.distance(food) < 20: x = random.randint(-290, 290) y = random.randint(-290, 290) food.goto(x,y) # New body of the snake after eating food. new_segment = turtle.Turtle() new_segment.speed(0) new_segment.shape("square") new_segment.color("red") new_segment.penup() segments.append(new_segment) delay -= 0.001 score += 10 # Changing the high score. if score > high_score: high_score = score pen.clear() pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Comic Sans MS", 24, "normal")) # Adding segments for the body of the snake. for index in range(len(segments)-1, 0, -1): x = segments[index-1].xcor() y = segments[index-1].ycor() segments[index].goto(x, y) if len(segments) > 0: x = snake.xcor() y = snake.ycor() segments[0].goto(x,y) move() # If snake touches its own body. for segment in segments: if segment.distance(snake) < 20: time.sleep(1) snake.goto(0,0) snake.direction = "stop" for segment in segments: segment.goto(1000, 1000) segments.clear() score = 0 delay = 0.1 pen.clear() pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Comic Sans MS", 24, "normal")) time.sleep(delay) wn.mainloop()
''' Filename: Negascout.py Description: Responsible for finding an optimal move based on its evaluation function. @author: Hristo Asenov ''' import Evaluation import MoveGenerator import string import Common import bisect class Negascout(object): ## # Constructor Negascout def __init__(self, board, color): self.hashkeysEvalsSteps = [] self.evaluations = [] self.eval = Evaluation.Evaluation() (self.start_row, self.start_col, self.end_row, self.end_col) = self.eval.getStrongestGrid(board, color) #print "start row: " + str(self.start_row) #print "start col: " + str(self.start_col) #print "end row: " + str(self.end_row) # print "end col: " + str(self.end_col) # self.start_row = 0 # self.start_col = 0 # self.end_row = 7 # self.end_col = 7 ## # Negascout algorithm # @param depth - how deep we would like to go in the tree # @param alpha - initial value of alpha # @param beta - initial value of beta # @param board - 2 dimensional list of the initial board # @param color - initial color of the player # @param steps - the steps that the player has already taken # @param count - turn count # @param hash - a pointer to an object that is the hash of the board # @return - a tuple: first element is integer value of strength, second element is steps taken, third element is # the board at the end, fourth element is the hashkey of the ending board def negascout(self, depth, alpha, beta, board, color, steps, count, hash): if (depth == 0): strength = self.eval.evaluateBoard(board, color, True) #returns the strength value of the board self.insertEntrySorted((hash.get_hashkey(), strength,board), self.hashkeysEvalsSteps) return (strength, steps,board,hash.get_hashkey()) b = beta turnList = [] # Construct a new MoveGenerator object for white and its board, # then generate all the possible moves. moveGen = MoveGenerator.MoveGenerator(count, color, board, hash) # make sure that there are no past moves being made, since # the function will confuse it with push or pull moveGen.genMoves("", self.start_row, self.start_col, self.end_row, self.end_col) #moveGen.genMoves("") # The list of possible moves is stored in moveGen.moveStepHashes # as a list of tuples of the form (the board, the steps taken # to get to that board, and hash key for that board). turnList = moveGen.moveStepHashes for turn in turnList: newBoardState = turn[0] stepPerBoard = turn[1] hashForBoard = turn[2] # reset from initial board hash to new board hash hash.resetInitialHashKey(hashForBoard) newColor = color if depth > 1: # if depth is 1, we need to evaluate the actual board with the same color newColor = string.translate(color, Common.nextColor) currentHashKeys = map(lambda x: x[0], self.hashkeysEvalsSteps) if self.isEntryInList(hashForBoard, currentHashKeys) and depth == 1: # original entry, need to reevaluate # already got the evaluation of it, just return the evaluated value ins_pt = self.getInsPt() a = (self.hashkeysEvalsSteps[ins_pt][0],stepPerBoard,self.hashkeysEvalsSteps[2],self.hashkeysEvalsSteps[3]) else: # descend one level and invert the function bTemp = (-1 * b[0],b[1],b[2],b[3]) alphaTemp = (-1 * alpha[0], alpha[1],alpha[2],alpha[3]) a = self.negascout(depth - 1, bTemp, alphaTemp, newBoardState, newColor, stepPerBoard, count, hash) a = (a[0] * -1,a[1],a[2],a[3]) # alpha-beta pruning if a[0] > alpha[0]: alpha = a if alpha[0] >= beta[0]: return (alpha[0], steps + " | " + alpha[1],alpha[2],alpha[3]) if alpha[0] >= b[0]: betaTemp = (-1 * beta[0],beta[1],beta[2],beta[3]) alphaTemp = (-1 * alpha[0],alpha[1],alpha[2],alpha[3]) alpha = self.negascout(depth - 1, betaTemp, alphaTemp, newBoardState, newColor, stepPerBoard, count, hash) alpha = (alpha[0] * -1,alpha[1],alpha[2],alpha[3]) if alpha[0] >= beta[0]: return (alpha[0],steps + " | " + alpha[1],alpha[2],alpha[3]) b = (alpha[0] + 1,alpha[1],alpha[2],alpha[3]) return (alpha[0],steps + " | " + alpha[1],alpha[2],alpha[3]) def insertEntrySorted(self, entry, list): ins_pt = bisect.bisect_left(list, entry) if len(list) == ins_pt or entry != list[ins_pt]: list.insert(ins_pt, entry) else: raise Exception, "You are trying to append to list after evaluation, and the entry was found which is impossible!!!" def isEntryInList(self, entry, list): ins_pt = bisect.bisect_left(list, entry) if len(list) == ins_pt or entry != list[ins_pt]: self.found_ins_pt = -1 return False else: self.found_ins_pt = ins_pt return True def getInsPt(self): if self.found_ins_pt == -1: raise Exception, "Trying to access insertion point when it wasn't defined" else: return self.found_ins_pt
x = int(input()) y = int(input()) a = int(input()) b = int(input()) if ((x + y) % 2 == 0) and ((a + b) % 2 == 0): print("YES") elif ((x + y) % 2 != 0) and ((a + b) % 2 != 0): print("YES") else: print("NO")
# # @lc app=leetcode.cn id=329 lang=python3 # # [329] 矩阵中的最长递增路径 # # https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix/description/ # # algorithms # Hard (40.91%) # Likes: 193 # Dislikes: 0 # Total Accepted: 14.6K # Total Submissions: 35.6K # Testcase Example: '[[9,9,4],[6,6,8],[2,1,1]]' # # 给定一个整数矩阵,找出最长递增路径的长度。 # # 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。 # # 示例 1: # # 输入: nums = # [ # ⁠ [9,9,4], # ⁠ [6,6,8], # ⁠ [2,1,1] # ] # 输出: 4 # 解释: 最长递增路径为 [1, 2, 6, 9]。 # # 示例 2: # # 输入: nums = # [ # ⁠ [3,4,5], # ⁠ [3,2,6], # ⁠ [2,2,1] # ] # 输出: 4 # 解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。 # # # # @lc code=start class Solution: # 思路:dfs,memo[i][j]记录从i j节点能走的最长路径。 def longestIncreasingPath(self, matrix: List[List[int]]) -> int: if not matrix or not matrix[0]: return 0 row = len(matrix) col = len(matrix[0]) memo = [[0] * col for _ in range(row)] def dfs(i, j): nonlocal memo if memo[i][j] != 0: return memo[i][j] res = 1 for x, y in [[-1, 0], [1, 0], [0, 1], [0, -1]]: tmp_i = x + i tmp_j = y + j if 0 <= tmp_i < row and 0 <= tmp_j < col and matrix[tmp_i][tmp_j] > matrix[i][j]: res = max(res, 1 + dfs(tmp_i, tmp_j)) memo[i][j] = max(res, memo[i][j]) return memo[i][j] return max(dfs(i, j) for i in range(row) for j in range(col)) # @lc code=end
# # @lc app=leetcode.cn id=1021 lang=python3 # # [1021] 删除最外层的括号 # # https://leetcode-cn.com/problems/remove-outermost-parentheses/description/ # # algorithms # Easy (76.90%) # Likes: 117 # Dislikes: 0 # Total Accepted: 30.2K # Total Submissions: 39.1K # Testcase Example: '"(()())(())"' # # 有效括号字符串为空 ("")、"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括号字符串,+ # 代表字符串的连接。例如,"","()","(())()" 和 "(()(()))" 都是有效的括号字符串。 # # 如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。 # # 给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。 # # 对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。 # # # # 示例 1: # # 输入:"(()())(())" # 输出:"()()()" # 解释: # 输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())", # 删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。 # # 示例 2: # # 输入:"(()())(())(()(()))" # 输出:"()()()()(())" # 解释: # 输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))", # 删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。 # # # 示例 3: # # 输入:"()()" # 输出:"" # 解释: # 输入字符串为 "()()",原语化分解得到 "()" + "()", # 删除每个部分中的最外层括号后得到 "" + "" = ""。 # # # # # 提示: # # # S.length <= 10000 # S[i] 为 "(" 或 ")" # S 是一个有效括号字符串 # # # # @lc code=start class Solution: # 思路,找出S中的原语。 # 原语为左括号和右括号正好匹配的字符串,也就是说把原语进行栈操作,栈是为空的。 # 因此可用一个stack存放S的字符,左括号添加进stack,如果是右括号就将stack末位弹出,当数组为空时,说明这是一个原语。 # 通过记录原语的起始位置,去掉最外层括号后,连接到返回值。 def removeOuterParentheses(self, S: str) -> str: res = '' atom_begin = 0 stack = [] for i in range(len(S)): if S[i] == ')': stack.pop() # 找到原语,取出对应的结果并设置新原语的begin位置 if not stack: res += S[atom_begin + 1:i] atom_begin = i + 1 else: stack.append(S[i]) return res # @lc code=end
# # @lc app=leetcode.cn id=152 lang=python3 # # [152] 乘积最大子数组 # # https://leetcode-cn.com/problems/maximum-product-subarray/description/ # # algorithms # Medium (39.69%) # Likes: 621 # Dislikes: 0 # Total Accepted: 74.4K # Total Submissions: 187.4K # Testcase Example: '[2,3,-2,4]' # # 给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。 # # # # 示例 1: # # 输入: [2,3,-2,4] # 输出: 6 # 解释: 子数组 [2,3] 有最大乘积 6。 # # # 示例 2: # # 输入: [-2,0,-1] # 输出: 0 # 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 # # # @lc code=start class Solution: # 因为可能包含负数,如果前面一个子序列的乘积为负数 而 当前元素为负数,则可以得到一个正数, # 所以必须记录pre连续子数组乘积的最大值、最小值。 # 其转移方程如下: # cur_max = max(pre_max * num, pre_min * num, num) # cur_min = min(pre_max * num, pre_min * num, num) def maxProduct(self, nums: List[int]) -> int: if not nums: return res = nums[0] pre_max = nums[0] pre_min = nums[0] for num in nums[1:]: cur_max = max(pre_max * num, pre_min * num, num) cur_min = min(pre_max * num, pre_min * num, num) res = max(res, cur_max) pre_max = cur_max pre_min = cur_min return res # @lc code=end
# # @lc app=leetcode.cn id=143 lang=python3 # # [143] 重排链表 # # https://leetcode-cn.com/problems/reorder-list/description/ # # algorithms # Medium (55.97%) # Likes: 234 # Dislikes: 0 # Total Accepted: 26.9K # Total Submissions: 48.1K # Testcase Example: '[1,2,3,4]' # # 给定一个单链表 L:L0→L1→…→Ln-1→Ln , # 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→… # # 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 # # 示例 1: # # 给定链表 1->2->3->4, 重新排列为 1->4->2->3. # # 示例 2: # # 给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3. # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: # 1、如果链表为空,或者有1个节点,2个节点的时候,直接返回。 # 2、把链表等分为前后两段head1、head2,快慢指针。 # 3、反转head2。 # 4、合并两个链表。 def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ if not head or not head.next or not head.next.next: return head # 利用快慢指针将链表分为两段,长度分别为 a a 或者 a a+1 def splitList(head): dummy = ListNode(0) dummy.next = head slow, fast = dummy, head while fast and fast.next: slow = slow.next fast = fast.next.next head1, head2 = head, slow.next slow.next = None return head1, head2 def reverse(node): if not node.next: return node new_head = reverse(node.next) # 把node放到已反转的子链表的尾部 node.next.next = node node.next = None return new_head # 合并两个链表 def mergeTwoList(l1, l2): dummy = cur = ListNode(-1) while l1 and l2: cur.next = l1 l1 = l1.next cur = cur.next cur.next = l2 l2 = l2.next cur = cur.next if l1: cur.next = l1 if l2: cur.next = l2 return dummy.next head1, head2 = splitList(head) head2 = reverse(head2) mergeTwoList(head1, head2) # @lc code=end
# # @lc app=leetcode.cn id=187 lang=python3 # # [187] 重复的DNA序列 # # https://leetcode-cn.com/problems/repeated-dna-sequences/description/ # # algorithms # Medium (44.51%) # Likes: 102 # Dislikes: 0 # Total Accepted: 19K # Total Submissions: 42.5K # Testcase Example: '"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"' # # 所有 DNA 都由一系列缩写为 A,C,G 和 T 的核苷酸组成,例如:“ACGAATTCCG”。在研究 DNA 时,识别 DNA # 中的重复序列有时会对研究非常有帮助。 # # 编写一个函数来查找目标子串,目标子串的长度为 10,且在 DNA 字符串 s 中出现次数超过一次。 # # # # 示例: # # 输入:s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" # 输出:["AAAAACCCCC", "CCCCCAAAAA"] # # # @lc code=start class Solution: # 思路,10个字母长度的子串序列,出现次数超过一次的,直接遍历记录即可。 def findRepeatedDnaSequences(self, s: str) -> List[str]: res = collections.defaultdict(int) for i in range(0, len(s) - 9): res[s[i:i + 10]] += 1 return [k for k, v in res.items() if v > 1] # @lc code=end
# # @lc app=leetcode.cn id=6 lang=python3 # # [6] Z 字形变换 # # https://leetcode-cn.com/problems/zigzag-conversion/description/ # # algorithms # Medium (48.05%) # Likes: 703 # Dislikes: 0 # Total Accepted: 137.1K # Total Submissions: 285.4K # Testcase Example: '"PAYPALISHIRING"\n3' # # 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 # # 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下: # # L C I R # E T O E S I I G # E D H N # # # 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。 # # 请你实现这个将字符串进行指定行数变换的函数: # # string convert(string s, int numRows); # # 示例 1: # # 输入: s = "LEETCODEISHIRING", numRows = 3 # 输出: "LCIRETOESIIGEDHN" # # # 示例 2: # # 输入: s = "LEETCODEISHIRING", numRows = 4 # 输出: "LDREOEIIECIHNTSG" # 解释: # # L D R # E O E I I # E C I H N # T S G # # # @lc code=start class Solution: # 1、res[row] += c: 把每个字符 c 填入对应行 res[row] # 2、row += direction: 更新当前字符 c 对应的行索引; # 3、direction = - direction: 在达到 ZZ 字形转折点时,执行反向。 def convert(self, s: str, numRows: int) -> str: if numRows < 2: return s res = ['' for _ in range(numRows)] # 当前行和移动方向 row, direction = 0, -1 for c in s: res[row] += c # 换方向 if row == 0 or row == numRows - 1: direction = -direction row += direction return ''.join(res) # @lc code=end
# # @lc app=leetcode.cn id=224 lang=python3 # # [224] 基本计算器 # # https://leetcode-cn.com/problems/basic-calculator/description/ # # algorithms # Hard (38.02%) # Likes: 205 # Dislikes: 0 # Total Accepted: 14.8K # Total Submissions: 39K # Testcase Example: '"1 + 1"' # # 实现一个基本的计算器来计算一个简单的字符串表达式的值。 # # 字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格  。 # # 示例 1: # # 输入: "1 + 1" # 输出: 2 # # # 示例 2: # # 输入: " 2-1 + 2 " # 输出: 3 # # 示例 3: # # 输入: "(1+(4+5+2)-3)+(6+8)" # 输出: 23 # # 说明: # # # 你可以假设所给定的表达式都是有效的。 # 请不要使用内置的库函数 eval。 # # # # @lc code=start class Solution1: def __init__(self) -> None: self.index = 0 # 与227题不一样 def calculate(self, s: str) -> int: s = s.replace(' ', '') return self.get(s) # 因为有括号嵌套,所以采用递归的思路,遇到括号就递归调用get函数 # 而get函数负责处理没有括号的表达式 # res是当前已经算好的结果,cur是目前的数字,pre_op是cur数字之前的符号+- def get(self, s): if self.index >= len(s): return 0 res = 0 pre_op = '+' while self.index < len(s): cur = 0 if s[self.index] == '(': self.index += 1 cur = self.get(s) else: while self.index < len(s) and s[self.index].isdigit(): cur = cur * 10 + int(s[self.index]) self.index += 1 if pre_op == '+': res += cur elif pre_op == '-': res -= cur if self.index < len(s) and s[self.index] == ')': self.index += 1 return res # 更新pre_op if self.index < len(s) and s[self.index] in ['+', '-']: pre_op = s[self.index] self.index += 1 return res class Solution: # 用栈来实现,和上面的递归一样的思路 # 遇到( 时,把先前已经计算好的res 和 pre_op 存放到stack里面,然后开始计算当前括号里面的内容 # 遇到 )时,说明括号里面的内容计算完毕,然后把之前stack里面保存的结果弹出更新结果 # 最后当所有数字结束的时候,需要把结果进行计算,确保结果是正确的。 def calculate(self, s: str) -> int: s = s.replace(' ', '') res, cur_num, pre_op = 0, 0, 1 stack = [] for c in s: if c.isdigit(): cur_num = 10 * cur_num + int(c) elif c == "+" or c == "-": res = res + pre_op * cur_num cur_num = 0 pre_op = 1 if c == "+" else -1 elif c == "(": stack.append(res) stack.append(pre_op) res = 0 pre_op = 1 elif c == ")": res = res + pre_op * cur_num cur_num = 0 res = res * stack.pop() res = stack.pop() + res res = res + pre_op * cur_num return res # @lc code=end if __name__ == "__main__": print(Solution().calculate(s="(6)-(8)-(7)+(1+(6))"))
# # @lc app=leetcode.cn id=912 lang=python3 # # [912] 排序数组 # # @lc code=start class Solution: def sortArray(self, nums: List[int]) -> List[int]: import random def quick_sort(arr, l, r): if l < r: q = partition2(arr, l, r) quick_sort(arr, l, q - 1) quick_sort(arr, q + 1, r) # 算法导论上比较精妙的分割方法 # [l,r]两边都闭区间 def partition(arr, l, r): # 设置哨兵 pivot = arr[r] i = l - 1 for j in range(l, r): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] # 将哨兵交换到i+1位置 arr[i + 1], arr[r] = arr[r], arr[i + 1] return i + 1 # 比较直观容易理解的分割实现 def partition2(array, left, right): # 选最左为哨兵,就先从右遍历;相反也可以 key = array[left] while left < right: while left < right and array[right] > key: right -= 1 array[left] = array[right] while left < right and array[left] <= key: left += 1 array[right] = array[left] array[left] = key return left random.shuffle(nums) quick_sort(nums, 0, len(nums) - 1) return nums # @lc code=end
# # @lc app=leetcode.cn id=884 lang=python3 # # [884] 两句话中的不常见单词 # # https://leetcode-cn.com/problems/uncommon-words-from-two-sentences/description/ # # algorithms # Easy (62.25%) # Likes: 62 # Dislikes: 0 # Total Accepted: 10.9K # Total Submissions: 17.5K # Testcase Example: '"this apple is sweet"\n"this apple is sour"' # # 给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。) # # 如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。 # # 返回所有不常用单词的列表。 # # 您可以按任何顺序返回列表。 # # # # # # # 示例 1: # # 输入:A = "this apple is sweet", B = "this apple is sour" # 输出:["sweet","sour"] # # # 示例 2: # # 输入:A = "apple apple", B = "banana" # 输出:["banana"] # # # # # 提示: # # # 0 <= A.length <= 200 # 0 <= B.length <= 200 # A 和 B 都只包含空格和小写字母。 # # # # @lc code=start class Solution: def uncommonFromSentences(self, A: str, B: str) -> List[str]: count = collections.Counter(A.split()) count += collections.Counter(B.split()) return [word for word in count if count[word] == 1] # @lc code=end
# # @lc app=leetcode.cn id=164 lang=python3 # # [164] 最大间距 # # https://leetcode-cn.com/problems/maximum-gap/description/ # # algorithms # Hard (55.14%) # Likes: 168 # Dislikes: 0 # Total Accepted: 15.8K # Total Submissions: 28.7K # Testcase Example: '[3,6,9,1]' # # 给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 # # 如果数组元素个数小于 2,则返回 0。 # # 示例 1: # # 输入: [3,6,9,1] # 输出: 3 # 解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。 # # 示例 2: # # 输入: [10] # 输出: 0 # 解释: 数组元素个数小于 2,因此返回 0。 # # 说明: # # # 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。 # 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。 # # # # @lc code=start class Solution: # 首先肯定要先排序,然后遍历。但正常排序不满足线性时间复杂度的要求,所以需要用到O(N)的排序。 # 由于元素都是非负整数,所以采用桶排序的方法。 def maximumGap(self, nums: List[int]) -> int: if len(nums) < 2 or min(nums) == max(nums): return 0 min_num, max_num, n = min(nums), max(nums), len(nums) gap = (max_num - min_num) // (n - 1) or 1 # 需要桶的个数 cnt = (max_num - min_num) // gap + 1 # 桶内的下界 上界 buckets = [[None, None] for _ in range(cnt)] for i in nums: bucket = buckets[(i - min_num) // gap] bucket[0] = i if not bucket[0] else min(bucket[0], i) bucket[1] = i if not bucket[1] else max(bucket[1], i) # 因为最后要检查 每个桶的下界 与 上一个桶的上届,所以这里要确保桶下界一定有值 buckets = [b for b in buckets if b[0]] return max(buckets[i][0] - buckets[i - 1][1] for i in range(1, len(buckets))) # @lc code=end
# # @lc app=leetcode.cn id=66 lang=python3 # # [66] 加一 # # https://leetcode-cn.com/problems/plus-one/description/ # # algorithms # Easy (44.34%) # Likes: 485 # Dislikes: 0 # Total Accepted: 164.1K # Total Submissions: 370K # Testcase Example: '[1,2,3]' # # 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 # # 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 # # 你可以假设除了整数 0 之外,这个整数不会以零开头。 # # 示例 1: # # 输入: [1,2,3] # 输出: [1,2,4] # 解释: 输入数组表示数字 123。 # # # 示例 2: # # 输入: [4,3,2,1] # 输出: [4,3,2,2] # 解释: 输入数组表示数字 4321。 # # # # @lc code=start class Solution: def plusOne(self, digits: List[int]) -> List[int]: flag = 1 for i in range(len(digits) - 1, -1, -1): if digits[i] + flag == 10: digits[i] = 0 flag = 1 else: digits[i] = digits[i] + flag flag = 0 if flag == 1: digits.insert(0, 1) return digits # @lc code=end
# # @lc app=leetcode.cn id=599 lang=python3 # # [599] 两个列表的最小索引总和 # # https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists/description/ # # algorithms # Easy (50.84%) # Likes: 73 # Dislikes: 0 # Total Accepted: 15.2K # Total Submissions: 29.7K # Testcase Example: '["Shogun","Tapioca Express","Burger King","KFC"]\n' + '["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]' # # 假设Andy和Doris想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。 # # 你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设总是存在一个答案。 # # 示例 1: # # 输入: # ["Shogun", "Tapioca Express", "Burger King", "KFC"] # ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] # 输出: ["Shogun"] # 解释: 他们唯一共同喜爱的餐厅是“Shogun”。 # # # 示例 2: # # 输入: # ["Shogun", "Tapioca Express", "Burger King", "KFC"] # ["KFC", "Shogun", "Burger King"] # 输出: ["Shogun"] # 解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。 # # # 提示: # # # 两个列表的长度范围都在 [1, 1000]内。 # 两个列表中的字符串的长度将在[1,30]的范围内。 # 下标从0开始,到列表的长度减1。 # 两个列表都没有重复的元素。 # # # # @lc code=start class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: if len(list1) < len(list2): return self.findRestaurant(list2, list1) hashmap = {} min_index = 2000 result = [] for i, restaurant in enumerate(list1): hashmap[restaurant] = i for i in range(len(list2)): if list2[i] in hashmap: if hashmap[list2[i]] + i < min_index: min_index = hashmap[list2[i]] + i result = [list2[i]] elif hashmap[list2[i]] + i == min_index: result.append(list2[i]) return result # @lc code=end
# # @lc app=leetcode.cn id=139 lang=python3 # # [139] 单词拆分 # # https://leetcode-cn.com/problems/word-break/description/ # # algorithms # Medium (44.84%) # Likes: 461 # Dislikes: 0 # Total Accepted: 56.9K # Total Submissions: 127K # Testcase Example: '"leetcode"\n["leet","code"]' # # 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。 # # 说明: # # # 拆分时可以重复使用字典中的单词。 # 你可以假设字典中没有重复的单词。 # # # 示例 1: # # 输入: s = "leetcode", wordDict = ["leet", "code"] # 输出: true # 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。 # # # 示例 2: # # 输入: s = "applepenapple", wordDict = ["apple", "pen"] # 输出: true # 解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。 # 注意你可以重复使用字典中的单词。 # # # 示例 3: # # 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] # 输出: false # # # # @lc code=start class Solution: # 其实就是left right两个指针蛮力搜索字符串, # 当发现[left right]在字典中,且之前的切分合法,则right也可以作为一个切分点。 def wordBreak(self, s: str, wordDict: List[str]) -> bool: n = len(s) dp = [False] * (n + 1) dp[0] = True for left in range(n): if not dp[left]: continue for right in range(left + 1, n + 1): if dp[left] and s[left:right] in wordDict: dp[right] = True return dp[-1] # @lc code=end
# # @lc app=leetcode.cn id=583 lang=python3 # # [583] 两个字符串的删除操作 # # https://leetcode-cn.com/problems/delete-operation-for-two-strings/description/ # # algorithms # Medium (49.27%) # Likes: 118 # Dislikes: 0 # Total Accepted: 8K # Total Submissions: 16.2K # Testcase Example: '"sea"\n"eat"' # # 给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。 # # # # 示例: # # 输入: "sea", "eat" # 输出: 2 # 解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea" # # # # # 提示: # # # 给定单词的长度不超过500。 # 给定单词中的字符只含有小写字母。 # # # # @lc code=start class Solution: # 转化为两个word的最长公共子串问题(但这里只能通过删除操作,没有更改操作) def minDistance(self, word1: str, word2: str) -> int: m = len(word1) n = len(word2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if word1[i - 1] == word2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return m + n - 2 * dp[m][n] # @lc code=end
# # @lc app=leetcode.cn id=493 lang=python3 # # [493] 翻转对 # # https://leetcode-cn.com/problems/reverse-pairs/description/ # # algorithms # Hard (25.94%) # Likes: 99 # Dislikes: 0 # Total Accepted: 4.9K # Total Submissions: 19K # Testcase Example: '[1,3,2,3,1]' # # 给定一个数组 nums ,如果 i < j 且 nums[i] > 2*nums[j] 我们就将 (i, j) 称作一个重要翻转对。 # # 你需要返回给定数组中的重要翻转对的数量。 # # 示例 1: # # # 输入: [1,3,2,3,1] # 输出: 2 # # # 示例 2: # # # 输入: [2,4,3,5,1] # 输出: 3 # # # 注意: # # # 给定数组的长度不会超过50000。 # 输入数组中的所有数字都在32位整数的表示范围内。 # # # # @lc code=start import bisect from typing import List class Solution1: # 归并排序的过程中,如果前半个数组的元素大于后半个数组的元素,这种组合叫翻转对,时间复杂度 O(NlogN) # 而且归并排序就是不停调整翻转对,使其最终有序 def reversePairs(self, nums: List[int]) -> int: # 合并两个有序数组,nums[start, mid) nums[mid:end) def merge(nums, start, mid, end): l, r = start, mid res = list() while l < mid and r < end: if nums[l] < nums[r]: res.append(nums[l]) l += 1 else: res.append(nums[r]) r += 1 nums[start:end] = res + nums[l:mid] + nums[r:end] def mergesort_and_count(nums, start, end): # print('start={},end={}'.format(start, end)) # 为空 或者 只有一个元素时,退出 if start + 1 >= end: return 0 mid = start + (end - start) // 2 count = mergesort_and_count(nums, start, mid) + mergesort_and_count(nums, mid, end) # 统计[start, mid) [mid, end)两个区间中出现的翻转对 j = mid for i in range(start, mid): while j < end and nums[i] > 2 * nums[j]: j += 1 count += j - mid # 合并两个有序区间 merge(nums, start, mid, end) return count return mergesort_and_count(nums, 0, len(nums)) # 树状数组做法, O(NlogN)时间复杂度 class BinaryIndexedTree(object): # 注意index从1开始到N def __init__(self, N): self.BIT = [0] * (N + 1) def __low_bit(self, x): return x & (-x) # 第index个节点增加delta, index从1开始算起 def update(self, index, delta): while index < len(self.BIT): self.BIT[index] += delta index += self.__low_bit(index) # 求数组A[1..index]的和, 包含index def get_sum(self, index): ans = 0 while index > 0: ans += self.BIT[index] index -= self.__low_bit(index) return ans class Solution2: def reversePairs(self, nums: List[int]) -> int: arr = sorted(set(nums)) arr = [x * 2 for x in arr] n1, n2 = len(arr), len(nums) btree = BinaryIndexedTree(n1 + 1) ans = 0 for i, v in enumerate(reversed(nums)): index = bisect.bisect_left(arr, v) ans += btree.get_sum(index) index = bisect.bisect_left(arr, v * 2) btree.update(index + 1, 1) return ans class Solution: # 直接遍历,对于已经遍历过的元素有序拍好并二分找翻转对 def reversePairs(self, nums: List[int]) -> int: ans = 0 arr = list() for v in nums: index = bisect.bisect_right(arr, v * 2) # 默认是在升序数组二分,所以这里要计算后面的长度 ans += (len(arr) - index) bisect.insort_right(arr, v) return ans # @lc code=end if __name__ == "__main__": print(Solution().reversePairs(nums=[1, 3, 2, 3, 1]))
# # @lc app=leetcode.cn id=1221 lang=python3 # # [1221] 分割平衡字符串 # # https://leetcode-cn.com/problems/split-a-string-in-balanced-strings/description/ # # algorithms # Easy (78.34%) # Likes: 53 # Dislikes: 0 # Total Accepted: 19.4K # Total Submissions: 24.7K # Testcase Example: '"RLRRLLRLRL"' # # 在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。 # # 给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。 # # 返回可以通过分割得到的平衡字符串的最大数量。 # # # # 示例 1: # # 输入:s = "RLRRLLRLRL" # 输出:4 # 解释:s 可以分割为 "RL", "RRLL", "RL", "RL", 每个子字符串中都包含相同数量的 'L' 和 'R'。 # # # 示例 2: # # 输入:s = "RLLLLRRRLR" # 输出:3 # 解释:s 可以分割为 "RL", "LLLRRR", "LR", 每个子字符串中都包含相同数量的 'L' 和 'R'。 # # # 示例 3: # # 输入:s = "LLLLRRRR" # 输出:1 # 解释:s 只能保持原样 "LLLLRRRR". # # # # # 提示: # # # 1 <= s.length <= 1000 # s[i] = 'L' 或 'R' # 分割得到的每个字符串都必须是平衡字符串。 # # # # @lc code=start class Solution: # 扫描一遍,贪心 def balancedStringSplit(self, s: str) -> int: cnt, balance = 0, 0 for i in range(len(s)): if s[i] == 'L': balance += 1 if s[i] == 'R': balance -= 1 if balance == 0: cnt += 1 return cnt # @lc code=end
# # @lc app=leetcode.cn id=142 lang=python3 # # [142] 环形链表 II # # https://leetcode-cn.com/problems/linked-list-cycle-ii/description/ # # algorithms # Medium (49.71%) # Likes: 449 # Dislikes: 0 # Total Accepted: 69.2K # Total Submissions: 139K # Testcase Example: '[3,2,0,-4]\n1' # # 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 # # 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 # # 说明:不允许修改给定的链表。 # # # # 示例 1: # # 输入:head = [3,2,0,-4], pos = 1 # 输出:tail connects to node index 1 # 解释:链表中有一个环,其尾部连接到第二个节点。 # # # # # 示例 2: # # 输入:head = [1,2], pos = 0 # 输出:tail connects to node index 0 # 解释:链表中有一个环,其尾部连接到第一个节点。 # # # # # 示例 3: # # 输入:head = [1], pos = -1 # 输出:no cycle # 解释:链表中没有环。 # # # # # # # 进阶: # 你是否可以不用额外空间解决此题? # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 注意第一步时相遇的点不一定为环入口点。 def detectCycle(self, head: ListNode) -> ListNode: # 1、先使用快慢指针判断是否有环。 slow, fast = head, head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: break # 2、退出while时,fast的状态,如果是最后一个节点则无环。 if not fast or not fast.next: return None # 3、如果有环,则把一个指针指向head,然后两个指针再遍历,相遇的点则为入口点。 slow = head while slow != fast: slow = slow.next fast = fast.next return fast # @lc code=end
# # @lc app=leetcode.cn id=14 lang=python3 # # [14] 最长公共前缀 # # https://leetcode-cn.com/problems/longest-common-prefix/description/ # # algorithms # Easy (38.24%) # Likes: 1094 # Dislikes: 0 # Total Accepted: 288.5K # Total Submissions: 754.2K # Testcase Example: '["flower","flow","flight"]' # # 编写一个函数来查找字符串数组中的最长公共前缀。 # # 如果不存在公共前缀,返回空字符串 ""。 # # 示例 1: # # 输入: ["flower","flow","flight"] # 输出: "fl" # # # 示例 2: # # 输入: ["dog","racecar","car"] # 输出: "" # 解释: 输入不存在公共前缀。 # # # 说明: # # 所有输入只包含小写字母 a-z 。 # # # @lc code=start class Solution: # 思路:依次比较strs中的字符串,找到最长的前缀,直到比较完所有的字符串。 def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return '' prefix = strs[0] for i in range(1, len(strs)): if not prefix: return '' # 缩小前缀继续和第i个元素找 while prefix not in strs[i][:len(prefix)] and len(prefix) > 0: prefix = prefix[:len(prefix) - 1] return prefix # @lc code=end
# # @lc app=leetcode.cn id=86 lang=python3 # # [86] 分隔链表 # # https://leetcode-cn.com/problems/partition-list/description/ # # algorithms # Medium (58.13%) # Likes: 214 # Dislikes: 0 # Total Accepted: 39.3K # Total Submissions: 67.6K # Testcase Example: '[1,4,3,2,5,2]\n3' # # 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 # # 你应当保留两个分区中每个节点的初始相对位置。 # # 示例: # # 输入: head = 1->4->3->2->5->2, x = 3 # 输出: 1->2->2->4->3->5 # # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def partition(self, head: ListNode, x: int) -> ListNode: if not head or not head.next: return head dummy_small = ListNode('#') p_small = dummy_small dummy_big = ListNode('#') p_big = dummy_big while head: if head.val < x: p_small.next = head p_small = p_small.next else: p_big.next = head p_big = p_big.next head = head.next p_small.next = dummy_big.next p_big.next = None return dummy_small.next # @lc code=end
# # @lc app=leetcode.cn id=559 lang=python3 # # [559] N叉树的最大深度 # # https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/description/ # # algorithms # Easy (69.61%) # Likes: 93 # Dislikes: 0 # Total Accepted: 25.9K # Total Submissions: 37.2K # Testcase Example: '[1,null,3,2,4,null,5,6]' # # 给定一个 N 叉树,找到其最大深度。 # # 最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。 # # 例如,给定一个 3叉树 : # # # # # # # # 我们应返回其最大深度,3。 # # 说明: # # # 树的深度不会超过 1000。 # 树的节点总不会超过 5000。 # # # @lc code=start """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def maxDepth(self, root: 'Node') -> int: if not root: return 0 if not root.children: return 1 res = 0 for child in root.children: res = max(res, self.maxDepth(child) + 1) return res # @lc code=end
# # @lc app=leetcode.cn id=70 lang=python3 # # [70] 爬楼梯 # # https://leetcode-cn.com/problems/climbing-stairs/description/ # # algorithms # Easy (49.73%) # Likes: 1076 # Dislikes: 0 # Total Accepted: 222.6K # Total Submissions: 447.6K # Testcase Example: '2' # # 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 # # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # # 注意:给定 n 是一个正整数。 # # 示例 1: # # 输入: 2 # 输出: 2 # 解释: 有两种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 # 2. 2 阶 # # 示例 2: # # 输入: 3 # 输出: 3 # 解释: 有三种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 + 1 阶 # 2. 1 阶 + 2 阶 # 3. 2 阶 + 1 阶 # # # # @lc code=start class Solution: def climbStairs(self, n: int) -> int: dp = [1 for _ in range(n + 1)] for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] # @lc code=end
# # @lc app=leetcode.cn id=121 lang=python3 # # [121] 买卖股票的最佳时机 # # https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/ # # algorithms # Easy (54.19%) # Likes: 1011 # Dislikes: 0 # Total Accepted: 219.5K # Total Submissions: 405.1K # Testcase Example: '[7,1,5,3,6,4]' # # 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 # # 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。 # # 注意:你不能在买入股票前卖出股票。 # # # # 示例 1: # # 输入: [7,1,5,3,6,4] # 输出: 5 # 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 # ⁠ 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。 # # # 示例 2: # # 输入: [7,6,4,3,1] # 输出: 0 # 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 # # # # @lc code=start class Solution: # dp[i][0] 第i天手上没有股票 # dp[i][1] 第i天手上有股票 def maxProfit(self, prices: List[int]) -> int: n = len(prices) if n <= 1: return 0 dp = [[0] * 2 for _ in range(n)] dp[0][0] = 0 dp[0][1] = -prices[0] # 只允许一次交易 for i in range(1, n): dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]) dp[i][1] = max(dp[i - 1][1], -prices[i]) return dp[-1][0] # @lc code=end
# # @lc app=leetcode.cn id=216 lang=python3 # # [216] 组合总和 III # # https://leetcode-cn.com/problems/combination-sum-iii/description/ # # algorithms # Medium (71.26%) # Likes: 123 # Dislikes: 0 # Total Accepted: 22.3K # Total Submissions: 31.3K # Testcase Example: '3\n7' # # 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。 # # 说明: # # # 所有数字都是正整数。 # 解集不能包含重复的组合。  # # # 示例 1: # # 输入: k = 3, n = 7 # 输出: [[1,2,4]] # # # 示例 2: # # 输入: k = 3, n = 9 # 输出: [[1,2,6], [1,3,5], [2,3,4]] # # # # @lc code=start import copy class Solution: def combinationSum3(self, k: int, n: int) -> List[List[int]]: res = [] def backtrack(start, k, tmp_sum, tmp_res): nonlocal res if k == 0 and tmp_sum == 0: res.append(copy.deepcopy(tmp_res)) # 组合中一个数字只能出现一次,所以从下一位开始选i for i in range(start + 1, 10): tmp_res.append(i) backtrack(i, k - 1, tmp_sum - i, tmp_res) tmp_res.pop() backtrack(0, k, n, []) return res # @lc code=end
# # @lc app=leetcode.cn id=719 lang=python3 # # [719] 找出第 k 小的距离对 # # https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance/description/ # # algorithms # Hard (32.99%) # Likes: 99 # Dislikes: 0 # Total Accepted: 4.3K # Total Submissions: 12.8K # Testcase Example: '[1,3,1]\n1' # # 给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。 # # 示例 1: # # # 输入: # nums = [1,3,1] # k = 1 # 输出:0 # 解释: # 所有数对如下: # (1,3) -> 2 # (1,1) -> 0 # (3,1) -> 2 # 因此第 1 个最小距离的数对是 (1,1),它们之间的距离为 0。 # # # 提示: # # # 2 <= len(nums) <= 10000. # 0 <= nums[i] < 1000000. # 1 <= k <= len(nums) * (len(nums) - 1) / 2. # # # # @lc code=start import heapq class Solution1: # 时间复杂度:O((k+N)logN),k最大可以达到 O(N^2),因此最坏情况下,时间复杂度为O(N^2logN),超出了时间限制 def smallestDistancePair(self, nums: List[int], k: int) -> int: nums.sort() heap = [(nums[i + 1] - nums[i], i, i + 1) for i in range(len(nums) - 1)] heapq.heapify(heap) for _ in range(k): d, i, j = heapq.heappop(heap) if j + 1 < len(nums): heapq.heappush(heap, (nums[j + 1] - nums[i], i, j + 1)) return d class Solution: # 二分法,类似378题,目标距离一定存在[lo, hi]之间,应该可以二分逼近查找 def smallestDistancePair(self, nums: List[int], k: int) -> int: def possible(guess): #Is there k or more pairs with distance <= guess? count = left = 0 for right, x in enumerate(nums): while x - nums[left] > guess: left += 1 count += right - left return count >= k nums.sort() lo = 0 hi = nums[-1] - nums[0] + 1 while lo < hi: mi = (lo + hi) // 2 if possible(mi): hi = mi else: lo = mi + 1 return lo # @lc code=end
import matplotlib.pyplot as plt import numpy as np def simple_process(): cnt = 2 primes = [] x = [] y = [] while True: flag = True for i in range(2, cnt): if cnt % i == 0: flag = False break if flag is True: primes.append(cnt) x.append(cnt) y.append(len(primes)) cnt += 1 plt.plot(x, y) plt.title("Prime Steps") plt.xlabel("number") plt.ylabel("number of primes") plt.grid() plt.pause(1e-9) plt.clf() def rapid_process(): cnt = 3 primes = np.array([2]) x = np.array([]) y = np.array([]) while True: flag = True for i in range(3, int(np.sqrt(cnt))+2, 2): if cnt % i == 0: flag = False break if flag is True: primes = np.append(primes, cnt) x = np.append(x, cnt) y = np.append(y, primes.size) prime_theorem = x/np.log(x) cnt += 2 plt.plot(x, y, color='g', label=str(primes[-1]), drawstyle='steps') plt.plot(x, prime_theorem, color='k', label='prime theorem', ls='--') plt.title("Prime Steps") plt.xlabel("number") plt.ylabel("number of primes") plt.legend(loc='upper left') plt.grid() plt.pause(1e-15) plt.clf() #simple_process() rapid_process()
import functools nums = [1, 2, 1, 3, 2, 5] ret = functools.reduce(lambda x, y: x ^ y, nums) div = 1 while div & ret == 0: div <<= 1 a, b = 0, 0 for n in nums: if n & div: a ^= n else: b ^= n print([a, b])
class Apartamento: def __init__(self): self.id = int() self.numero = str() self.torre = None self.vaga = int() self.proximo = None def cadastrar(self, valor): self.id = int(input("Digite o id do apartamento: ")) self.numero = str(input("Digite o número do apartamento: ")) self.torre = valor def imprimir(self): print(f"Id do Apartamento: {self.id} \nNúmero: {self.numero} \nTorre: {self.torre.nome}")
import tkinter as tk from tkinter import ttk window = tk.Tk() window.title("My Window") window.geometry("600x600+0+0") namelabel = ttk.Label(window, text="Miss P", foreground="red", font=("Helvetica", 58)) namelabel.pack() whatisnamelabel = ttk.Label(window, text="Hello, what is your name?") whatisnamelabel.pack() nameentry = ttk.Entry(window) nameentry.insert(0, "DEFAULT") nameentry.pack() whatisanimallabel = ttk.Label(window, text="What is your favourite animal?") whatisanimallabel.pack() #To use radiobuttons, we first need a variable that will hold the selected answer. For this, we could use text, but to keep it simple, we will use numbers today. #I am going to call this variable "animalvalue" animalvalue = 0 #Next, we are going to make the radiobuttons to add. #The first optin is the parent - in this case, we have called it "window". #"Text" allows us to choose what text will be displayed next to the button #"Variable" tells us what variable the option choice is going to modify - in this case, all three buttons will modify the "animalvalue" variable #"Value" tells the computer what to set the variable that we previously chose to. animalone = ttk.Radiobutton(window, text="Cats", variable=animalvalue, value=1) animaltwo = ttk.Radiobutton(window, text="Definitely cats", variable=animalvalue, value=2) animalthree = ttk.Radiobutton(window, text="Cats are the best", variable=animalvalue, value=3) #Don't forget to pack them! animalone.pack() animaltwo.pack() animalthree.pack() window.mainloop()
import tkinter as tk from tkinter import ttk window = tk.Tk() window.title("My Window") window.geometry("600x600+0+0") namelabel = ttk.Label(window, text="Miss P", foreground="red", font=("Helvetica", 58)) namelabel.pack() #In order to show the image in our program, we first need to know where to find it #THE IMAGE NEEDS TO BE A GIF TO WORK #The image component is found in TK, not TTK. #We use PhotoImage to create a new object of a "PhotoImage" #"file" tells the computer where to find the image that we a re using. For this I would recommend using relative links inside of a project folder. #The "r" refers to a "raw" string. It means that the backslashes will be used as part of the actual string and not as an escape character like it would be in a "normal"string #This essentially tells the computer to read the string as it is, not with any extra formatting catimage = tk.PhotoImage(file=r"\\phs.local\Users\Home\Staff\jepetersen\Desktop\cat.gif") #We need to make a new label (to hold the image) and use the "image" option to tell the computer where to find the PhotoImage. catimagelabel = ttk.Label(window, image=catimage) catimagelabel.pack() window.mainloop()
import sqlite3 # initialize database def create_db(db_name): conn = sqlite3.connect(db_name) c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS DENTALINFO (dentist_id integer PRIMARY KEY AUTOINCREMENT, dentist_name text NOT NULL, location text NOT NULL, specialization text NOT NULL, phone text NOT NULL); ''') print("Table created") c.close() conn.commit() conn.close() def inserst_db(db_name): conn = sqlite3.connect(db_name) c = conn.cursor() c.execute("INSERT INTO DENTALINFO (dentist_name, location, specialization, phone) \ VALUES ('dr.sharon', 'Burwood', 'Oral Surgery', '0451028117')") c.execute("INSERT INTO DENTALINFO (dentist_name, location, specialization, phone) \ VALUES ('dr.henry', 'Randwick', 'Paediatric Dentistry', '0451123456')") c.execute("INSERT INTO DENTALINFO (dentist_name, location, specialization, phone) \ VALUES ('dr.suzy', 'Eastwood', 'Orthodontics','0451456789')") print("Inserted") c.close() conn.commit() conn.close() if __name__ == '__main__': create_db("DentalService.db") inserst_db("DentalService.db")
#!python from sorting_iterative import is_sorted, bubble_sort, selection_sort, insertion_sort from timeit import default_timer as timer def random_ints(count=20, min=1, max=50): """Return a list of `count` integers sampled uniformly at random from given range [`min`...`max`] with replacement (duplicates are allowed).""" import random return [random.randint(min, max) for _ in range(count)] def merge(items1, items2): """ Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. Running time: O(n + m) Memory usage: O(n + m) """ # Repeat until one list is empty # Find minimum item in both lists and append it to new list # Append remaining items in non-empty list to new list merge_arr = [] i, j = 0, 0 while i < len(items1) and j < len(items2): # readability and don't have to make a copy when used val_1 = items1[i] val_2 = items2[j] if items1[i] <= items2[j]: merge_arr.append(val_1) i += 1 else: merge_arr.append(val_2) j += 1 # --- in case we can't use the .extend function --- # if lst1_index == len(items1): # for num in items2[lst2_index:]: # merge_arr.append(num) # elif lst2_index == len(items2): # for num in items1[lst1_index:]: # merge_arr.append(num) merge_arr.extend(items1[i:]) # extend is basically this 'merge_arr += items[i:]' merge_arr.extend(items2[j:]) return merge_arr def split_sort_merge(items): """ Sort given items by splitting list into two approximately equal halves, sorting each with an iterative sorting algorithm, and merging results into a list in sorted order. Running time: Best: O(n) Worst: O(n) Memory usage: O(n) """ # Split items list into approximately equal halves # Sort each half using any other sorting algorithm # Merge sorted halves into one list in sorted order lst1, lst2 = bubble_sort(items[0 : len(items)//2]), selection_sort(items[len(items)//2 : len(items)]) # return in-place array items[:] = merge(lst1, lst2) # return a new array # return merge(lst1, lst) # @time_it def merge_sort(items): """ Sort given items by splitting list into two approximately equal halves, sorting each recursively, and merging results into a list in sorted order. Running time: Best: O(n * log(n)) Average: O(n * log(n)) Worst: O(n * log(n)) Memory usage: O(log(n)) """ # Check if list is so small it's already sorted (base case) # Split items list into approximately equal halves # Sort each half by recursively calling merge sort # Merge sorted halves into one list in sorted order # returns in-place array for sorted elements # --- thanks Ben and Shash --- if len(items) > 1: mid = len(items) // 2 left = items[:mid] right = items[mid:] merge_sort(left) merge_sort(right) merged = merge(left, right) items[:] = merged # overwriting items array def merge_sort_out_of_place(items): if len(items) <= 1: return items mid = len(items)//2 left_half = merge_sort_out_of_place(items[0:mid]) right_half = merge_sort_out_of_place(items[mid:len(items)]) return merge(left_half, right_half) def partition(items, low, high): """ Return index `p` after in-place partitioning given items in range `[low...high]` by choosing a pivot (TODO: document your method here) from that range, moving pivot into index `p`, items less than pivot into range `[low...p-1]`, and items greater than pivot into range `[p+1...high]`. Running time: Best: O(n) Average: O(n) Worst: (n) Memory usage: O(1) """ # Choose a pivot any way and document your method in docstring above divider = low pivot = high # last item as pivot # Loop through all items in range [low..high] for index in range(low, high): # Move items less than pivot into front of range [low...p-1] # Move items greater than pivot into back of range [p+1...high] if items[index] < items[pivot]: # swap with divider items[index], items[divider] = items[divider], items[index] divider += 1 # Move pivot item into final position [p] and return index p items[pivot], items[divider] = items[divider], items[pivot] return divider def quick_sort(items, low=None, high=None): """ Sort given items in place by partitioning items in range `[low...high]` around a pivot item and recursively sorting each remaining sublist range. Running time: Best: O(n * log(n)) Average: O(n * log(n)) Worst: O(n^2) -- almost reversed or sorted Memory usage: O(log(n)) """ # Check if high and low range bounds have default values (not given) if low is None or high is None: low = 0 high = len(items) - 1 # Check if list or range is so small it's already sorted (base case) if (high - low) > 0: # Partition items in-place around a pivot and get index of pivot pivot = partition(items, low, high) # Sort each sublist range by recursively calling quick sort quick_sort(items, low, pivot - 1) quick_sort(items, pivot + 1, high) def time(func, lst): start = timer() func(lst) end = timer() total = round((end - start) * 1000, 5) # print(func, total) return total def compare(num_comparisons, num_ints, func1, func2): sort1_count = 0 for i in range(num_comparisons): lst = random_ints(num_ints, 1, 100) sort1 = time(merge_sort, lst) sort2 = time(quick_sort, lst) if sort1 < sort2: sort1_count += 1 print(func1, sort1_count / num_comparisons) print(func2, (num_comparisons - sort1_count) / num_comparisons) if __name__ == "__main__": # a = [9, 8, 7, 6, 5, 4, 3, 2, 1] # b = random_ints(50, 1, 30) # c = random_ints(1000, 1, 100) # d = random_ints(10000, 1, 1000) # e = random_ints(15, 1, 50) # f = [4, 5, 7, 3, 1, 9, 6, 5] # g = [41, 35, 9, 40, 18, 21, 29, 20, 35, 12, 46, 12, 3, 28, 40] # dups 12, 35, 40 # lst = b # time(merge_sort_out_of_place, lst) # time(insertion_sort, lst) # time(merge_sort, lst) # time(quick_sort, lst) # compare(10000, 50, merge_sort_out_of_place, insertion_sort) # compare(10000, 100, merge_sort, merge_sort_out_of_place) compare(100, 1000, merge_sort, quick_sort)
""" Three columns CSV to JSON converter """ import csv def isLast(itr): old = next(itr) for new in itr: yield False, old old = new yield True, old with open('misc-data/seventytwo-names.csv', 'r', encoding='utf-8') as cf: in_data = csv.reader(cf, delimiter=',') # num_rows = sum(1 for row in in_data) print('{"s72":[', end='') for i, (is_last, row) in enumerate(isLast(in_data)): if (not row[0]): continue if (i % 3 == 0): print('[', end='') print('["'+row[0]+'","'+row[1]+'","'+row[2]+'"', end='') print(']', end='') if (i % 3 == 2): print(']', end='') if not is_last: print(',') print(']}') # print(nRow, 'data')
import time #Some Functions and Exercice with while loop def tcheck_pass (): while input("password : ") != "sidali" : print("wrong !Try again !") print("Correct ,Comme on in ;) ") tcheck_pass() #fonction print from 1 to 10 n=1 while n<=10 : print(n) time.sleep(1) #This ligne make python pause 1 second n+=1 print("from 1 to 10 done") #This function asks the user to enter a word if the one already exists ill go out of the program def no_repeating(): words = [] while True: word = input("Tell me a word: ") if word in words: print("You told me that word already!") break words.append(word) return words no_repeating() #Fond x and y that x*y = 512 def find_512(): for x in range(100): for y in range(100): if x * y == 512: break # does not do what we want! return f"{x} * {y} == 512" print(find_512())
# # This implements the ability to compose and pipe functions so that they can # short circuit the pipe/composition with a value to return class ReturnValue(Exception): """ This is used to short circuit the valuation and return ret """ def __init__(self, ret): self.ret = ret def runPipe(m, initialValue): try: return m(initialValue) except ReturnValue, retv: return retv.ret def runPipeCurry(m): return lambda initialValue : runPipe(m, initialValue) def pipe(fs): """ Functional piping: pipe([f, g])(x) == g(f(x)) """ def _(v): t = v for f in fs: t = f(t) return t return _ def compose(fs): """ Functional composition: compose([f, g])(x) = f(g(x)) """ fs = list(fs) fs.reverse() return pipe(fs) def emit(v): raise ReturnValue(v) def ret(v): return v def const(c): """ Shorthand for lambda c : lambda _ : ret(c) """ return lambda _ : ret(c) def hookError(f, onError): """ Returns a function that will call f, and if f throws an exception calls onError and reraises the exception. Example: f = lambda s : s + ' world' onError = lambda e : sys.stdout.write(str(e) + '\n') print hookError(f, onError)('hello') This will print 'hello world'. If we change f to: f = lambda _ : raise Exception() hookError will raise an exception after printing the string represenation of the exception to stdout. If an error happens in onError, that is what will be raised """ def _(*args, **kwargs): try: return f(*args, **kwargs) except ReturnValue: # Don't hook the error in this case raise except Exception, err: onError(err, *args, **kwargs) raise return _
# Most callback-based frameworks, such as NodeJS and Tornado, handle events # using callback functions. For example if you want to download a webpage # you would do: # # downloadWebpage(url, function (contents) { /* handle page downloaded */ }) # # In Twisted, downloadWebpage would return a Deferred to which you would add # a callback, in pseudo code something like: # d = downloadWebpage(url) # d.addCallback(function(contents) { /* handle page downlaoded */ }) # # At the lowest level, Twisted has callbacks but a library exposes control # flow through deferreds rather than callbacks. A user of a library would # almost never pass in a function to call upon an event, rather they call # a function and a Deferred is returned from that function, callbacks # can then be added to that Deferred. # # It should be noted that Deferreds are not magic, they are not aware of # asynchronous events or anything. They are solely a mechanism for describing # how data should move through some control flow. You don't even actually have # to use Twisted to make use of the behavior of Deferreds. All of these examples # will, though. import time from twisted.internet import reactor from twisted.internet import defer from twisted.python import log # Example 1: Make a function that sleeps for some amount of time # Note that this function will return immediatly, but it is the # firing of the deferred that is being delayed def sleep(duration): # Create a deferred that will be returned d = defer.Deferred() # Tell the reactor to schedule the callback method of d to be # called after duration, call it with None. The callback # method takes a value but in this case we don't need one # since we are just trying to wait some period of time reactor.callLater(duration, d.callback, None) # Return d return d def useSleep(): print 'Sleeping' d = sleep(10) def _print(_): print 'Waking' d.addCallback(_print) return d # Example 2: The output of one callback becomes the input to the next # callback. def chaining(): d = defer.Deferred() d.addCallback(lambda x : x + 1) d.addCallback(lambda x : x * 2) d.addCallback(lambda x : x - 1) def _print(x): print x return x d.addCallback(_print) d.callback(1) return d # Example 3: Deferreds check to see if the previous callback returned # a Deferred and will add themselves to its callback. A callback can # return a Deferred and the behavior is what one would expect. The output # of the nested Deferred will become the input to the next callback. # In this exampple sleep returns a Deferred that will be fired # at the end of a duration. We are adding 2 more sleeps to that Deferred # so the entire Deferred will not be fired until the last 3 second sleep is # done. def sleepABunch(): print 'Sleeping' d = sleep(1).addCallback(lambda _ : sleep(2)).addCallback(lambda _ : sleep(3)) def _print(_): print 'Waking' d.addCallback(_print) return d # Example 4: Deferreds handle both success and errors. Add success handlers with # .addCallback and add failure handlers with .addErrback. A Deferred will capture any # Exception thrown in it and wrap it in a Failure object and give it to the next errback # in line. This mimics how exception handling works. def errorHandling(): def _callback(x): print 'Callback', x return x + 1 def _causeError(x): raise Exception('Causing exception at callback %d' % x) def _handleError(f): log.err(f) return 0 def _dontHandleError(f): log.err(f) return f d = defer.Deferred() d.addCallback(_callback) d.addCallback(_callback) d.addCallback(_callback) d.addCallback(_causeError) d.addErrback(_handleError) d.addCallback(_callback) d.addErrback(_handleError) d.addCallback(_causeError) d.addErrback(_dontHandleError) d.addErrback(_handleError) d.callback(0) return d # Example 5: Writing all this callback-based code is terrible, but Twisted # provides a trick using decorators and generators make it a bit easier @defer.inlineCallbacks def inlined(): print 'Sleeping' # We can call something that returns a deferred with yield yield sleep(3) print 'Waking' print 'Calling chaining' # yield can also return a value so we can get responses as well value = yield chaining() print 'Chaining returned', value # This is not valid though: # value = yield chaining() + yield chaining() # Example 6: Because inlineCallbacks make use of generators, and generators # cannot return a value, we have to use a special function to return # a value from an inlined callback @defer.inlineCallbacks def inlinedReturn(): @defer.inlineCallbacks def _inlinedReturn(): value1 = yield chaining() value2 = yield chaining() # This will return the sum of the two values defer.returnValue(value1 + value2) ret = yield _inlinedReturn() print ret # Example 7: Error handling looks closer to what we would expect in sequential code too @defer.inlineCallbacks def inlinedErrors(): try: yield sleep(1) raise Exception('Causing an exception') except Exception, err: print 'Caught exception:', err @defer.inlineCallbacks def _timeit(f): startTime = time.time() ret = yield f() endTime = time.time() print 'Time: %f' % (endTime - startTime) defer.returnValue(ret) @defer.inlineCallbacks def run(): print 'Example 1' yield _timeit(lambda : useSleep()) print print 'Example 2' yield _timeit(lambda : chaining()) print print 'Example 3' yield _timeit(lambda : sleepABunch()) print print 'Example 4' yield _timeit(lambda : errorHandling()) print print 'Example 5' yield _timeit(lambda : inlined()) print print 'Example 6' yield _timeit(lambda : inlinedReturn()) print print 'Example 7' yield _timeit(lambda : inlinedErrors()) print def main(): def _run(): d = run() d.addCallback(lambda _ : reactor.stop()) def _error(f): log.err(f) reactor.stop() d.addErrback(_error) return d reactor.callLater(0.0, _run) reactor.run() if __name__ == '__main__': main()
import random team1 = input("Enter The First Team: ") team2 = input("Enter The Second Team: ") team_name = False #Checking if Team 1 or Team 2 Input equals to Csk if team1.upper() == 'CSK' or team2.upper() == 'CSK': if(team1.upper() == 'CSK'): squad_of_team_1 = ['MS Dhoni(c)(wk)', 'Faf Du Plesis', 'Shane Watson', 'Ambati Raydu', 'Ravindra Jadeja', 'Dwane Bravo', 'Sam Currun' , 'Deepak Chahar', 'Shardul Thakur','Karn Sharma', 'Piyush Chawla', 'KM Asif', 'Imran Tahir', 'Kedar Jadhav', 'Lungi Ngidi', 'Mitchell Sentener', 'Monu Singh', 'Murli Vijay', 'Ruturaj Gaikwad', 'Josh Hezalwood', 'R Shai Kishore'] if(team2.upper() == 'CSK'): squad_of_team_2 = ['MS Dhoni(c)(wk)', 'Faf Du Plesis', 'Shane Watson', 'Ambati Raydu', 'Ravindra Jadeja', 'Dwane Bravo', 'Sam Currun' , 'Deepak Chahar', 'Shardul Thakur','Karn Sharma', 'Piyush Chawla', 'KM Asif', 'Imran Tahir', 'Kedar Jadhav', 'Lungi Ngidi', 'Mitchell Sentener', 'Monu Singh', 'Murli Vijay', 'Ruturaj Gaikwad', 'Josh Hezalwood', 'R Shai Kishore'] #Checking if Team 1 or Team 2 Input equals to Mi if team1.upper() == 'MI' or team2.upper() == 'MI': if(team1.upper() == 'MI'): squad_of_team_1 = ['Rohit Sharma(c)', 'Quinton De Cock', 'Suryakumar Yadav', 'Ishan Kishan', 'Krunal Pandya', 'Hardik Pandya' , 'Kieron Pollard', 'Aditya Tare', 'Anmolpreet Singh','Ankul Roy', 'Dhawal Kulkarni', 'Jayant Yadav', 'Mitchell Mclleghan', 'Rahul Chahar','Surfane RutherFord', 'Trent Boult', 'Chrish Lynn', 'Digvijay Deshmukh', 'Mosing Khan', 'Nathan Kultar Nile', 'Prince Balwant Rai Singh', 'Saurbh Tiwari', 'James Pattinson', 'Jaspreet Bumrah'] if(team2.upper() == 'MI'): squad_of_team_2 = ['Rohit Sharma(c)', 'Quinton De Cock', 'Suryakumar Yadav', 'Ishan Kishan', 'Krunal Pandya', 'Hardik Pandya' , 'Kieron Pollard', 'Aditya Tare', 'Anmolpreet Singh','Ankul Roy', 'Dhawal Kulkarni', 'Jayant Yadav', 'Mitchell Mclleghan', 'Rahul Chahar','Surfane RutherFord', 'Trent Boult', 'Chrish Lynn', 'Digvijay Deshmukh', 'Mosing Khan', 'Nathan Kultar Nile', 'Prince Balwant Rai Singh', 'Saurbh Tiwari', 'James Pattinson', 'Jaspreet Bumrah'] team_name = True #Checking if Team 1 or Team 2 Input equals to RCB if team1.upper() == 'RCB' or team2.upper() == 'RCB': if(team1.upper() == 'RCB'): squad_of_team_1 = ['Virat Kohli(c)', 'AB de Villiers', 'Devdutt Padikkal', 'Gurkeerat Singh', 'Moeen Ali', 'Mohammed Siraj', 'Navdeep Saini', 'Parthiv Patel', 'Pawan Negi', 'Shivam Dube', 'Umesh Yadav', 'Washington Sundar', 'Yuzvendra Chahal', 'Aaron Finch', 'Chris Morris', 'Dale Steyn', 'Isuru Udana', 'Joshua Philippe', 'Pavan Deshpande', 'Shahbaz Ahamad', 'Adam Zampa'] if(team2.upper() == 'RCB'): squad_of_team_2 = ['Virat Kohli(c)', 'AB de Villiers', 'Devdutt Padikkal', 'Gurkeerat Singh', 'Moeen Ali', 'Mohammed Siraj', 'Navdeep Saini', 'Parthiv Patel', 'Pawan Negi', 'Shivam Dube', 'Umesh Yadav', 'Washington Sundar', 'Yuzvendra Chahal', 'Aaron Finch', 'Chris Morris', 'Dale Steyn', 'Isuru Udana', 'Joshua Philippe', 'Pavan Deshpande', 'Shahbaz Ahamad', 'Adam Zampa'] team_name = True #Checking if Team 1 or Team 2 Input equals to KXIP if team1.upper() == 'KXIP' or team2.upper() == 'KXIP': if(team1.upper() == 'KXIP'): squad_of_team_1 = ['KL Rahul(c)', 'Arshdeep Singh', 'Chris Gayle', 'Darshan Nalkande', 'Krishnappa Gowtham', 'Hardus Viljoen', 'Harpreet Brar', 'Jagadeesha Suchith', 'Karun Nair', 'Mandeep Singh', 'Mayank Agarwal', 'Mohammed Shami', 'Mujeeb Ur Rahman', 'Murugan Ashwin', 'Nicholas Pooran', 'Sarfaraz Khan', 'Chris Jordan', 'Deepak Hooda', 'Glenn Maxwell', 'Ishan Porel', 'James Neesham', 'Prabhsimran Singh', 'Ravi Bishnoi', 'Sheldon Cottrell', 'Tajinder Dhillon'] if(team2.upper() == 'KXIP'): squad_of_team_2 = ['KL Rahul(c)', 'Arshdeep Singh', 'Chris Gayle', 'Darshan Nalkande', 'Krishnappa Gowtham', 'Hardus Viljoen', 'Harpreet Brar', 'Jagadeesha Suchith', 'Karun Nair', 'Mandeep Singh', 'Mayank Agarwal', 'Mohammed Shami', 'Mujeeb Ur Rahman', 'Murugan Ashwin', 'Nicholas Pooran', 'Sarfaraz Khan', 'Chris Jordan', 'Deepak Hooda', 'Glenn Maxwell', 'Ishan Porel', 'James Neesham', 'Prabhsimran Singh', 'Ravi Bishnoi', 'Sheldon Cottrell', 'Tajinder Dhillon'] team_name = True #Checking if Team 1 or Team 2 Input equals to KKR if team1.upper() == 'KKR' or team2.upper() == 'KKR': if(team1.upper() == 'KKR'): squad_of_team_1 = ['Dinesh Karthik (c)', 'Andre Russell', 'Kamlesh Nagarkoti', 'Kuldeep Yadav', 'Lockie Ferguson', 'Nitish Rana', 'Prasidh Krishna', 'Rinku Singh', 'Sandeep Warrier', 'Shivam Mavi', 'Shubman Gill', 'Siddhesh Lad', 'Sunil Narine', 'Chris Green', 'Eoin Morgan', 'M Siddharth', 'Nikhil Naik', 'Pat Cummins', 'Rahul Tripathi', 'Tom Banton', 'Varun Chakravarthy'] if(team2.upper() == 'KKR'): squad_of_team_2 = ['KL Rahul(c)', 'Arshdeep Singh', 'Chris Gayle', 'Darshan Nalkande', 'Krishnappa Gowtham', 'Hardus Viljoen', 'Harpreet Brar', 'Jagadeesha Suchith', 'Karun Nair', 'Mandeep Singh', 'Mayank Agarwal', 'Mohammed Shami', 'Mujeeb Ur Rahman', 'Murugan Ashwin', 'Nicholas Pooran', 'Sarfaraz Khan', 'Chris Jordan', 'Deepak Hooda', 'Glenn Maxwell', 'Ishan Porel', 'James Neesham', 'Prabhsimran Singh', 'Ravi Bishnoi', 'Sheldon Cottrell', 'Tajinder Dhillon'] team_name = True #Checking if Team 1 or Team 2 Input equals to SRH if team1.upper() == 'SRH' or team2.upper() == 'SRH': if(team1.upper() == 'SRH'): squad_of_team_1 = ['David Warner(c)', 'Abhishek Sharma', 'Basil Thampi', 'Bhuvneshwar Kumar', 'Billy Stanlake', 'Jonny Bairstow', 'Kane Williamson', 'Manish Pandey', 'Mohammad Nabi', 'Rashid Khan', 'Sandeep Sharma', 'Shahbaz Nadeem', 'Shreevats Goswami', 'Siddarth Kaul', 'Khaleel Ahmed', 'T Natarajan', 'Vijay Shankar', 'Wriddhiman Saha', 'Abdul Samad', 'Fabian Allen', 'Mitchell Marsh', 'Priyam Garg', 'Sandeep Bavanaka', 'Sanjay Yadav', 'Virat Singh'] if(team2.upper() == 'SRH'): squad_of_team_2 = ['David Warner(c)', 'Abhishek Sharma', 'Basil Thampi', 'Bhuvneshwar Kumar', 'Billy Stanlake', 'Jonny Bairstow', 'Kane Williamson', 'Manish Pandey', 'Mohammad Nabi', 'Rashid Khan', 'Sandeep Sharma', 'Shahbaz Nadeem', 'Shreevats Goswami', 'Siddarth Kaul', 'Khaleel Ahmed', 'T Natarajan', 'Vijay Shankar', 'Wriddhiman Saha', 'Abdul Samad', 'Fabian Allen', 'Mitchell Marsh', 'Priyam Garg', 'Sandeep Bavanaka', 'Sanjay Yadav', 'Virat Singh'] team_name = True #Checking if Team 1 or Team 2 Input equals to RR if team1.upper() == 'RR' or team2.upper() == 'RR': if(team1.upper() == 'RR'): squad_of_team_1 = ['Steve Smith(c)', 'Ankit Rajpoot', 'Ben Stokes', 'Jofra Archer', 'Jos Buttler', 'Mahipal Lomror', 'Manan Vohra', 'Mayank Markande', 'Rahul Tewatia', 'Riyan Parag', 'Sanju Samson', 'Shashank Singh', 'Shreyas Gopal', 'Varun Aaron', 'Akash Singh', 'Anirudha Joshi', 'Anuj Rawat', 'Andrew Tye', 'David Miller', 'Jaydev Unadkat', 'Kartik Tyagi', 'Oshane Thomas', 'Robin Uthappa', 'Tom Curran', 'Yashasvi Jaiswal'] if(team2.upper() == 'RR'): squad_of_team_2 = ['Steve Smith(c)', 'Ankit Rajpoot', 'Ben Stokes', 'Jofra Archer', 'Jos Buttler', 'Mahipal Lomror', 'Manan Vohra', 'Mayank Markande', 'Rahul Tewatia', 'Riyan Parag', 'Sanju Samson', 'Shashank Singh', 'Shreyas Gopal', 'Varun Aaron', 'Akash Singh', 'Anirudha Joshi', 'Anuj Rawat', 'Andrew Tye', 'David Miller', 'Jaydev Unadkat', 'Kartik Tyagi', 'Oshane Thomas', 'Robin Uthappa', 'Tom Curran', 'Yashasvi Jaiswal'] team_name = True #Checking if Team 1 or Team 2 Input equals to DC if team1.upper() == 'DC' or team2.upper() == 'DC': if(team1.upper() == 'DC'): squad_of_team_1 = ['Shreyas Iyer(c)', 'Ajinkya Rahane', 'Amit Mishra', 'Avesh Khan', 'Axar Patel', 'Harshal Patel', 'Ishant Sharma', 'Kagiso Rabada', 'Keemo Paul', 'Prithvi Shaw', 'R Ashwin', 'Rishabh Pant', 'Sandeep Lamichhane', 'Shikhar Dhawan', 'Alex Carey', 'Lalit Yadav', 'Marcus Stoinis', 'Mohit Sharma', 'Shimron Hetmyer', 'Tushar Deshpande', 'Daniels Sams', 'Anrich Nortje'] if(team2.upper() == 'DC'): squad_of_team_2 = ['Shreyas Iyer(c)', 'Ajinkya Rahane', 'Amit Mishra', 'Avesh Khan', 'Axar Patel', 'Harshal Patel', 'Ishant Sharma', 'Kagiso Rabada', 'Keemo Paul', 'Prithvi Shaw', 'R Ashwin', 'Rishabh Pant', 'Sandeep Lamichhane', 'Shikhar Dhawan', 'Alex Carey', 'Lalit Yadav', 'Marcus Stoinis', 'Mohit Sharma', 'Shimron Hetmyer', 'Tushar Deshpande', 'Daniels Sams', 'Anrich Nortje'] team_name = True if team_name == False: print("Wrong Team") quit() random_squad_for_1 = set({}) random_squad_for_2 = set({}) for i in range(1, 11): random_squad_for_1.add(random.randint(1, len(squad_of_team_1))) random_squad_for_2.add(random.randint(1, len(squad_of_team_2))) while len(random_squad_for_1) < 11: random_squad_for_1.add(random.randint(1, len(squad_of_team_1))) while len(random_squad_for_2) < 11: random_squad_for_2.add(random.randint(1, len(squad_of_team_2))) print(f"{team1} is throwing the toss") choice = ['Heads', 'Tails'] team_2_sayed = random.randint(0, 1) team_2_sayed = choice[team_2_sayed] print(f"{team2} Says {team_2_sayed}") coin_value = random.randint(0, 1) coin_value = choice[coin_value] if team_2_sayed == coin_value: bat_or_bowl = ['Bat', 'Bowl'] team_want_to_choose = random.randint(0, 1) print(f"{team2} Won the toss and elected to {bat_or_bowl[team_want_to_choose]}") else: bat_or_bowl = ['Bat', 'Bowl'] team_want_to_choose = random.randint(0, 1) print(f"{team2} Won the toss and elected to {bat_or_bowl[team_want_to_choose]}") print("\nSquads:- \n") #Printing Squad 1 print(f"{team1} Squad:- ") random_squad_team_1 = [] #printing Captain for j in random_squad_for_1: random_squad_team_1.append(j) print("1. " + squad_of_team_1[0]) for i in range(0, 10): num = random_squad_team_1[i] print(f"{i + 2}. {squad_of_team_1[num]}") #Printing Squad 2 print("\n") print(f"{team2} Squad:- ") random_squad_team_2 = [] #printing Captain for j in random_squad_for_2: random_squad_team_2.append(j) print("1. " + squad_of_team_2[0]) for i in range(0, 10): num = random_squad_team_2[i] print(f"{i + 2}. {squad_of_team_2[num]}")
# Basic calculator in python 3.6 # Made in Turkey # By akerem16 # [EN] First we will get number of operations. We will run the code block according to what action will be taken. # [TR] ilk önce işlem numarasını almamız gerekiyor. Hangi işlem yapılacaksa ona göre kod bloğu çalıştıracağız. operationnumber = str(input(""" [EN] Hello i am a basic calculator! Thanks to me, you can quickly do the following: 1- Addition (+) 2- Subtraction (-) 3- Multiplication (*) 4- Division (/) 5- Get power (^^) 0- Exit code [TR] Merhaba. Ben basit bir hesap makinesiyim! Benim sayemde aşağıdakileri işlemleri hızlıca yapabilirsiniz: 1- Toplama (+) 2- Çıkarma (-) 3- Çarpma (*) 4- Bölme (/) 5- Üssünü alma (^^) 0- Çıkış Your choice: """)) # [EN] Now we define operations according to the selection made. # [TR] Şimdi yapılan seçime göre işlemleri tanımlıyoruz. if operationnumber == "1": print("Result:", int(input("Number 1: ")) + int(input("Number 2: "))) elif operationnumber == "2": print("Result:", int(input("Number 1: ")) - int(input("Number 2: "))) elif operationnumber == "3": print("Result:", int(input("Number 1: ")) * int(input("Number 2: "))) elif operationnumber == "4": print("Result:", int(input("Number 1: ")) / int(input("Number 2: "))) elif operationnumber == "5": print("Result:", int(input("Number 1: ")) ** int(input("Number 2: "))) elif operationnumber == "0": exit() else: print("[EN] Wrong choice entered.") print("[TR] Hatalı giriş yapıldı.") exit()
def max_num (num1, num2, num3): #find the largest number in these 3 max=num1 if num1>=num2: if num1>=num3: max=num1 else: max=num3 elif num2>=num3: max=num2 else: max=num3 return max print (max_num(5, 3, 7)) def is_equal (str1, str2): #compare if two string is equal return str1==str2 #in Python, object contents are compared using == instead of equals() # != is "not equal" print (is_equal("gg", "gg"))
friends=["Bob", "John", "Jim", "gg"] first_friend=friends[0] print(first_friend) print(friends) print(friends[-1]) #negative index just overflow print(friends[1:3]) #print from index 1 to (3-1)print(friends[1:]) #print from index 1 to the end friends [1]="fuck" #modify the element in list index 1 to "fuck"
def checkDouble(x): for i in range(5): if str(x)[i] == str(x)[i+1] and str(x).count(str(x)[i]) <= 2: return True return False def checkIncreasing(x): sort = "".join(sorted(str(x))) if str(x) == sort: return True return False lowerLimit = 254032 upperLimit = 789860 possiblePasswords = [] for i in range(lowerLimit, upperLimit+1): if checkDouble(i) and checkIncreasing(i): possiblePasswords.append(i) print(len(possiblePasswords))
#Pergunte a quantidade de km percorridos por um carro alugado e a quantidade de dias pelos quais #ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60 p/dia e R$ 0,15 por km rodado dias = int(input('Por quantos dias o carro foi alugado? ')) km = int(input('Quantos km rodados? ')) pagar = (dias*60) + (km*0.15) print('O total a pagar é R${:.2f} !'.format(pagar) )
#Leia a altura e a largura de uma parede em metros, calcule a sua area e a quntidade # necessária de tinta para pinta-la, sabendo que cada l pinta 2m² altura = float(input('Digite a altura da parede em metros: ')) largura = float(input('Digite a largura da parece em metros: ')) mquadrado = altura * largura tinta = mquadrado / 2 print('A quantidade de tinta necessária para pintar {:.2f}m² é {:.2f}l!'. format(mquadrado,tinta))
n = input('Digite algo: ') print('Qual o tipo primitivo?', type(n)) print('É numérico?',n.isnumeric()) print('É alfanumérico? ',n.isalnum()) print('É alfa',n.isalpha()) print('É ascii',n.isascii()) print('É decimal', n.isdecimal()) print('É digit', n.isdigit()) print('É identifier', n.isidentifier()) print('É tudo minúsculo', n.islower()) print('É printable', n.isprintable()) print('É espaço', n.isspace()) print('É capitalizada', n.istitle()) print('É tudo maiúsculo', n.isupper())
'''Leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a media atingida: media abaixo de 5.0 REPROVADO media entre 5 e 6.9 RECUPERAÇÃO media 7 ou superior APROVADO''' n1 = float(input('Digite a primeira nota do aluno: ')) n2 = float(input('Digite a segunda nota do aluno: ')) media = (n1 + n2) / 2 if media < 5.0: print('A média do aluno foi {}.Aluno reprovado!'.format(media)) elif media >= 5 or media < 7: print('A média do aluno foi {}. Aluno em recuperação!'.format(media)) else: print('A média do aluno foi {}. Aluno aprovado!'.format(media))
# holds all of the data in array values import os import sys import my_data from my_data import symptoms_names from my_data import symptoms_numbers from my_data import disease_match_to_symptom from my_data import symptom_match_to_disease # save these from the user entering them # should match with 392680, 8031, 27497 user_symptoms = ["shortness of breath", "pain chest","nausea"] indices = [] matched_indexes = [] # find the user symptoms in the symptoms list and save the index values for j in user_symptoms: indices = [i for i, x in enumerate(symptoms_names) if x == j ] #print (indices) for i in indices: matched_indexes.append(i) print matched_indexes # the corresponding symptom number that the user entered matched_symptom_numbers = [] for i in matched_indexes: matched_symptom_numbers.append(symptoms_numbers[i]) print matched_symptom_numbers # match those symptom numbers with their corresponding disease numbers # save the top-5 diseases, print them out in order
*** Problem Statement # Given ‘N’ ropes with different lengths, we need to connect these ropes into one big rope with minimum cost. The cost of connecting two ropes is equal to the sum of their lengths. Example 1: Input: [1, 3, 11, 5] Output: 33 Explanation: First connect 1+3(=4), then 4+5(=9), and then 9+11(=20). So the total cost is 33 (4+9+20) Example 2: Input: [3, 4, 5, 6] Output: 36 Explanation: First connect 3+4(=7), then 5+6(=11), 7+11(=18). Total cost is 36 (7+11+18) Example 3: Input: [1, 3, 11, 5, 2] Output: 42 Explanation: First connect 1+2(=3), then 3+3(=6), 6+5(=11), 11+11(=22). Total cost is 42 (3+6+11+22) *** from heapq import * def minimum_cost_to_connect_ropes(ropeLengths): result = [] final_result=0 for i in range(len(ropeLengths)): heappush(result, ropeLengths[i]) while len(result)!=1: x=0 for i in range(2): x+=heappop(result) final_result+=x heappush(result, x) return final_result def main(): print("Minimum cost to connect ropes: " + str(minimum_cost_to_connect_ropes([1, 3, 11, 5]))) print("Minimum cost to connect ropes: " + str(minimum_cost_to_connect_ropes([3, 4, 5, 6]))) print("Minimum cost to connect ropes: " + str(minimum_cost_to_connect_ropes([1, 3, 11, 5, 2]))) main()
*** Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference. Examples : Input : A[] = {l, 3, 15, 11, 2} B[] = {23, 127, 235, 19, 8} Output : 3 That is, the pair (11, 8) Input : A[] = {l0, 5, 40} B[] = {50, 90, 80} Output : 10 That is, the pair (40, 50) Explaination: So bascially the naive approach here would be using two for lopps and scanning all the elements in both the Arrays. However, the time complexity for that would be O(N^2). The more better approach would be to sort the arrays frist which take O(LogN) and then compare elements in both the arrya. *** def findSmallestDifference(A,B,m,n): A.sort() B.sort() Diff=float('inf') i=m-1 j=n-1 while i>-1 and j>-1: if B[j]>=A[i]: Diff= min(abs(B[j]-A[i]), Diff) j-=1 if B[j]<A[i]: Diff= min(abs(A[i]-B[j]), Diff) i-=1 return Diff A = [1, 2, 11, 5] #After Sorting [1,2,5,11] # Input given array B B = [4, 12, 19, 23, 127, 235] # Calculate size of Both arrays m = len(A) n = len(B) # Call function to # print smallest result print(findSmallestDifference(A, B, m, n))
# Задание 3 # Функция принимает три числа a, b, c. Функция должна определить, существует ли треугольник с такими сторонами. # Если треугольник существует, вернёт True, иначе False. a=int(input()) b=int(input()) c=int(input()) def triangle (a,b,c): if a+b>c and b+c>a and a+c>b: print('True') else: print('False') triangle (a,b,c)
def task(): print('\n<<< Виконання завдання >>>') # Получаем строку и сразу разбираем её по словам в массив (список) через split() # Строка "привет всем и пока" в split сделает список: ['привет', 'всем', 'и', 'пока'] text = input('Введіть щось: ').split() # Перебираем каждое слово: # Создаём типо последовательность от 0 до длинны списка (нашей строки, которая теперь список) # Длинна списка будет 4, но максимальный индекс = 3 (потому что нумерация от нуля) for i in range(len(text)): # Если первая буква (вторая кв. скобочка [0]) равна 'a', то if text[i-1][0].lower() == 'a': # Если длина слова <= 3, то оно нафиг удаляется, а цикл начинает новую итерацию (continue) if len(text[i-1]) <= 3: text.pop(i-1) continue # Бахаем срез этому слову ([:-3] означает от первого символа до 3-го с конца (за конец отвечает минус)) text[i-1] = text[i-1][:-3] # " ".join(список) собирает весь список в строку с разделителем " " (пробелы, но можно хоть " *** ") print(f' Результат: {" ".join(text)}') print('\n>>> Лабораторну роботу №3 виконала\n' '>>> студентка КМ-93 Довгаль Єва\n' '>>> Варіанти кожного завдання: 4\n') print('Суть завдання:\n' ' Видалити останні 3 символа зі слів, що починаються на "a"') while True: task() restart = input('Може ще раз? Y/N\n') if restart.lower().replace(' ', '') != 'y': break
# Autor: Salamandra #Url del ejercicio: http://www.pythondiario.com/2013/05/ejercicios-en-python-parte-1.html # Definir una función generar_n_caracteres() que tome un entero n y devuelva el caracter multiplicado por n. Por ejemplo: generar_n_caracteres(5, "x") debería devolver "xxxxx". def generar_n_caracteres(caracter,cantidad): return caracter*cantidad print("Programa para generar una cantidad de caracteres dados") caracter=input("Ingrese el caracter: ") cantidad=int(input("Ingrese la cantidad de veces que quiera el que caracter '" + caracter + "' se desea repetir: ")) print(generar_n_caracteres(caracter,cantidad))
#sum program sum = 10 def calculate(): sum = 30 sum = sum + 20 currentSum = 200 totalSum = sum + currentSum print(totalSum) calculate(); print (sum)
# def info_person(): # person = {"name": "Jorge", "age": "31", "country": "Mexico", "programingLang": "Python"} # print "My name is ", person["name"] # print "My age is ", person["age"] # print "My country of birth is ", person["country"] # print "My favorite language is ", person["programingLang"] # # info_person() def info person(): person = {"name": "Jorge", "age": "31", "country": "Mexico", "programingLang": "Python"} for key, value in person.items(): print "My ", key, "is ", value info_person()
def showStd(): students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] for data in students: print data["first_name"]+" "+data["last_name"] showStd() print ("-")* 5, "Part II", ("-")*5 def showinfo(): users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } for keys in users: print keys numStd = 1 for data in users[keys]: wordsCount = len(data["first_name"]) + len(data["last_name"]) print numStd, "-", data["first_name"], data["last_name"], "-", wordsCount numStd +=1 showinfo()
import csv import sys def count_for_chf(): with open('/Users/Shia/Documents/Capstone/FeatExtraction/data/brfss/extracted.csv', 'rb') as csv_file: reader = csv.DictReader(csv_file) count = [0, 0, 0, 0] # 0-40, 40-60, 60-80, 80+ for row in reader: if row['VETERAN3'] == '1': age = float(row['_AGE80']) if age < 40: count[0] += 1 elif age < 60: count[1] += 1 elif age < 80: count[2] += 1 else: count[3] += 1 print count if __name__ == "__main__": count_for_chf()
class SequenceIterator(): def __init__(self, sequence: object): self._sequence = sequence self._iterator = iter(self._sequence._contents) def __next__(self): while True: elem = next(self._iterator) if self._sequence._filter(elem): return elem class Sequence(): def __init__(self, iterable: object): self._contents = iterable self._filter = lambda foo: True def __iter__(self): return SequenceIterator(self) def Filter(self, func): newseq = Sequence(self) newseq._filter = func return newseq def test(): numbers = [i for i in range(1, 10)] seq = Sequence(numbers) print(numbers) print(seq) def Print(iterable): for elem in iterable: print(elem, end=' ') print() Print( numbers ) Print( seq ) Print( seq ) Print( seq.Filter(lambda x: x % 2 == 0) ) Print( Sequence(numbers).Filter(lambda x: x % 3 == 0).Filter(lambda x: x > 5) ) #test()
from sys import argv from math import sqrt from typing import List from time import sleep class Sudoku: def __init__(self, sudoku: List[List[int]]): ''' :param sudoku: int[n][n] :attr N: n * n ''' self.board = sudoku self.N = len(self.board[0]) self.n = int(sqrt(self.N)) self.sep = "\n" + ("+ " + ("- " * self.n)) * self.n + "+" self.s = 1 / self.N / 2 def valid(self, r: int, c: int, num: int) -> bool: ''' :param r, c: current position (rth row, cth col) :returns True if num can be placed at board[r, c] else False ''' R, C = (r // self.n) * self.n, (c // self.n) * self.n for i in range(self.N): if num in (self.board[r][i], self.board[i][c], self.board[R + (i % self.n)][C + (i // self.n)]): return False return True def solve(self, r: int = 0, c: int = 0, verbose=0) -> bool: ''' :param r, c: current position (rth row, cth col) :recursively tries to solve the sudoku by trying to place numbers from [r, c] ''' if r > self.N and c > self.N: return True if self.board[r][c]: return self.solve(r, c + 1, verbose) if c + 1 < self.N else (self.solve(r + 1, 0, verbose) if r + 1 < self.N else True) for i in range(1, self.N + 1): if self.valid(r, c, i): if verbose: sleep(self.s) print("\033c", end='') self.disp() self.board[r][c] = i if self.solve(r, c, verbose): return True else: self.board[r][c] = 0 return False def disp(self): print(self.sep) [print((("| " + "{} " * self.n) * self.n + "|").format(*('{:x}'.format(j) if j else " " for j in self.board[i])), self.sep if not (i + 1) % self.n else "") for i in range(self.N)] def main(): try: with open(argv[1], "r") as f: sudoku = Sudoku([list(map(lambda x: int(x, 16), x.split())) for x in f]) solved = sudoku.solve(verbose=int(argv[2])) print("\033c", end='') sudoku.disp() print("Solved" if solved else "No Solution") except Exception as e: # print(f"Error! {e}") print(f"Usage python(3) {argv[0]} filename 0/1 {{1 for solution with steps. 0 for only final solution}}") print("file contains n lines of n space separated integers between 1 and n") exit(1) # 0 0 0 2 6 0 7 0 1 # 6 8 0 0 7 0 0 9 0 # 1 9 0 0 0 4 5 0 0 # 8 2 0 1 0 0 0 4 0 # 0 0 4 6 0 2 9 0 0 # 0 5 0 0 0 3 0 2 8 # 0 0 9 3 0 0 0 7 4 # 0 4 0 0 5 0 0 3 6 # 7 0 3 0 1 8 0 0 0 if __name__ == '__main__': main()
import math class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return str((self.x, self.y)) def __hash__(self): return hash((self.x, self.y)) def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __ne__(self, other): return not self.__eq__(other) def manhattanDistance(self, point): """Returns the Manhattan distance to another point.""" return abs(self.x - point.x) + abs(self.y - point.y) class WireSegment: def __init__(self, starting_point, direction, distance): assert direction in {"U", "D", "L", "R"}, "Invalid direction" self.starting_point = starting_point self.direction = direction self.distance = distance def __repr__(self): return "WireSegment(" + str(self.starting_point) + ", " + self.direction + ", " + str(self.distance) + ")" def isVertical(self): """Returns whether the WireSegment is aligned vertically.""" return (self.direction in {"U", "D"}) def isHorizontal(self): """Returns whether the WireSegment is aligned horizontally.""" return not self.isVertical() def getStartingPoint(self): """Returns the starting point of the WireSegment.""" return self.starting_point def getEndPoint(self): """Returns the ending point of the WireSegment.""" x = self.starting_point.x y = self.starting_point.y if self.direction is "L": return Point(x - self.distance, y) elif self.direction is "R": return Point(x + self.distance, y) elif self.direction is "U": return Point(x, y + self.distance) elif self.direction is "D": return Point(x, y - self.distance) def getPoints(self): """Returns all grid points touched by the WireSegment.""" start = self.starting_point end = self.getEndPoint() if self.direction is "L": return {Point(x, start.y) for x in range(end.x, start.x + 1)} elif self.direction is "R": return {Point(x, start.y) for x in range(start.x, end.x + 1)} elif self.direction is "U": return {Point(start.x, y) for y in range(start.y, end.y + 1)} elif self.direction is "D": return {Point(start.x, y) for y in range(end.y, start.y + 1)} def getIntersections(self, segment): """Checks against another WireSegment and returns the set of all intersections.""" a1 = self.getStartingPoint() a2 = self.getEndPoint() b1 = segment.getStartingPoint() b2 = segment.getEndPoint() if ( min(a1.x, a2.x) > max(b1.x, b2.x) or max(a1.x, a2.x) < min(b1.x, b2.x) or min(a1.y, a2.y) > max(b1.y, b2.y) or max(a1.y, a2.y) < min(b1.y, b2.y) ): return set() else: return self.getPoints().intersection(segment.getPoints()) def stepsToReachPoint(self, point): """Returns the number of steps along the WireSegment it takes to reach the given Point.""" assert point in self.getPoints() return self.starting_point.manhattanDistance(point) class Wire: def __init__(self, segments): self.segments = segments self.starting_point = segments[0].starting_point def isContinuous(self): """Returns whether all consecutive WireSegments of the Wire are connected.""" cursor = self.starting_point for segment in self.segments: if cursor == segment.getStartingPoint(): cursor = segment.getEndPoint() else: return False return True def getPoints(self): """Returns all grid points touched by the Wire.""" points = set() for segment in self.segments: points = points.union(segment.getPoints()) return points def getIntersections(self, wire): """Checks against another Wire or WireSegment and returns the set of all intersections.""" return set.intersection(self.getPoints(), wire.getPoints()) def stepsToReachPoint(self, point): """Returns the number of steps along the Wire it takes to reach the given Point.""" steps = 0 for segment in self.segments: if point in segment.getPoints(): steps += segment.stepsToReachPoint(point) return steps else: steps += segment.distance raise ValueError("Given point is not part of Wire.") if __name__ == "__main__": with open("input/3.input", "r") as file: wires = [] for line in file: wire_data = line.strip().split(",") wire_data = [(x[0], x[1:]) for x in wire_data] cursor = Point(0,0) segments = [] for segment_data in wire_data: direction = segment_data[0] distance = int(segment_data[1]) segment = WireSegment(cursor, direction, distance) segments.append(segment) cursor = segment.getEndPoint() wires.append(Wire(segments)) central_port = Point(0,0) wire_a = wires[0] wire_b = wires[1] intersections = Wire.getIntersections(wire_a, wire_b) intersections.remove(central_port) # Part 1 closestDistance = min([central_port.manhattanDistance(point) for point in intersections]) print("PART 1 | central port <--> closest wire intersection:", closestDistance) # Part 2 fewestCombinedSteps = min([wire_a.stepsToReachPoint(point) + wire_b.stepsToReachPoint(point) for point in intersections]) print("PART 2 | minimum combined step distance:", fewestCombinedSteps)
'''#1 import math a, b, c = eval(raw_input("Enter a, b, c:")) n = b*b-4*a*c if (n>0): r1 =( -b + math.sqrt(b*b-4*a*c))/2*a r2 =( -b - math.sqrt(b*b-4*a*c))/2*a print(r1 , r2) elif (n==0): r1 =( -b + math.sqrt(b*b-4*a*c))/2*a r2 =( -b - math.sqrt(b*b-4*a*c))/2*a r1 = r2 print(r1) if (n<0) : print("The equation has no real roots") ''' '''#2 import random n1=random.randint(1,100) n2=random.randint(1,100) n=n1+n2 num = raw_input(("qing shu ru shang mian de lia ge shu zhi he:")) if num == n: print("True") else: print("False") print(n) ''' '''#3 today = eval (raw_input("jin tian shi :")) day = eval(raw_input("guo le ji tian :")) week = (today+day)%7 if week == 0: print("jin tian shi {} and the future day is Sunday".format(today)) elif week == 1: print("jin tian shi {} and the future day is Monday".format(today)) elif week == 2: print("jin tian shi {} and the future day is Tuesday".format(today)) elif week == 3: print("jin tian shi {} and the future day is Wendnesday".format(today)) elif week == 4: print("jin tian shi {} and the future day is Thurday".format(today)) elif week == 5: print("jin tian shi {} and the future day is Firday".format(today)) ''' '''#4 print("qing shu ru san ge zheng shu :") x = eval(raw_input(">>")) y = eval(raw_input(">>")) z = eval(raw_input(">>")) if x>y: x,y = y,x if x>z: x,z = z,x if y>z: y,z = z,y print(x,y,z) ''' '''#5 w1,p1 = eval(raw_input('Enter weight and price for package 1"')) w2,p2 = eval(raw_input('Enter weight and price for package 2"')) baozhuang1 = p1 / w1 baozhuang2 = p2 / w2 if baozhuang1 < baozhuang2: print('package 1 has the better price') elif baozhuang1 >baozhuang2: print('package 2 has the better price') else: print('package 1 the same as package 2') ''' '''#6 month ,year = eval(raw_input("shu ru month and years:")) a = 0 if(a){ case 1: case 3: case 5: case 7: case 8: case 10: case 12 :print("31\n");break case 2:if (year%4==0 and year%100!=0 | year%400==0): a=29 else: a=28 case 4: case 6: case 9: case 11:print("30\n"); } print(a) ''' '''#7 import random yingbi = eval(raw_input("cha shi zhengmian(1) huanshi fanmian(0):")) n = random.randint(0,1) if (n == 1): print('True') if n==0: print('False') ''' '''#11 num = eval(raw_input("shu ru yi ge san wei shu:")) bai = num /100 shi = num/10%10 ge = num % 10 if bai == ge: print("{} is a pailndrome".format(num)) else: print("{} is not a pailndrome".format(num)) ''' '''#12 a,b,c = eval(raw_input("shu ru san jiao xing de san ge bian:")) zc = a+b+c if (a+b>c): print("The perimeter is {}".format(zc)) else: print("shu ru fei fa") '''
""" 날짜 : 2020/06/24 이름 : 이성진 내용 : 내장함수 교재 p231 """ # abs() : 절대값 r1 = abs(-5) r2 = abs(5) print('r1 :', r1) print('r2 :', r2) # all() : 리스트에서 0이 포함됐는지 검사하는 함수 r3 = all([1,2,3,4,5]) r4 = all([1,2,3,4,0]) print('r3 :', r3) print('r4 :', r4) # any() : 리스트에서 하나라도 True 값이 있으면 전체 True, 모두 False 이면 전체 False r5 = any([0, '', None, False, 5]) # 2-7에서 확인할 수 있음. r6 = any([0, '', None, False, []]) # 모두 false 인 경우 print('r5 :', r5) print('r6 :', r6) # enumerate() : 반복문에서 인덱스값과 원소갑을 동시에 출력 people = ['김유신', '김춘추', '장보고'] for i, name in enumerate(people): print(i, name) # lambda() : def sum(a, b): return a+b add = lambda a,b:a+b r7 = sum(1, 2) r8 = add(1, 2) print('r7 :', r7) print('r8 :', r8)
import sys import re import argparse import random import time # !/usr/bin/env python pwins = 0 cwins = 0 play = True pchoice = None draw = 0 def main(): print("Welcome to Rock Paper Scissors") parser = argparse.ArgumentParser(description='asdfasdfasdfas') parser.add_argument('--selection', '-s', help='Choose "(R)ock", "(P)aper", or "(S)cissor" for single game') parser.add_argument('--bestof', '-b', help='Play a best of series, odd numbers only') args = parser.parse_args() if args.selection is not None and args.bestof is not None: print('You can only define one argument') elif args.bestof is not None and int(args.bestof) % 2 == 0: print('--bestof can only receive an odd number') elif args.selection is not None and re.fullmatch('[r|p|s]', str(args.selection), re.IGNORECASE) is None: print('--selection must match "(R)ock, (P)aper, or (S)cissor') else: gamemode(args) print('Thanks for Playing!') return 0 def gamemode(args): global play while play: if args.selection is None and args.bestof is None: select(args) if args.bestof is not None: bestofcontrol(args) if args.selection is not None: selectioncontrol(args) def select(args): global pwins, cwins, play, pchoice, draw pchoice = None if args.selection is None or draw == 1: if args.bestof is not None: pick = input("Enter selection: (R)ock, (P)aper, (S)cissors:") else: pick = input("Enter selection: (R)ock, (P)aper, (S)cissors, or (E)xit:") if args.selection is not None: pick = args.selection if re.fullmatch('[r|R]', pick): pchoice = 0 elif re.fullmatch('[p|P]', pick): pchoice = 1 elif re.fullmatch('[s|S]', pick): pchoice = 2 elif args.bestof is None and re.fullmatch('[e|E]', pick): print('Thanks for Playing!') sys.exit() else: print("Incorrect Option, try again") select(args) gameplay(args) def bestofcontrol(args): global play, cwins, pwins count = int(args.bestof) for x in range(0, count): if (count + 1) - x > pwins or (count + 1) - x > cwins: select(args) else: break if pwins > cwins: print("You won the Best of " + str(args.bestof)) else: print("The Computer won the best of " + str(args.bestof)) play = False def selectioncontrol(args): global play play = False select(args) def gameplay(args): global pchoice, pwins, cwins, draw cchoice = random.randint(0, 2) dictonary = {0: 'Rock', 1: 'Paper', 2: "Scissor"} timerprint() print('You chose ' + dictonary[pchoice] + '. The computer chose ' + dictonary[cchoice] + '.') if cchoice == pchoice: print("It's a draw. Please try again") draw = 1 select(args) elif pchoice == 0 and cchoice == 2: print("You win this round") pwins += 1 printscore(args) elif pchoice == 1 and cchoice == 0: print("You win this round") pwins += 1 printscore(args) elif pchoice == 2 and cchoice == 1: print("You win this round") pwins += 1 printscore(args) else: print('The computer wins this round.') cwins += 1 printscore(args) def timerprint(): print('Rock... ', end="", flush=True) time.sleep(1) print('Paper... ', end="", flush=True) time.sleep(1) print('Scissor... ', end="", flush=True) time.sleep(1) print('Shoot!') def printscore(args): if args.selection is None: print('Score [You: ' + str(pwins) + '; Computer: ' + str(cwins) + ']') if __name__ == "__main__": sys.exit(main())
""" Tic Tac Toe Player """ import math import copy from copy import deepcopy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who has the next turn on a board. """ cnt = 0 num = 0 if board == initial_state(): return X else: for i in range(3): for j in range(3): if (board[i][j] == 'X'): cnt = cnt+1 elif (board[i][j] == "O"): num = num+1 if cnt > num: return O elif not terminal(board) and cnt == num: return X else: return None def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ S = set() cnt = 0 for i in range(3): for j in range(3): if board[i][j] is EMPTY: S.add((i, j)) return S def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ i, j = action new_board = deepcopy(board) A = player(new_board) if new_board[i][j] is not EMPTY: raise Exception("Invalid action.") else: new_board[i][j] = A return new_board def winner(board): """ Returns the winner of the game, if there is one. """ if (board[0] == ["X", "X", "X"] or board[1] == ["X", "X", "X"] or board[2] == ["X", "X", "X"] or board[0][0] == board[1][0] == board[2][0] == "X" or board[0][1] == board[1][1] == board[2][1] == "X" or board[0][2] == board[1][2] == board[2][2] == "X" or board[0][0] == board[1][1] == board[2][2] == "X" or board[0][2] == board[1][1] == board[2][0] == "X"): return X if (board[0] == ["O", "O", "O"] or board[1] == ["O", "O", "O"] or board[2] == ["O", "O", "O"] or board[0][0] == board[1][0] == board[2][0] == "O" or board[0][1] == board[1][1] == board[2][1] == "O" or board[0][2] == board[1][2] == board[2][2] == "O" or board[0][0] == board[1][1] == board[2][2] == "O" or board[0][2] == board[1][1] == board[2][0] == "O"): return O else: return None def terminal(board): """ Returns True if game is over, False otherwise. """ if winner(board) == 'X' or winner(board) == 'O': return True else: for i in range(3): for j in range(3): if board[i][j] == EMPTY: return False return True def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ W = winner(board) if W == "X": utility_ = 1 elif W == "O": utility_ = -1 else: utility_ = 0 return utility_ def maxvalue(board): if terminal(board): return utility(board) v = float("-inf") for action in actions(board): v = max(v, minvalue(result(board, action))) return v def minvalue(board): if terminal(board): return utility(board) v = float("inf") for action in actions(board): v = min(v, maxvalue(result(board, action))) return v """ def minimax(board): p = player(board) # If empty board is provided as input, return corner. #new_state = None #states = actions(board) temporary = deepcopy(board) #new_score = 0 #old_score = 0 if p == X: #temporary[i][j] = "X" old_score=float("-inf") new_state = None for state in action(board): new_score = minvalue(result(board,state)) if new_score > old_score: old_score = new_score new_state = state elif p==O: #temporary[i][j] = "O" old_score=float("inf") new_state = None for state in actions(board): new_score1 = maxvalue(result(board,state)) if new_score1 < old_score: old_score = new_score1 new_state = state #board = temporary return new_state """ def minimax(board): #Returns the optimal action for the current player on the board. new_state = None p=player(board) #states = actions(board) #temporary = deepcopy(board) #new_score = 0 old_score = -9999 old_score1=9999 for state in actions(board): #i, j = state if p == X: #old_Score=float("-inf") #new_state = None new_score = minvalue(result(board,state)) if new_score > old_score: old_score = new_score new_state = state elif p==O: #old_score1=float("inf") #new_state = None new_score1 = maxvalue(result(board,state)) if new_score1 < old_score1: old_score1 = new_score1 new_state = state #board = temporary return new_state
import tkinter as tk from tkinter.constants import END # screen window = tk.Tk() window.title("Calculator") window.iconbitmap("calculator.ico") # place to type in enter = tk.Entry(window, width = 45, borderwidth = 10) enter.grid(row = 0, column = 0, columnspan = 3) # print number in thing function def button_clicked(number): get = enter.get() enter.delete(0, END) enter.insert(0, get + str(number)) def addition(): global num1 global math math = "add" num1 = enter.get() enter.delete(0, END) def subtract(): global num1 global math math = "subtract" num1 = enter.get() enter.delete(0, END) def multiply(): global num1 global math math = "multiply" num1 = enter.get() enter.delete(0, END) def divide(): global num1 global math math = "divide" num1 = enter.get() enter.delete(0, END) def equals(): num2 = enter.get() enter.delete(0, END) if math == "add": enter.insert(0, int(num1) + int(num2)) elif math == "subtract": enter.insert(0, int(num1) - int(num2)) elif math == "multiply": enter.insert(0, int(num1) * int(num2)) elif math == "divide": enter.insert(0, int(int(num1) / int(num2))) # buttons button1 = tk.Button(window, text = "1", padx=40, pady=20, command= lambda: button_clicked(1)) button2 = tk.Button(window, text = "2", padx=40, pady=20, command= lambda: button_clicked(2)) button3 = tk.Button(window, text = "3", padx=40, pady=20, command= lambda: button_clicked(3)) button4 = tk.Button(window, text = "4", padx=40, pady=20, command= lambda: button_clicked(4)) button5 = tk.Button(window, text = "5", padx=40, pady=20, command= lambda: button_clicked(5)) button6 = tk.Button(window, text = "6", padx=40, pady=20, command= lambda: button_clicked(6)) button7 = tk.Button(window, text = "7", padx=40, pady=20, command= lambda: button_clicked(7)) button8 = tk.Button(window, text = "8", padx=40, pady=20, command= lambda: button_clicked(8)) button9 = tk.Button(window, text = "9", padx=40, pady=20, command= lambda: button_clicked(9)) button0 = tk.Button(window, text = "0", padx=40, pady=20, command= lambda: button_clicked(0)) button_plus = tk.Button(window, text = "+", padx=40, pady=20, command = addition) button_sub = tk.Button(window, text = "-", padx=40, pady=20, command = subtract) button_multi = tk.Button(window, text = "*", padx=40, pady=20, command = multiply) button_div = tk.Button(window, text = "/", padx=40, pady=20, command = divide) button_equals = tk.Button(window, text = "=", padx=40, pady=20, command = equals) # place the button in window button1.grid(row=3, column=0) button2.grid(row=3, column=1) button3.grid(row=3, column=2) button4.grid(row=2, column=0) button5.grid(row=2, column=1) button6.grid(row=2, column=2) button7.grid(row=1, column=0) button8.grid(row=1, column=1) button9.grid(row=1, column=2) button_plus.grid(row=4, column=0) button0.grid(row=4, column=1) button_equals.grid(row=4, column=2) button_sub.grid(row=5, column=0) button_multi.grid(row=5, column=1) button_div.grid(row=5, column=2) window.mainloop()
''' Items held by players or found in rooms. Part of the text adventure game''' class Item(): ''' Items held by players or found in rooms. Base class for specialized item types.''' def __init__(self, name, description): self.name = name self.description = description def on_take(self): ''' Status message from taking an item ''' print(f'{self.name} taken!') def on_drop(self): ''' Status message for dropping an item ''' print(f'{self.name} dropped!')
from src.model.CollisionSide import CollisionSide def detect_collision_from_inside(collider, container): """ Detects if the `collider` has collided with the `container` from the inside :param collider: the collider :param container: the container :return: The side of the container where the collision happened """ if collider.right >= container.right: if collider.vertical_center() >= container.vertical_center(): return CollisionSide( CollisionSide.Primary.RIGHT, CollisionSide.Secondary.RIGHT_TOP ) else: return CollisionSide( CollisionSide.Primary.RIGHT, CollisionSide.Secondary.RIGHT_BOTTOM ) elif collider.left <= container.left: if collider.vertical_center() >= container.vertical_center(): return CollisionSide( CollisionSide.Primary.LEFT, CollisionSide.Secondary.LEFT_TOP ) else: return CollisionSide( CollisionSide.Primary.LEFT, CollisionSide.Secondary.LEFT_BOTTOM ) elif collider.top >= container.top: if collider.horizontal_center() >= container.horizontal_center(): return CollisionSide( CollisionSide.Primary.TOP, CollisionSide.Secondary.TOP_RIGHT ) else: return CollisionSide( CollisionSide.Primary.TOP, CollisionSide.Secondary.TOP_LEFT ) elif collider.bottom <= container.bottom: if collider.horizontal_center() >= container.horizontal_center(): return CollisionSide( CollisionSide.Primary.BOTTOM, CollisionSide.Secondary.BOTTOM_RIGHT ) else: return CollisionSide( CollisionSide.Primary.BOTTOM, CollisionSide.Secondary.BOTTOM_LEFT ) else: return None def detect_collision_from_outside(collider, obstacle): """ Detects if the `collider` has collided with the `obstacle` from the outside :param collider: the collider :param obstacle: the obstacle :return: The side of the obstacle where the collision happened """ if collider.delta_y < 0 and obstacle.top >= collider.bottom >= obstacle.vertical_center() \ and _is_within_obstacle_y_area(collider, obstacle): if collider.horizontal_center() >= obstacle.horizontal_center(): return CollisionSide( CollisionSide.Primary.TOP, CollisionSide.Secondary.TOP_RIGHT ) else: return CollisionSide( CollisionSide.Primary.TOP, CollisionSide.Secondary.TOP_LEFT ) elif collider.delta_y > 0 and obstacle.bottom <= collider.top <= obstacle.vertical_center() \ and _is_within_obstacle_y_area(collider, obstacle): if collider.horizontal_center() >= obstacle.horizontal_center(): return CollisionSide( CollisionSide.Primary.BOTTOM, CollisionSide.Secondary.BOTTOM_RIGHT ) else: return CollisionSide( CollisionSide.Primary.BOTTOM, CollisionSide.Secondary.BOTTOM_LEFT ) elif obstacle.left <= collider.right <= obstacle.right \ and _is_within_obstacle_x_area(collider, obstacle): if collider.vertical_center() >= obstacle.vertical_center(): return CollisionSide( CollisionSide.Primary.LEFT, CollisionSide.Secondary.LEFT_TOP ) else: return CollisionSide( CollisionSide.Primary.LEFT, CollisionSide.Secondary.LEFT_BOTTOM ) elif obstacle.right >= collider.left >= obstacle.left \ and _is_within_obstacle_x_area(collider, obstacle): if collider.vertical_center() >= obstacle.vertical_center(): return CollisionSide( CollisionSide.Primary.RIGHT, CollisionSide.Secondary.RIGHT_TOP ) else: return CollisionSide( CollisionSide.Primary.RIGHT, CollisionSide.Secondary.RIGHT_BOTTOM ) else: return None def _is_within_obstacle_y_area(collider, obstacle): """ If we imagine that the obstacle is a column that extends vertically from top of the screen to the bottom, this returns whether or not the collider is intersecting with said column :return: True if the collider is within the obstacle's y area, False otherwise """ return collider.right > obstacle.left and collider.left < obstacle.right def _is_within_obstacle_x_area(collider, obstacle): """ If we imagine that the obstacle is a row that extends horizontally from left of the screen to the right, this returns whether or not the collider is intersecting with said row :return: True if the collider is within the obstacle's x area, False otherwise """ return collider.top >= obstacle.bottom and collider.bottom <= obstacle.top
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # method 1: # hashmap # time complexity: O(m+n) # space complexity: O(m) or O(n) class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: s = set() while headA: s.add(headA) headA = headA.next while headB: if headB in s: return headB headB = headB.next # method 2: # time complexity: O(n) # space complexity: O(1) class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: pA = headA pB = headB while pA is not pB: pA = pA.next if pA else headB pB = pB.next if pB else headA # pA is pB only happens in two situations: # 1. pA and pB reach the intersection node # 2. pA and pB reand the end (None) return pA
import unittest from typing import List """ 思路: 当 p 循环时, min_price 为 p 之前的最小值 将移动的 p 选定为最大值 在每一次循环中, p-min_price 为在 p 点卖时的最大收益 再取所有 p-min_price 里的最大值 """ class Solution1: def maxProfit(self, prices: List[int]) -> int: min_price = float("inf") max_profit = 0 for p in prices: min_price = min(p, min_price) max_profit = max(max_profit, p - min_price) return max_profit class Solution2: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 m = n = 0 for i in range(1, len(prices)): m = max(0, m + prices[i] - prices[i - 1]) n = max(n, m) return n class Test(unittest.TestCase): def test(self): s = Solution2() data = [([7, 1, 5, 3, 6, 4], 5), ([7, 6, 4, 3, 1], 0)] for d in data: print(d) self.assertEqual(s.maxProfit(d[0]), d[1]) if __name__ == "__main__": unittest.main()
# https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes class Solution: def countPrimes(self, n: int) -> int: if n <= 2: return 0 isPrime = [True] * n isPrime[0] = isPrime[1] = False for i in range(2,n): if i * i >= n: break if isPrime[i] == False: continue for j in range(i*i, n, i): isPrime[j] = False return sum(isPrime)
def longest(s1, s2): s3 = s1 + s2 s3 = set(s3) s3 = list(s3) s3.sort() return "". join(s3)
import random def getList(dict): list = [] for key in dict.keys(): list.append(key) return list def initBackpack(): backpack = list() f = open("25.txt") # считываю грузоподъемность и вместимость firstline = f.readline() weight = firstline[0:firstline.index(" ")] capacity = firstline[firstline.index(" ") + 1:] f.close() # построчно считываю остаток файла f = open("25.txt") for line in f: if line == weight + ' ' + capacity: continue backpack.append(line.split()) f.close() return int(weight), float(capacity), backpack population_size = 200 weight, capacity, backpack = initBackpack() population = dict() # Возвращает один код, полученный жадным алгоритмом def Greedy(backpack): randomNum = random.randint(0, len(backpack)) current_backpack_weight = 0 current_backpack_capacity = 0 gen = dict() for i in range(0, len(backpack)): gen[i] = 0 for i in range(randomNum, len(backpack)): # Если помещается — берем if current_backpack_weight + int(backpack[i][0]) < weight and \ current_backpack_capacity + float(backpack[i][1]) < capacity: current_backpack_weight += int(backpack[i][0]) current_backpack_capacity += float(backpack[i][1]) gen[i] = 1 # Иначе берем сколько можно и выходим for i in range(0, len(backpack)): # Если помещается — берем if current_backpack_weight + int(backpack[i][0]) < weight and \ current_backpack_capacity + float(backpack[i][1]) < capacity: current_backpack_weight += int(backpack[i][0]) current_backpack_capacity += float(backpack[i][1]) gen[i] = 1 # Иначе берем сколько можно и выходим return gen # Создает популяцию def PopulationCreator(population): for i in range(0, population_size): population[i] = Greedy(backpack) PopulationCreator(population) # population_weight = dict() # for i in range(0, population_size): # population_weight[i] = 0 # Выбор 20% самых самых (по ценности) def CrossoverSelection(population_weight): for i in range(0, population_size): for j in range(0, 30): if population[i][j] == 1: population_weight[i] += int(backpack[j][2]) population_weight = dict(sorted(population_weight.items(), key=lambda kv: kv[1], reverse=True)[:int(200 * 0.2)]) return population_weight # population_weight = CrossoverSelection(population_weight) # Равномерное скрещивание через случайных родителей def Crossover(): parents_copy = population_weight.copy() parents = getList(parents_copy) newGens = list() while parents_copy: can_be_parent = getList(parents_copy) parent1 = 0 parent2 = 0 # Определение родителей while (parent1 == parent2): parent1 = random.choice(can_be_parent) parent2 = random.choice(can_be_parent) newGen = dict() for genxd in range(0, 2): # Создание маски для однородного скрещивания mask = dict() for i in range(0, 30): mask[i] = random.randint(1, 2) # Выбор гена с помощью маски for i in range(0, 30): if mask[i] == 1: newGen[i] = population[parent1][i] else: newGen[i] = population[parent2][i] newGens.append(newGen) del parents_copy[parent1] del parents_copy[parent2] dictOfGens = {i: newGens[i] for i in range(0, len(newGens))} return dictOfGens, parents # CrossoverRes, CurrentParents = Crossover() # Мутация инвертированием битов случайной особи def Mutation(CrossoverResult): MutationRes = CrossoverResult.copy() randX = random.randint(0, 39) for i in CrossoverResult[randX]: if MutationRes[randX][i] == 1: MutationRes[randX][i] = 0 else: MutationRes[randX][i] = 1 return MutationRes # MutationRes = Mutation(CrossoverRes) # Новая популяция через замену старых родителей потомками def NewPopulation(parents, MutationRes, population): for i in parents: counter = 0 population[i] = MutationRes[counter] counter += 1 return population # newPop = NewPopulation(CurrentParents, MutationRes, population) # Самый низкий по цене груз def cheapest(backpack): max_weight = 1000000 for i in range(0, len(backpack)): if int(backpack[i][2]) < max_weight: max_weight = int(backpack[i][2]) return max_weight # Возвращает лучшего из популяции def Best(newPopulation): forBestWeight = dict() for i in range(0, population_size): forBestWeight[i] = 0 for i in range(0, population_size): for j in range(0, 30): if population[i][j] == 1: forBestWeight[i] += int(backpack[j][2]) forBestWeight = dict(sorted(forBestWeight.items(), key=lambda kv: kv[1], reverse=True)[:1]) return (forBestWeight) # Список лучших особей для каждого нового поколения ListOfBest = list() # bestInPop = Best(newPop) # current_best = getList(bestInPop)[0] # ListOfBest.append(newPop[current_best]) # Возвращает ценность def getW(gen): sum = 0 for j in range(0, 30): if gen[j] == 1: sum += int(backpack[j][2]) return sum # Возвращает вес def getVES(gen): sum = 0 for j in range(0, 30): if gen[j] == 1: sum += int(backpack[j][0]) return sum # Возвращает объем def getP(gen): sum = 0 for j in range(0, 30): if gen[j] == 1: sum += float(backpack[j][1]) return sum # Проверка листа с лучшими def Check(ListofBest, cheap): listofSums = list() if len(ListOfBest) >= 2: for i in ListofBest: listofSums.append(getW(i)) for i in listofSums: for j in listofSums: if i != j: if abs(i - j) <= cheap: return 1 return 0 # Основной цикл, который активирует генетический алгоритм counter = 0 mostCh = cheapest(backpack) while (counter <= 500): print("Поколение: ", counter) population_weight = dict() for i in range(0, population_size): population_weight[i] = 0 population_weight = CrossoverSelection(population_weight) CrossoverRes, CurrentParents = Crossover() MutationRes = Mutation(CrossoverRes) newPop = NewPopulation(CurrentParents, MutationRes, population) bestInPop = Best(newPop) current_best = getList(bestInPop)[0] ListOfBest.append(newPop[current_best]) # Условие выхода из цикла - отличие в лучших меньше или равно самому менее ценному предмету if Check(ListOfBest, mostCh) == 1: break counter += 1 best = 0 bestID = 0 # Выбор лучшего результата из всех for i in range(0, len(ListOfBest)): if getW(ListOfBest[i]) > best and getP(ListOfBest[i]) < 12 and getVES(ListOfBest[i]) < 13000: best = getW(ListOfBest[i]) bestID = i bestIndivid = ListOfBest[i] print(bestID) print("Лучший индивид - ", bestIndivid) print("Ценность - ", best) sumOfValue = 0 sumOfW = 0 for i in range(0, 30): if bestIndivid[i] == 1: sumOfW += int(backpack[i][0]) sumOfValue += float(backpack[i][1]) print("Объем ", sumOfValue) print("Вес ", sumOfW)
#!/usr/local/bin python3 # encoding=utf-8 import os from PIL import Image # 图片最大减少的像素值 SQUARE_FIT_SIZE = 800 LOGO_FILE_NAME = 'catlogo.png' logo_im = Image.open(LOGO_FILE_NAME) logo_width, logo_height = logo_im.size print('logo image size:%s,%s' %(logo_width, logo_height)) os.makedirs('img_with_logo', exist_ok=True) for file_name in os.listdir('.'): if not (file_name.endswith('.png') or file_name.endswith('jpg')) or file_name == LOGO_FILE_NAME: continue im = Image.open(file_name) width, height = im.size print(width, height) if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE: if width > height: height = int(SQUARE_FIT_SIZE / width * height) width = SQUARE_FIT_SIZE else: width = int(width * SQUARE_FIT_SIZE / height) height = SQUARE_FIT_SIZE im = im.resize((width, height)) print('img:%s size, width:%s, height:%s' % (file_name, width, height)) im.paste(logo_im, (width - logo_width, height - logo_height), logo_im) im.save(os.path.join('img_with_logo', file_name))
texto = "curso de Python 3" txt1 = texto.capitalize() # Curso de python 3 txt2 = texto.swapcase() # CURSO DE pYTHON 3 txt3 = texto.upper() # CURSO DE PYTHON 3 txt4 = texto.lower() # curso de python 3 txt5 = texto.title() # Curso De Python 3 texto = "curso de Python 3, Python básico" txt6 = texto.replace("Python", "Java", 1) # curso de Java 3, Python básico # .replace(texto_reemplazado, reemplazo, num_reemplazos_opcional) minusculas = txt4.islower() mayusculas = txt3.isupper() texto = " curso de Python 3, Python básico " txt7 = texto.strip() # "curso de Python 3, Python básico" sin espacios en los extremos
from tkinter import * import sqlite3,sys def connection(): try: conn=sqlite3.connect("student.db") except: print("cannot connect to the database") return conn def verifier(): a=b=c=d=e=f=0 if not student_name.get(): t1.insert(END,"<>Student name is required<>\n") a=1 if not roll_no.get(): t1.insert(END,"<>Roll no is required<>\n") b=1 if not branch.get(): t1.insert(END,"<>Branch is required<>\n") c=1 if not phone.get(): t1.insert(END,"<>Phone number is requrired<>\n") d=1 if not father.get(): t1.insert(END,"<>Father name is required<>\n") e=1 if not address.get(): t1.insert(END,"<>Address is Required<>\n") f=1 if a==1 or b==1 or c==1 or d==1 or e==1 or f==1: return 1 else: return 0 def add_student(): ret=verifier() if ret==0: conn=connection() cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS STUDENTS(NAME TEXT,ROLL_NO INTEGER,BRANCH TEXT,PHONE_NO INTEGER,FATHER TEXT,ADDRESS TEXT)") cur.execute("insert into STUDENTS values(?,?,?,?,?,?)",(student_name.get(),int(roll_no.get()),branch.get(),int(phone.get()),father.get(),address.get())) conn.commit() conn.close() t1.insert(END,"ADDED SUCCESSFULLY\n") def view_student(): conn=connection() cur=conn.cursor() cur.execute("select * from STUDENTS") data=cur.fetchall() conn.close() for i in data: t1.insert(END,str(i)+"\n") def delete_student(): ret=verifier() if ret==0: conn=connection() cur=conn.cursor() cur.execute("DELETE FROM STUDENTS WHERE ROLL_NO=?",(int(roll_no.get()),)) conn.commit() conn.close() t1.insert(END,"SUCCESSFULLY DELETED THE USER\n") def update_student(): ret=verifier() if ret==0: conn=connection() cur=conn.cursor() cur.execute("UPDATE STUDENTS SET NAME=?,ROLL_NO=?,BRANCH=?,PHONE_NO=?,FATHER=?,ADDRESS=? where ROLL_NO=?",(student_name.get(),int(roll_no.get()),branch.get(),int(phone.get()),father.get(),address.get(),int(roll_no.get()))) conn.commit() conn.close() t1.insert(END,"UPDATED SUCCESSFULLY\n") def clse(): sys.exit() if __name__=="__main__": root=Tk() root.title("Student Management System") student_name=StringVar() roll_no=StringVar() branch=StringVar() phone=StringVar() father=StringVar() address=StringVar() label1=Label(root,text="Student name:") label1.place(x=0,y=0) label2=Label(root,text="Roll no:") label2.place(x=0,y=30) label3=Label(root,text="Branch:") label3.place(x=0,y=60) label4=Label(root,text="Phone Number:") label4.place(x=0,y=90) label5=Label(root,text="Father Name:") label5.place(x=0,y=120) label6=Label(root,text="Address:") label6.place(x=0,y=150) e1=Entry(root,textvariable=student_name) e1.place(x=100,y=0) e2=Entry(root,textvariable=roll_no) e2.place(x=100,y=30) e3=Entry(root,textvariable=branch) e3.place(x=100,y=60) e4=Entry(root,textvariable=phone) e4.place(x=100,y=90) e5=Entry(root,textvariable=father) e5.place(x=100,y=120) e6=Entry(root,textvariable=address) e6.place(x=100,y=150) t1=Text(root,width=80,height=20) t1.grid(row=10,column=1) b1=Button(root,text="ADD STUDENT",command=add_student,width=40) b1.grid(row=11,column=0) b2=Button(root,text="VIEW ALL STUDENTS",command=view_student,width=40) b2.grid(row=12,column=0) b3=Button(root,text="DELETE STUDENT",command=delete_student,width=40) b3.grid(row=13,column=0) b4=Button(root,text="UPDATE INFO",command=update_student,width=40) b4.grid(row=14,column=0) b5=Button(root,text="CLOSE",command=clse,width=40) b5.grid(row=15,column=0) root.mainloop()
import random from games.cards.Card import Card TYPES_CARD = ["Diamond", "Spade", "Heart", "Club"] ACE_FACES = {"Jack": 11, "Queen": 12, "King": 13, "ACE": 14} class DeckOfCards: def __init__(self): # init the deck with all cards self.deck = self.__build_deck() def __shuffle(self): # Shuffle the deck random.shuffle(self.deck) def deal_one(self): # Take one card from the top of the deck return self.deck.pop(0) def new_game(self): # Init the deck self.__init__() self.__shuffle() def show(self): # Print all card in deck all_cards = "" for card in self.deck: all_cards += str(card) + "\n" print(all_cards) def __build_deck(self): # First - create regular cards [(2,Diamond), (3,Diamond), (4,Diamond), (5,Diamond), (6,Diamond),....] regular_cards = [Card(num, suit) for suit in TYPES_CARD for num in range(2, 11)] # second - create regular cards [(Jack,Diamond), (Jack,Spade), (Jack,Heart), (Jack,Club), (Queen,Diamond),....] faces_cards = [Card(v, suit) for k, v in ACE_FACES.items() for suit in TYPES_CARD] return regular_cards + faces_cards
''' 2- Sílaba 'pe' Se pide desarrollar un programa en Python que permita cargar por teclado un texto completo en una variable de tipo cadena de caracteres. Se supone que el usuario cargará un punto para indicar el final del texto, y que cada palabra de ese texto está separada de las demás por un espacio en blanco. El programa debe: Determinar cuántas palabras tienen 3, 5 o 7 letras. Determinar la cantidad de palabras con más de tres letras, que tienen una vocal en la tercera letra. Determinar el porcentaje de palabras que tienen sólo una o dos vocales sobre el total de palabras del texto. Determinar la cantidad de palabras que contienen más de una vez la sílaba “pe”. Por ejemplo, si el texto ingresado es “Mi amigo pepe tiene un auto verde.”, la salida esperada es la siguiente: La cantidad de palabras con 3, 5 o 7 letras de longitud son: 3 La cantidad de palabras con mas de 3 letras y una vocal en la tercer letra son: 2 El porcentaje de palabras con 2 vocales sobre el total del texto es: 57.14% La cantidad de palabras con mas de una sílaba 'pe' es: 1 Utilizar funciones para el desarrollo del programa. ''' def porcentaje(rangoPalabras1o2Vocales, totalPalabras): porcentaje_primer_punto = ((rangoPalabras1o2Vocales * 100) / totalPalabras) return porcentaje_primer_punto def texto_a_ingresar(): texto = str(input("\nIngrese un texto con espacios entre palabras y finalizado por un punto: ")) while texto == '': print("\nERROR! No ha ingresado ningun texto. Vuelve a intentarlo!") texto = str(input("Ingrese un texto con espacios entre palabras y finalizado por un punto: ")) while (texto[-1] != '.'): texto = input("\nERROR!! El texto debe finalizar con un punto. vuelve a intentarlo: ") while texto == '': print("\nERROR! No ha ingresado ningun texto. Vuelve a intentarlo!") texto = str(input("Ingrese un texto con espacios entre palabras y finalizado por un punto: ")) return texto def main(): texto_a_analizar = texto_a_ingresar() cant_palabras_con_357 = 0 cantidad_palabras_3ra_letra_vocal = 0 cantidad_palabras_con_1o2_vocales = 0 cantidad_palabras_2omas_silabas_pe = 0 letra_ant = "" vocales = "aeiouAEIOUáéíóúÁÉÍÓÚ" cantidad_palabras_silaba_pe = 0 cantidad_letras_por_palabras_lista = [] cantidad_vocales_por_palabra_lista = [] cont_letras = 0 cantidad_palabras = 0 cantidad_vocales_por_palabra = 0 total_letras = 0 bandera_silaba_pe = True for letra in texto_a_analizar: total_letras = total_letras + 1 cont_letras = cont_letras + 1 if letra in vocales and letra != " " and letra != ".": cantidad_vocales_por_palabra = cantidad_vocales_por_palabra + 1 if letra_ant == "p" and letra == "e" and bandera_silaba_pe == True: cantidad_palabras_silaba_pe = cantidad_palabras_silaba_pe + 1 if cantidad_palabras_silaba_pe == 2 or cantidad_palabras_silaba_pe > 2: cantidad_palabras_2omas_silabas_pe = cantidad_palabras_2omas_silabas_pe + 1 bandera_silaba_pe = False cantidad_palabras_silaba_pe = 0 if letra == " " or letra == ".": cantidad_palabras = cantidad_palabras + 1 cantidad_letras_por_palabra = cont_letras - 1 cantidad_letras_por_palabras_lista.append(cantidad_letras_por_palabra) cantidad_vocales_por_palabra_lista.append(cantidad_vocales_por_palabra) cantidad_vocales_por_palabra = 0 cont_letras = 0 bandera_silaba_pe = True elif cont_letras == 4: if letra_ant in vocales: cantidad_palabras_3ra_letra_vocal = cantidad_palabras_3ra_letra_vocal + 1 letra_ant = letra for numero in cantidad_letras_por_palabras_lista: if numero == 3 or numero == 5 or numero == 7: cant_palabras_con_357 = cant_palabras_con_357 + 1 for numero in cantidad_vocales_por_palabra_lista: if numero == 2 or numero == 1: cantidad_palabras_con_1o2_vocales = cantidad_palabras_con_1o2_vocales + 1 print(f"La cantidad de palabras con 3, 5 o 7 letras de longitud son: {cant_palabras_con_357}") print(f"La cantidad de palabras con mas de 3 letras y una vocal en la tercer letrac " f"son: {cantidad_palabras_3ra_letra_vocal}") print(f"El porcentaje de palabras con 1 o 2 vocales sobre el total del texto " f"es: {porcentaje(cantidad_palabras_con_1o2_vocales, cantidad_palabras):.2f}% ") print(f"La cantidad de palabras con mas de una sílaba 'pe' " f"es: {cantidad_palabras_2omas_silabas_pe}") main()
''' 4. Punto en el plano Se pide realizar un programa que ingresando el valor x e y de un punto determine a que cuadrante pertenece en el sistemas de coordenadas. ''' x = float(input("\nIngrese el valor de 'x': ")) y = float(input("Ingrese el valor de 'y': ")) print() if x > 0 and y > 0: print(f"El punto correspondiente al valor '{x:.0f}' en 'x' y '{y:.0f}' en 'y' pertenecen al primer cuadrante" "del eje de coordenadas") elif x < 0 and y > 0: print(f"El punto correspondiente al valor '{x:.0f}' en 'x' y '{y:.0f}' en 'y' pertenecen al segundo cuadrante" "del eje de coordenadas") elif x < 0 and y < 0: print(f"El punto correspondiente al valor '{x:.0f}' en 'x' y '{y:.0f}' en 'y' pertenecen al tercer cuadrante" "del eje de coordenadas") elif x > 0 and y < 0: print(f"El punto correspondiente al valor '{x:.0f}' en 'x' y '{y:.0f}' en 'y' pertenecen al cuarto cuadrante" "del eje de coordenadas") else: print(f"El punto correspondiente al valor '{x:.0f}' en 'x' y '{y:.0f}' en 'y' no pertenecen a ningun" f" a ningun cuadrante porque ese punto se encuentra en el origen")
''' 7. Tirada de moneda Programar una tirada de una moneda (opciones: cara o cruz) aleatoriamente. Permitir que un jugador apueste a cara o cruz y luego informar si acertó o no con su apuesta. ''' import random print(">>> TIRADA DE MONEDA <<<\n") print("Digite '1' si apuesta 'CARA'\n" "Digite '2' si apuesta 'CRUZ\n") apuesta = input("Numero de apuesta: ") if apuesta == 1: apuesta = 'cara' else: apuesta = 'cruz' caras = ('cara', 'cruz') resultado_apuesta = (random.choice(caras)) print(f"\nEl jugador aposto por {apuesta}, el resultado de la apuesta fue: {resultado_apuesta}\n") if apuesta == resultado_apuesta: print("Bravo!!! Su apuesta ha sido Satisfactoria") elif apuesta != resultado_apuesta: print("Error!!! Su apuesta ha fallado")
''' 23- Cálculo presupuestario En un hospital existen 3 áreas de servicios: Urgencias, Pediatría y Traumatología. El presupuesto anual del hospital se reparte de la siguiente manera: Urgencias 50%, Pediatría 35% y Traumatología 15% Cargar por teclado el monto del presupuesto total del hospital, y calcular y mostrar el monto que recibirá cada área. ''' presupuesto_total_hospital=int(input(f"Ingrese el presupuesto total del hospital: ")) urgencias= (presupuesto_total_hospital*50)/100 pediatria= (presupuesto_total_hospital*35)/100 traumatologia= (presupuesto_total_hospital*15)/100 print(f"El área de Urgencias recibe ${urgencias} del presupuesto anual del hospital") print(f"El área de Pediatría recibe ${pediatria} del presupuesto anual del hospital") print(f"El área de Traumatología recibe ${traumatologia} del presupuesto anual del hospital")
class Solution: def search(self, nums, target): n = len(nums) if (n == 0): return False end = n - 1 start = 0 while (start <= end): mid = (start + end)//2 if (nums[mid] == target): return True if (not self.isBinarySearchHelpful(nums, start, nums[mid])): start+=1 continue #which array does pivot belong to. pivotArray = self.existsInFirst(nums, start, nums[mid]) #which array does target belong to. targetArray = self.existsInFirst(nums, start, target) if (pivotArray ^ targetArray): # pivot and target exist in different sorted arrays, recall that xor is true when both operands are distinct if (pivotArray): start = mid + 1 #pivot in the first, target in the second else: end = mid - 1 #target in the first, pivot in the second else: #If pivot and target exist in same sorted array if (nums[mid] < target): start = mid + 1 else: end = mid - 1 return False #returns true if we can reduce the binary_search space in current binary binary_search space def isBinarySearchHelpful(self, arr, start, element): return arr[start] != element #returns true if element exists in first array, false if it exists in second def existsInFirst(self, arr, start, element): return arr[start] <= element
# """ # This is ArrayReader's API interface. # You should not implement it, or speculate about its implementation # """ #class ArrayReader(object): # def get(self, index): # """ # :type index: int # :rtype int # """ #binary_search in array of unknown length class Solution(object): def bsearch(self, reader, start, end, target): while start <= end: mid = (start+end)//2 if reader.get(mid) == target: return mid elif target < reader.get(mid): end = mid - 1 else: start = mid + 1 if reader.get(start) == 2147483647: return "max" return -1 def search(self, reader, target): start = 0 end = 2 index = -1 while index == -1: index = self.bsearch(reader, start, end, target) if index == "max": return -1 else: start = end+1 end = end * 2 return index
class Solution(object): ''' find shortest sub-array with degree same as original array. Degree =maximum frequency of any character/number ''' def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ countmap = {} left = {} # maintain the left occurence of any character right = {} #maintain index of rightmost occurence of any character for i, n in enumerate(nums): if n not in left: left[n] = i # this will be leftmost occurence right[n] = i # this will be the rightmost occurence if n in countmap: countmap[n] += 1 else: countmap[n] = 1 degree = max(countmap.values()) ans = len(nums) for x in countmap: if countmap[x] == degree: ans = min(ans, right[x] - left[x] + 1) return ans
#NOTE there is NO equivalent of TreeMap (sorted keys dictionary) in Python #There is collections.OrderedDict which stores keys in the order which elements were added to the dict #>>> a = OrderedDict() # >>> a[4] = 1 # >>> a # OrderedDict([(4, 1)]) # >>> a[6] = 2 # >>> print(a.keys()) # [4, 6] # >>> print(a.values()) class Solution: def verticalOrder(self, root: TreeNode) -> List[List[int]]: hashmap = collections.defaultdict(list) #map --> column_no : [list of nodes] queue = [] if root is None: return [] queue.append((root,0)) #Adding root's level = 0 minlevel = 0 #for avoiding sorting the hashmap #can use treemap in java maxlevel = 0 while queue: curLen = len(queue) for i in range(curLen): cur,level = queue.pop(0) if level < minlevel: minlevel = level if level > maxlevel: maxlevel = level hashmap[level].append(cur.val) if cur.left: queue.append((cur.left, level-1)) if cur.right: queue.append((cur.right, level+1)) res = [] for i in range(minlevel,maxlevel+1): if i in hashmap: res.append(hashmap[i]) return res
''' There are several other data structures, like balanced trees and hash tables, which give us the possibility to binary_search for a word in a dataset of strings. Then why do we need trie? Although hash table has O(1) time complexity for looking for a key, it is not efficient in the following operations : 1. Finding all keys with a common prefix. 2. Enumerating a dataset of strings in lexicographical order. Another reason why trie outperforms hash table, is that as hash table increases in size, there are lots of hash collisions and the binary_search time complexity could deteriorate to O(n), where n is the number of keys inserted. Trie could use less space compared to Hash Table when storing many keys with the same prefix. In this case using trie has only O(m) time complexity, where m is the key length. Searching for a key in a balanced tree costs O(mlogn) time complexity. ''' class Trie: def __init__(self): """ Initialize your data structure here. """ self.trie = {} def insert(self, word): """ Inserts a word into the trie. """ temp = self.trie for w in word: if w in temp: temp=temp[w] else: temp[w]={} temp=temp[w] temp['#'] = True print(self.trie) print (temp) def search(self, word): """ Returns if the word is in the trie. """ temp = self.trie for w in word: if w in temp: temp = temp[w] else: return False return '#' in temp def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. """ temp = self.trie for w in prefix: if w in temp: temp = temp[w] else: return False return True tr = Trie() tr.insert("abc") tr.insert("cde")
class Trie: def __init__(self): self.key = None self.chars = [None]*26 def insert(trie, word): #max depth is 26 cur = trie for w in word: key = ord(w) - ord('a') #each level is for english alphabets in order a = 0 to z=25 if cur.chars[key] is None: cur.chars[key] = Trie() cur = cur.chars[key] cur.key = word #store the word Itself as a key in the leaf def preOrder(trie, words): if trie is None: return for i in range(26): if trie.chars[i]: if trie.chars[i].key: #if leaf node append to results words.append(trie.chars[i].key) preOrder(trie.chars[i], words) words = ["abd", "acg", "aa", "a", "bce", "zz", "aab"] trie = Trie() for word in words: insert(trie, word) res = [] preOrder(trie, res) print (res)
class RandomizedSet: def __init__(self): self.indexmap = {} #map of value to index (keys are sets element) key -> index of list self.elements = [] #list of elements All set keys are added here too """ Initialize your data structure here. """ def insert(self, val): if val in self.indexmap: return False else: self.indexmap[val] = len(self.elements) self.elements.append(val) return True def remove(self, val): if val not in self.indexmap: return False index = self.indexmap[val] last = self.elements[-1] self.elements[index] = last #put last element in deleted place self.indexmap[last] = index #update index of last element self.elements.pop() #remove last element del self.indexmap[val] return True def getRandom(self): return choice(self.elements) # r = random.randint(0,len(self.elements)-1) # return self.elements[r] """ Get a random element from the set. """ # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
class Solution(object): def search(self, nums, target): start = 0 end = len(nums)-1 while start <= end: #have to check until start==end mid = (start + end)//2 if nums[mid] == target: return mid elif target < nums[mid]: end = mid-1 #end = mid -1 as we are done checking mid or else will lead to inf loop else: start = mid+1 #mid +1 as we are done checkin mid return -1
# -*- coding: utf-8 -*- """ Created on Mon Oct 19 10:15:01 2020 @author: kevin """ import gauss as gs import auxclass as aux import sys print("\n-------------Calculadora de Sistemas de Ecuaciones MxN-------------\nIngresa el numero de Ecuaciones: ") m = int(input())#Ecuaciones print("Ingresa el numero de incognitas: ") n = int(input())#Incognitas l= aux.strlist(m)#inicializa la lista l = aux.add(l,m,n)#Lista de Listas que contiene las ecuaciones print("-----------Matriz del Sistema "+str(m)+"x"+str(n)+"-----------") aux.printMatrix(l,m)#Imprimir la matriz #Diagonalizacion y Teorema de Rouche-Frobenius l = gs.Diagonalize(l,m,n) print("-----------Matriz de Coeficientes Diagonalizada-----------") aux.printMatrixCoe(l,m,n) print("-----------Matriz Aumentada Diagonalizada-----------") aux.printMatrix(l,m) rC = gs.rango(l,m,n-1)#Rango de la matriz de coeficientes rA = gs.rango(l,m,n)#Rango de la matriz aumentada sol = gs.solution(rC,rA,n)#solucion string print("\nR(A) =",rC) print("R(A*) =",rA) print("n =",n) print("\nPor lo tanto el Sistema tiene: ", sol, "\n") if(gs.isHomogeneous(l,m,n)):#Caso particular print("Es Homogenea\n") if(sol == 'Ninguna Solución'): sys.exit(0)#Finaliza el programa """ #Reduccion de Gauss-Jordan print("-----------Matriz por Llevar a su forma escalonada-----------") l = gs.compact(l,m,n) m = len(l) aux.printMatrix(l,m) #Resultado """
from collections import Iterator from copy import deepcopy class LinkedListIterator(Iterator): def __init__(self, linked_list): self.list = linked_list def __next__(self): if self.list is END: raise StopIteration t = self.list.head self.list = self.list.tail return t class LinkedList: """ Immutable linked list with unique elements""" __slots__ = ('head', 'tail', 'size') def __init__(self, head, tail, size): self.head = head self.tail = tail self.size = size def __len__(self): return self.size def append(self, other): if other in self: return self return LinkedList(other, self, self.size + 1) def __iter__(self): return LinkedListIterator(self) def __repr__(self): return 'i[' + ', '.join(map(lambda x: repr(x), self)) + ']' def __contains__(self, item): return item in set(self) END = LinkedList(None, None, 0) def cons(elem, linked_list): return linked_list.append(elem) def nil(): return END
def _reachable_tiles(self, convoy, path, reachable): if self.is_fleet: return _reachable_tiles() def _reachable_tiles_base(self, convoy, path, reachable): """ Compute all the reachable tiles for a given unit. This take into account all the adjacent land tiles and all the land tiles accessible through convoys """ # reachable = set() # For each tile check if they are accessible for tile in self.loc.neighbours: if tile.is_water: unit = self.board.get_unit_at(tile) if unit is not None and unit.is_fleet and tile not in path: # There is a fleet on the tile so we might be able to convoy though fleet chains _reachable_tiles(unit, convoy_=True, path=path.append(self.loc), reachable=reachable) else: if tile not in path: if tile not in reachable: reachable[tile] = set() reachable[tile].add(path) def _reachable_tiles(self, convoy_, path, reachable): """ fleets can reach every tile that are adjacent """ if not convoy_: for tile in self.loc.neighbours: # for a tile to be reachable by a fleet it needs to be either water # or a land tile with a common sea between current loc and dest loc has_common_sea = self.loc in tile.seas or len(self.loc.seas.intersection(tile.seas)) > 0 if (tile.is_water or has_common_sea) and tile not in path: if tile not in reachable: reachable[tile] = set() reachable[tile].add(path) return reachable _reachable_tiles_base(self, convoy_=True, path=path.append(self.loc), reachable=reachable)
import matplotlib.pyplot as plt import numpy as np def exhaustive_search(a, b, inc): ran = np.arange(a, b, inc) # print(ran) y = func(ran.__array__()) # print(y) plt.plot(ran, y) i: int for i in range(1, len(y) - 1): if (y[i - 1] > y[i] and y[i + 1] > y[i]) or (y[i] > y[i - 1] and y[i] > y[i + 1]): print("Approximate local optima is ", ran[i]) plt.plot(ran[0:i], y[0:i], 'r+') break elif y[-1] > y[-2] and i == len(y) - 2: # print("local optima is ", y[-1]) print("local minimum is ", a) print("local maximum is ", b) plt.plot(ran[0:i], y[0:i]) break elif y[-1] < y[-2] and i == len(y) - 2: # print("local optima is ",y[0]) print("local minimum is ", b) print("local maximum is ", a) plt.plot(ran[0:i], y[0:i]) break plt.show() def func(x: list) -> list: arr = [] for i in x: try: arr.append(i ** 2 + 54 / i) except ZeroDivisionError: arr.append(np.Inf) return arr def fun(x: float) -> float: try: y = ((x ** 2) + 54 / x) except ZeroDivisionError: y = np.Inf return y if __name__ == "__main__": print("Remember to update function") a = int(input("enter the base range\t")) b = int(input("enter the upper range\t")) c = float(input("Enter the increment value\t")) exhaustive_search(a, b, c)
class Song(object): def __init__(self, rowId, title, artist): self.rowId = rowId self.title = title self.artist = artist def __str__(self): return "({0}, {1} - {2})".format(self.rowId, self.artist, self.title)
import sqlite3 def create_database(db_path): connection = sqlite3.connect(db_path) cursor = connection.cursor() create_person_table = '{}{}{}{}{}{}{}'.format( 'CREATE TABLE IF NOT EXISTS', ' person(id INTEGER PRIMARY KEY,', ' first_name text NOT NULL,', ' lastname text NOT NULL,', ' new_birthday text NOT NULL,', ' age text NOT NULL,', ' message text NOT NULL);' ) cursor.execute(create_person_table) connection.commit() connection.close() print('Database successfully created and populated with data!')
# Getting Started with Raspberry Pi Ch 4 Example 6 import pygame from pygame.locals import * import RPi.GPIO as GPIO import time def setup_leds(): GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.OUT) GPIO.setup(24, GPIO.OUT) GPIO.setup(25, GPIO.OUT) def output_to_led(value,leds): #simple 3 LED case #Option: generalise this! bucket=value % (2**leds) binary_string=bin(bucket)[2:].zfill(3) led0=int(binary_string[2]) led1=int(binary_string[1]) led2=int(binary_string[0]) print value, bucket, led2, led1, led0 # Output our led bit values to real LEDS if led0: #This means if led value is not zero GPIO.output(23, GPIO.HIGH) if led1: #This means if led value is not zero GPIO.output(24, GPIO.HIGH) if led2: #This means if led value is not zero GPIO.output(25, GPIO.HIGH) #Hold the LEDs up for 0.7 seconds time.sleep(0.2) #Now drop all the LEDs and hold for 0.5s and then we should loop back here after hold GPIO.output(23, GPIO.LOW) GPIO.output(24, GPIO.LOW) GPIO.output(25, GPIO.LOW) time.sleep(0.1) def fetch_and_display_mouse_input(): width, height = 320, 320 radius = 0 mouseX, mouseY = 0, 0 pygame.init() window = pygame.display.set_mode((width, height)) window.fill(pygame.Color(255, 255, 255)) fps = pygame.time.Clock() myloop=True myloopctr=0 while myloop: for event in pygame.event.get(): if event.type == MOUSEMOTION: mouseX, mouseY = event.pos output_to_led(mouseX+mouseY,3) pygame.display.update() fps.tick(30) myloopctr+=1 if myloopctr > 100: myloop=False #####MAIN ###### setup_leds() fetch_and_display_mouse_input()
#!/usrs/bin/env python3 ''' Task : write a script to take a list as a parameter from a user and return its reversed version as a result. Example: [2, 3, 4, 5] if pass then result will be [5, 4, 3, 2] ''' #1Solution, Let's write a function def reverse_items_list(items_list): __reversed_items_list = [] __original_items_list = items_list __reversed_index = len(items_list) - 1 for index, item in enumerate(items_list): __reversed_items_list.append(items_list[__reversed_index-index]) return __reversed_items_list #Now the function is defined, let's define a function to prompt user to pass a list def prompt_user_to_pass_items_list(): items_list = input("Enter Numbers only: " ) items_list = list(items_list) print(reverse_items_list(items_list)) if __name__ == "__main__": prompt_user_to_pass_items_list()
''' Problem: Given a 32-bit signed integer, reverse digits of an integer. Example: Input: 123 Output: 321 Solution: (Slow) -Convert to string, reverse and convert to int ''' class Solution: def reverse(self, x: int) -> int: if (x < 0): s = str(-x) num = -int(s[::-1]) if (abs(num) > (2 ** 31 -1)): return 0 return num else: s = str(x) num = int(s[::-1]) if (num > (2 ** 31 -1)): return 0 return num
''' validation for email ''' import re def check_valid_email(email): if (re.match("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$", email) != None): return email return "colud you please provide correct email " email = "abc@gmail.com" output = check_valid_email(email) print(output)