text
stringlengths
37
1.41M
''' For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given an integer, convert it to a roman numeral. ''' class Solution: def f(self, n): d = [["I", 1], ["IV", 4], ["V", 5], ["IX", 9], ['X', 10], ['XL', 40], ['L', 50], ['XC', 90], ['C', 100], ['CD', 400], ['D', 500], ['CM', 900], ['M', 1000]] res = '' for s, val in reversed(d): if n // val: count = n // val res += (s * count) n = n % val print(res) return res
''' We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.) A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Return a list of all uncommon words. You may return the list in any order. ''' class Solution: def uncommonFromSentences(self, A: str, B: str) -> List[str]: a = (A.split(' ')) b = (B.split(' ')) ad = dict() bd = dict() for x in a: if x not in ad.keys(): ad[x] = 1 else: ad[x]+=1 for x in b: if x not in bd.keys(): bd[x] = 1 else: bd[x]+=1 res = [] for x in a: if x not in b and ad[x] == 1: res.append(x) for x in b: if x not in a and bd[x] == 1: res.append(x) print(res) return res
''' Given an array of distinct integers arr, where arr is sorted in ascending order, return the smallest index i that satisfies arr[i] == i. If there is no such index, return -1. ''' class Solution: def fixedPoint(self, arr: List[int]) -> int: for i in range(len(arr)): if arr[i] == i: return i return -1
''' You are given a 0-indexed integer array nums. Swaps of adjacent elements are able to be performed on nums. A valid array meets the following conditions: The largest element (any of the largest elements if there are multiple) is at the rightmost position in the array. The smallest element (any of the smallest elements if there are multiple) is at the leftmost position in the array. Return the minimum swaps required to make nums a valid array. ''' ''' Explanation When talking about swap, it's very likely to run into Greedy algorithm. In this case, we want to move the minimum to the leftmost side then find how many swaps need to move maximum to the rightmost side. See below comment for more explanation ''' class Solution: def minimumSwaps(self, nums: List[int]) -> int: mi = min(nums) # find minimum idx1 = nums.index(mi) # locate the first mi from the left side nums = [nums[idx1]] + nums[:idx1] + nums[idx1+1:] # make the swaps & update `nums` mx = max(nums) # find maximum idx2 = nums[::-1].index(mx) # locate the first mx from the right side return idx1 + idx2 # return total swaps needed -------------------------------------------------------------------------------------------------------------- class Solution: def minimumSwaps(self, nums: List[int]) -> int: min_value = max_index = nums[0] min_index = max_value = 0 for i, n in enumerate(nums): if n < min_value: min_value = n min_index = i if n >= max_value: max_value = n max_index = i return min_index + len(nums) - 1 - max_index - (min_index > max_index)
''' Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally. ''' class Solution: def winnerSquareGame(self, n: int) -> bool: dp = [False] * (n + 1) squares = [] curSquare = 1 for i in range(1, n + 1): if i == curSquare * curSquare: squares.append(i) curSquare += 1 dp[i] = True else: for square in squares: if not dp[i - square]: dp[i] = True break return dp[n] ---------------------------------------------- class Solution: def winnerSquareGame(self, n: int) -> bool: dp = [False]*(n+1) for i in range(1,n+1): j = 1 while j*j <= i: dp[i] |= not dp[i-j*j] j+=1 return dp[n]
''' Given a two-dimensional integer list intervals of the form [start, end] representing intervals (inclusive), return their intersection, that is, the interval that lies within all of the given intervals. You can assume that the intersection will be non-empty. ''' class Solution: def solve(self, intervals): first = max([item[0] for item in intervals]) second = min([item[1] for item in intervals]) return [first,second]
''' Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: dummy = ListNode(0,head) groupPrev = dummy while True: kth = self.getKth(groupPrev,k) if not kth: break groupNext = kth.next #reversing the group prev,cur = kth.next, groupPrev.next while cur!= groupNext: tmp = cur.next cur.next= prev prev = cur cur = tmp tmp = groupPrev.next groupPrev.next = kth groupPrev = tmp return dummy.next def getKth(self, cur,k): while cur and k > 0: cur = cur.next k = k-1 return cur
''' Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. ''' class Solution: # Why slots: https://docs.python.org/3/reference/datamodel.html#slots # TLDR: 1. faster attribute access. 2. space savings in memory. # For letcode problems this can save ~ 0.1MB of memory <insert is something meme> __slots__ = () def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: # Init return array in which, we'll store justified lines lines = [] # current line width width = 0 # current line words line = [] for word in words: # Gather as many words that will fit under maxWidth restrictions. # Line length is a sum of: # 1) Current word length # 2) Sum of words already in the current line # 3) Number of spaces (each word needs to be separated by at least one space) if (len(word) + width + len(line)) <= maxWidth: width += len(word) line.append(word) continue # If the current line only contains one word, fill the remaining string with spaces. if len(line) == 1: # Use the format function to fill the remaining string with spaces easily and readable. # For letcode police, yes you could do something like: # line = " ".join(line) # line += " " * (maxWidth - len(line)) # lines.append(line) # to be more "raw", but I see no point in that. lines.append( "{0: <{width}}".format( " ".join(line), width=maxWidth) ) else: # Else calculate how many common spaces and extra spaces are there for the current line. # Example: # line = ['a', 'computer.', 'Art', 'is'] # width left in line equals to: maxWidth - width: 20 - 15 = 5 # len(line) - 1 because to the last word, we aren't adding any spaces # Now divmod will give us how many spaces are for all words and how many extra to distribute. # divmod(5, 3) = 1, 2 # This means there should be one common space for each word, and for the first two, add one extra space. space, extra = divmod( maxWidth - width, len(line) - 1 ) i = 0 # Distribute extra spaces first # There cannot be a case where extra spaces count is greater or equal to number words in the current line. while extra > 0: line[i] += " " extra -= 1 i += 1 # Join line array into a string by common spaces, and append to justified lines. lines.append( (" " * space).join(line) ) # Create new line array with the current word in iteration, and reset current line width as well. line = [word] width = len(word) # Last but not least format last line to be left-justified with no extra space inserted between words. # No matter the input, there always be the last line at the end of for loop, which makes things even easier considering the requirement. lines.append( "{0: <{width}}".format(" ".join(line), width=maxWidth) ) return lines
''' We define str = [s, n] as the string str which consists of the string s concatenated n times. For example, str == ["abc", 3] =="abcabcabc". We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, s1 = "abc" can be obtained from s2 = "abdbec" based on our definition by removing the bolded underlined characters. You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2]. Return the maximum integer m such that str = [str2, m] can be obtained from str1. ''' This is a difficult problem (for me anyway). I kept thinking that there had to be a trick Firstly, if there is any character in s2 that is not in s1 then we can never obtain [S2, M] from S1. Then I step through s1, incrementing an index pointer in s2 whenever characters match : When I reach the end of s2, go back to the start and increment the counter s2_reps that tells me how many complete copies of s2 I have used. Similarly when I reach the end of s1, go back to the start and increment s1_reps. At then end of s1 record in a dictionary a mapping from the next index to be matched in s2 as key and the pair of (s1_reps, s2_reps) as value. If the key has been seen before then we are in a loop, every time we go through s1 we are at the same position in s2. So we can break from stepping through the strings and work out how many loops we can go through for all of [s1, n1]. (Potentially we never find a loop and have reached n1 repetitions of s1 already so can just return s2_reps // n2) Having found how many repetitions of s1 and s2 there are in a loop, we use as many loops as possible to go through n1 copies of s1. Bear in mind that there may be some repetitions before the loop is entered. Then all that remains is if we have not seen n1 copies of s1 after the final loop, step through the strings again until we reach n1. I suspect the code below could be made a little more efficient. Comments welcome! class Solution(object): def getMaxRepetitions(self, s1, n1, s2, n2): if any(c for c in set(s2) if c not in set(s1)): # early return if impossible return 0 s2_index_to_reps = {0 : (0, 0)} # mapping from index in s2 to numbers of repetitions of s1 and s2 i, j = 0, 0 s1_reps, s2_reps = 0, 0 while s1_reps < n1: if s1[i] == s2[j]: j += 1 # move s2 pointer if chars match i += 1 if j == len(s2): j = 0 s2_reps += 1 if i == len(s1): i = 0 s1_reps += 1 if j in s2_index_to_reps: # loop found, same index in s2 as seen before break s2_index_to_reps[j] = (s1_reps, s2_reps) if s1_reps == n1: # already used n1 copies of s1 return s2_reps // n2 initial_s1_reps, initial_s2_reps = s2_index_to_reps[j] # repetitions before loop starts loop_s1_reps = s1_reps - initial_s1_reps loop_s2_reps = s2_reps - initial_s2_reps loops = (n1 - initial_s1_reps) // loop_s1_reps s2_reps = initial_s2_reps + loops * loop_s2_reps s1_reps = initial_s1_reps + loops * loop_s1_reps while s1_reps < n1: # if loop does not end with n1 copies of s1, keep going if s1[i] == s2[j]: j += 1 i += 1 if i == len(s1): i = 0 s1_reps += 1 if j == len(s2): j = 0 s2_reps += 1 return s2_reps // n2 ---------------------------------------------------------------------- class Solution: def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int: dp = [] for i in range(len(s2)): start = i cnt = 0 for j in range(len(s1)): if s1[j] == s2[start]: start += 1 if start == len(s2): start = 0 cnt += 1 dp.append((start,cnt)) res = 0 next = 0 for _ in range(n1): res += dp[next][1] next = dp[next][0] return res // n2
''' You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Each element belongs to exactly one pair. The elements present in a pair are equal. Return true if nums can be divided into n pairs, otherwise return false. ''' class Solution: def divideArray(self, nums: List[int]) -> bool: n = nums n.sort() pairs = len(n)//2 i = 0 while i < len(n)-1: if n[i] != n[i+1]: return False i+=2 return True class Solution: def divideArray(self, nums: List[int]) -> bool: d = dict() for n in nums: if n not in d: d[n] = 1 else: d[n] +=1 d = d.values() for v in d: if v%2 != 0: return False return True
''' You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums, and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted. ''' def largestSumOfAverages(self, nums: List[int], k: int) -> float: n = len(nums) pre = [0] for i in nums: pre.append(pre[-1] + i) def solve(i, k): if(k == 1): return sum(nums[i:])/(n-i) if(n-i < k): return -1 if((i, k) in d): return d[(i, k)] temp = 0 for j in range(i+1, n): temp = max(temp, solve(j, k-1)+(pre[j]-pre[i])/(j-i)) d[(i, k)] = temp return temp d = dict() return solve(0, k) -------------------------------------------------------------------------------------------------------------------------- The idea of this question is very straightforward. There are 2 things to consider: state and option. State is the variable, what might change in the question, in this case, the length of the array & the number of partition Option is what we can decide. In this case, we can decide whether cut the array or not at a certain position, and we want to optimize the option, aka we need to find the best result from cut or not cut. DP array is defined as follow: dp[i][j] states what is the maximal result given that the first i+1 character in the array and j cuts. Here is the process: Base case: when i = 0, j =0, means given the first char, maximum of 0 cut is allowed, dp[i][j] = A[0], piece of cake. Base nonpermissible case: when i = 0, j = n , n in [1,2,3...], means given the first char, maximum of n cut is allowed, dp[i][j] = 0 State Transition: for any dp[i][j] that are not classified as base cases, we want to find the maximum partition, which is the maximum of dp[k][j-1]+avg(A[k+1:i+1])) such that k in the range of 0 to i-1. (Intuitively, we don't care what the partition from 0 to k is, we leave that as to our subproblems) Here is the code written in Python: class Solution: def largestSumOfAverages(self, A: List[int], K: int) -> float: def avg(array): return sum(array) / len(array) dp = [[0 for _ in range(K)] for _ in range(len(A))] dp[0][0] = A[0] for i in range(len(A)): for j in range(K): # if i == 0 and j != 0: # continue if j == 0: dp[i][j] = avg(A[:i+1]) else: for k in range(i): dp[i][j] = max(dp[i][j],dp[k][j-1]+avg(A[k+1:i+1])) return dp[len(A)-1][K-1] ---------------------------------------------------------------------------------------------------------- def dp(A, K): dp = [[0] * len(A) for _ in range(K)] for j in range(len(A)): dp[0][j] = mean(A[:j + 1]) for k in range(1, K): for j in range(k, len(A)): for i in range(j): dp[k][j] = max(dp[k][j], dp[k - 1][i] + mean(A[i + 1:j + 1])) return dp[-1][-1] return dp(A, K)
''' Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. ''' class Solution: def minInsertions(self, S: str) -> int: L = len(S) DP = [[0 for _ in range(L+1)] for _ in range(L+1)] for i,j in itertools.product(range(L),range(L)): DP[i+1][j+1] = DP[i][j] + 1 if S[i] == S[L-1-j] else max(DP[i][j+1],DP[i+1][j]) return L - DP[-1][-1] -------------------------------------------------------------------------------------------------------------------------------------------- Define dp(s) as the minimum number of steps to make s palindrome. We'll get the recursion below: dp(s) = 0 if s == s[::-1] dp(s) = dp(s[1:-1]) if s[0] == s[-1] dp(s) = 1 + min(dp(s[1:]), dp(s[:-1])) otherwise from functools import lru_cache class Solution: def minInsertions(self, s: str) -> int: @lru_cache(None) def dp(s): if s == s[::-1]: return 0 elif s[0] == s[-1]: return dp(s[1:-1]) else: return 1 + min(dp(s[1:]), dp(s[:-1])) return dp(s)
''' You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique. ''' class Solution: def removeDuplicates(self, s: str) -> str: s = list(s) stack = [] for c in s: # if the prev charac is same as before, we need to pop it, the current same char is iterated over as usual if stack and stack[-1] == c: stack.pop() else: stack.append(c) res = ''.join(stack) print(res) return res
''' You are given an integer array nums. In one move, you can choose one element of nums and change it to any value. Return the minimum difference between the largest and smallest value of nums after performing at most three moves. ''' If the size <= 4, then just delete all the elements and either no or one element would be left giving the answer 0. else sort the array there are 4 possibilities now:- delete 3 elements from left and none from right delete 2 elements from left and one from right and so on.. now just print the minima. class Solution: def minDifference(self, nums: List[int]) -> int: if len(nums) <= 4: return 0 nums.sort() return min(nums[-1] - nums[3], nums[-2] - nums[2], nums[-3] - nums[1], nums[-4] - nums[0]) --------------------------------------------------------------------------------------------------------------- class Solution: def minDifference(self, nums: List[int]) -> int: n = len(nums) # If nums are less than 3 all can be replace, # so min diff will be 0, which is default condition if n > 3: # Init min difference min_diff = float("inf") # sort the array nums = sorted(nums) # Get the window size, this indicates, if we # remove 3 element in an array how many element # are left, consider 0 as the index, window # size should be (n-3), but for array starting # with 0 it should be ((n-1)-3) window = (n-1)-3 # Run through the entire array slinding the # window and calculating minimum difference # between the first and the last element of # that window for i in range(n): if i+window >= n: break else: min_diff = min(nums[i+window]-nums[i], min_diff) # return calculated minimum difference return min_diff return 0 # default condition
''' Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall. Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lies on the dartboard. Given the integer r, return the maximum number of darts that can lie on the dartboard. ''' class Solution: def numPoints(self, points: List[List[int]], r: int) -> int: def getPointsInside(i, r, n): # This vector stores alpha and beta and flag # is marked true for alpha and false for beta angles = [] for j in range(n): if i != j and distance[i][j] <= 2 * r: # acos returns the arc cosine of the complex # used for cosine inverse B = math.acos(distance[i][j] / (2 * r)) # arg returns the phase angle of the complex x1, y1 = points[i] x2, y2 = points[j] A = math.atan2(y1 - y2, x1 - x2) alpha = A - B beta = A + B angles.append((alpha, False)) angles.append((beta, True)) # angles vector is sorted and traversed angles.sort() # count maintains the number of points inside # the circle at certain value of theta # res maintains the maximum of all count cnt, res = 1, 1 for angle in angles: # entry angle if angle[1] == False: cnt += 1 # exit angle else: cnt -= 1 res = max(cnt, res) return res # Returns count of maximum points that can lie # in a circle of radius r. # dis array stores the distance between every # pair of points n = len(points) max_pts = n distance = [[0 for _ in range(max_pts)] for _ in range(max_pts)] for i in range(n - 1): for j in range(i + 1, n): # abs gives the magnitude of the complex # number and hence the distance between # i and j x1, y1 = points[i] x2, y2 = points[j] distance[i][j] = distance[j][i] = sqrt((x1 - x2)**2 + (y1 - y2)**2) # This loop picks a point p ans = 0 # maximum number of points for point arr[i] for i in range(n): ans = max(ans, getPointsInside(i, r, n)) return ans
''' Given a string word to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum number of letters that must be inserted so that word becomes valid. A string is called valid if it can be formed by concatenating the string "abc" several times. ''' class Solution: def addMinimum(self, word: str) -> int: res = 0 i = 0 while i < len(word): if word[i:i+3]=='abc': i+=3 elif word[i:i+2] == 'ab' or word[i:i+2] == 'bc' or word[i:i+2]=='ac': i+=2 res+=1 else: i+=1 res+=2 return res
''' You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking. Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1. ''' class Solution: def minimumSemesters(self, N: int, relations: List[List[int]]) -> int: g = collections.defaultdict(set) g_reversed = collections.defaultdict(set) for c in relations: g[c[0]].add(c[1]) g_reversed[c[1]].add(c[0]) queue = [] for i in range(1, N+1): if not g_reversed[i]: queue.append((1,i)) max_level = 0 topological_sort = [] while queue: level, v1 = queue.pop(0) topological_sort.append(v1) max_level = max(level, max_level) for v2 in g[v1]: g_reversed[v2].remove(v1) if not g_reversed[v2]: queue.append((level+1, v2)) return max_level if len(topological_sort) == N else -1 ------------------------------------------------- class Solution: def minimumSemesters(self, N: int, relations: List[List[int]]) -> int: inDegree = {i: 0 for i in range(1, N+1)} child = {i: [] for i in range(1, N+1)} for a,b in relations: inDegree[b] += 1 child[a].append(b) sources = deque([]) for k, v in inDegree.items(): if v == 0: sources.append(k) if not sources: return -1 res = 0 while sources: for _ in range(len(sources)): item = sources.popleft() for ch in child[item]: inDegree[ch] -= 1 if inDegree[ch] == 0: sources.append(ch) res += 1 for k, v in inDegree.items(): if v != 0: return -1 return res ---------------------------------------------------------------- class Solution: def minimumSemesters(self, n: int, relations: List[List[int]]) -> int: graph = defaultdict(list) indegree = [0] * n for prev_course, next_course in relations: indegree[next_course - 1] += 1 graph[prev_course - 1].append(next_course - 1) queue = [] order = [] max_level = 0 for i in range(n): if indegree[i] == 0: queue.append((i, 1)) while queue: # bfs will traverse the graph by level node, level = queue.pop(0) order.append(node) max_level = max(max_level, level) for nei in graph[node]: indegree[nei] -= 1 if indegree[nei] == 0: queue.append((nei, level + 1)) return max_level if len(order) == n else -1 -------------------------------------------------------------------------- Idea First, we construct a graph where each node maps to its dependencies. To find out the depth of every node we traverse all of its descendants in depth-first fashion and assign the depth to be 1 more than the deepest child we encounter. We also check for cycles by assigning a temporary depth of -1 to every node we visit. Complexity Time: O(E), where E is the number of edges, since we traverse the edges during graph construction and DFS. Space: O(E), because we store the graph of dependences. def minimumSemesters(self, n: int, relations: List[List[int]]) -> int: dependences = defaultdict(list) # course and its dependences for a, b in relations: dependences[b].append(a) node_depth = {} def visit(node): if node in node_depth: return node_depth[node] node_depth[node] = -1 # visiting maxdep = 0 for dep in dependences[node]: depth = visit(dep) if depth == -1: return -1 maxdep = max(maxdep, depth) del dependences[node] node_depth[node] = 1 + maxdep return node_depth[node] while dependences: if visit(next(iter(dependences))) == -1: return -1 return max(node_depth.values()) -------------------------------------------------------------------------------- Using Kahn's algo class Solution: def minimumSemesters(self, n: int, relations: List[List[int]]) -> int: graph = {} indeg = [0]*n for u, v in relations: graph.setdefault(u-1, []).append(v-1) indeg[v-1] += 1 ans = 0 queue = [x for x in range(n) if not indeg[x]] while queue: ans += 1 newq = [] for x in queue: for xx in graph.get(x, []): indeg[xx] -= 1 if not indeg[xx]: newq.append(xx) queue = newq return -1 if any(indeg) else ans
''' You are given a 0-indexed integer array books of length n where books[i] denotes the number of books on the ith shelf of a bookshelf. You are going to take books from a contiguous section of the bookshelf spanning from l to r where 0 <= l <= r < n. For each index i in the range l <= i < r, you must take strictly fewer books from shelf i than shelf i + 1. Return the maximum number of books you can take from the bookshelf. ''' class Solution: def maximumBooks(self, books: List[int]) -> int: n = len(books) dp, stack = [0] * n, [] for i in range(n): if books[i] == 0: stack.append(i) continue while stack: j = stack[-1] if books[j] >= books[i] - (i - j): stack.pop() else: break if not stack: j = -1 if books[i] - i + j + 1 < 0: dp[i] = books[i] * (books[i] + 1) // 2 else: dp[i] = (books[i] + books[i] - i + j + 1) * (i - j) // 2 if j >= 0: dp[i] += dp[j] stack.append(i) return max(dp) ------------------------------------------------------------------------------------------------------ class Solution: def maximumBooks(self, books: List[int]) -> int: n = len(books) dp = [0] * n diff = [0] * n prev = [-1] * n res = 0 stack = [] for i in range(n): diff[i] = books[i] - i # increasing stack to find prev smaller for i in range(n): while stack and stack[-1][1] >= diff[i]: stack.pop() if stack: prev[i] = stack[-1][0] stack.append([i, diff[i]]) dp[0] = books[0] for i in range(n): if prev[i] != -1: length, startIndex = i - prev[i], i - prev[i] startValue = books[i] - startIndex + 1 endValue = books[i] total = ((startValue + endValue) * length) // 2 dp[i] = max(total, total + dp[prev[i]]) else: length, startIndex = min(i + 1, books[i]), min(i + 1, books[i]) startValue = books[i] - startIndex + 1 endValue = books[i] total = ((startValue + endValue) * length) // 2 dp[i] = total return max(dp)
''' Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxSumBST(self, root: Optional[TreeNode]) -> int: self.res = 0 def dfs(root): if not root: return True, 0, float('inf'), float('-inf') lbst,lsum,lmin,lmax = dfs(root.left) rbst,rsum,rmin,rmax = dfs(root.right) if lbst and rbst and lmax <= root.val < rmin: self.res = max(self.res,(lsum+root.val+rsum)) return True, (lsum+root.val+rsum), min(root.val,lmin),max(root.val,rmax) else: return False,0,0,0 dfs(root) return self.res ------------------------------------------------------------------------------------------------------------- def maxSumBST(self, root: Optional[TreeNode]) -> int: ans = [0] dp = dict() def summ(node): if(not node): return 0 if(node in dp): return dp[node] dp[node] = node.val + summ(node.left) + summ(node.right) return dp[node] def dfs(node): if(node.left): l_min, l_max, isB_l = dfs(node.left) l = isB_l and l_max < node.val else: l_min = node.val l = 1 if(node.right): r_min, r_max, isB_r = dfs(node.right) r = isB_r and r_min > node.val else: r_max = node.val r = 1 if(l and r): ans[0] = max(ans[0], summ(node)) return l_min, r_max, 1 return -1, -1, 0 _, _, f = dfs(root) if(f): ans[0] = max(ans[0], summ(root)) return ans[0] ---------------------------------------------------------------------------------------------------------- class Solution: def find(self, node): if node is None: return 0, 0, inf, -inf l_best, l_sum, l_min, l_max = self.find(node.left) r_best, r_sum, r_min, r_max = self.find(node.right) l_min, r_max = min(node.val, l_min), max(node.val, r_max) if l_sum != -inf and r_sum != -inf and l_max < node.val < r_min: return max(l_best, r_best, l_sum + r_sum + node.val), l_sum + r_sum + node.val, l_min, r_max else: return max(l_best, r_best), -inf, l_min, r_max def maxSumBST(self, root: Optional[TreeNode]) -> int: return self.find(root)[0]
''' Given a string s, return its run-length encoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. ''' from itertools import groupby class Solution: def solve(self, s): res = list() for c, g in groupby(s): res.append([len(list(g)), c]) q = '' for k, v in res: q += str(k) + v del res return q #another class Solution: def solve(self, s): res = "" counter = 1 for i in range(1, len(s)): if s[i - 1] == s[i]: counter += 1 else: res = res + str(counter) + s[i - 1] counter = 1 res = res + str(counter) + s[-1] return res
#Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. def f(s,t): s1, s2 = [],[] for i in range(len(s)): if s[i] == '#': if s1: s1.pop() else: s1.append(s[i]) for i in range(len(t)): if t[i] == '#': if s2: s2.pop() else: s2.append(t[i]) if s1 == s2: return True else: return False
''' Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false. ''' class Solution: def hasAllCodes(self, s: str, k: int) -> bool: codes = set() for i in range(len(s) - k + 1): codes.add(s[i:i+k]) return len(codes) == 2 ** k
''' You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph. Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist. ''' #bfs import math from collections import deque class Solution(object): def shortestAlternatingPaths(self, n, red_edges, blue_edges): # build the graph in hash table graph = {i: [[], []] for i in range(n)} # node: [red edges list], [blue edges list] for [i, j] in red_edges: graph[i][0].append(j) for [i, j] in blue_edges: graph[i][1].append(j) res = [math.inf for _ in range(n)] # we will keep min length in this list res[0] = 0 # min length for the first node is 0 min_len = 0 # queue = deque() queue.append((0, "r")) queue.append((0, "b")) seen = set() while queue: level_size = len(queue) min_len += 1 for _ in range(level_size): node, color = queue.popleft() if (node, color) not in seen: seen.add((node, color)) # in addition to vertex, we need to have the color too # add all opposite color children in the queue if color == "r": for child in graph[node][1]: queue.append((child, "b")) res[child] = min(min_len, res[child]) # we reached to a child, so we have to update res[child] if color == "b": for child in graph[node][0]: queue.append((child, "r")) res[child] = min(min_len, res[child]) # we reached to a child, so we have to update res[child] for i in range(n): if res[i] == math.inf: res[i] = -1 return res ---------------------------------------------------------------------------------------------------------------------------------- class Solution: def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]: if n == 0: return [] # build graph adjList = {i:[] for i in range(n)} # {0: [(1, 'r'), 1:[], 2:[1, 'b']} for start, end in red_edges: adjList[start].append((end, 'r')) for start, end in blue_edges: adjList[start].append((end, 'b')) ans = [-1] * n ans[0] = 0 # do bfs by increasing level every time stack = [] for nextPtr, color in adjList[0]: stack.append((nextPtr, color)) # (position, color) visited = {(0, 'r'), (0, 'b')} # We start at vertex 0, so we don't want to go back to it. level = 0 while stack: level += 1 nextStack = [] for node, color in stack: if ans[node] == -1: ans[node] = level else: ans[node] = min(ans[node], level) for nextPtr, nextColor in adjList[node]: if color != nextColor and (nextPtr, nextColor) not in visited: nextStack.append((nextPtr, nextColor)) visited.add((nextPtr, nextColor)) stack = nextStack return ans
''' You are given two integers m and n, which represent the dimensions of a matrix. You are also given the head of a linked list of integers. Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1. Return the generated matrix. ''' class Solution: def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: r, c = 0, 0 xr, xc = 0, 1 matrix = [[-1 for _ in range(n)] for _ in range(m)] while head: matrix[r][c] = head.val # Conditions to swap the direction if r + xr < 0 or r + xr >= m or c + xc < 0 or c + xc >= n or matrix[r+xr][c+xc] != -1: xr, xc = xc, -xr r += xr c += xc head = head.next return matrix --------------------------------------------------------------------------------------------------------- class Solution: def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: result = [ [-1] * n for _ in range(m) ] node = head UP = 2 DOWN = 3 LEFT = 1 RIGHT = 0 directions = ( (0,1), (0,-1), (-1,0), (1,0)) direction = RIGHT uB, dB, lB, rB = 0, m-1, 0, n-1 row, col = 0, 0 while node: result[row][col] = node.val node = node.next if direction == RIGHT and col == rB and row != dB: direction = DOWN uB += 1 if direction == DOWN and col == rB and row == dB: direction = LEFT rB -= 1 if direction == LEFT and col == lB and row != uB: direction = UP dB -= 1 if direction == UP and col == lB and row == uB: direction = RIGHT lB += 1 dr,dc = directions[direction] row,col = row+dr, col+dc return result
''' On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The north direction is the positive direction of the y-axis. The south direction is the negative direction of the y-axis. The east direction is the positive direction of the x-axis. The west direction is the negative direction of the x-axis. The robot can receive one of three instructions: "G": go straight 1 unit. "L": turn 90 degrees to the left (i.e., anti-clockwise direction). "R": turn 90 degrees to the right (i.e., clockwise direction). The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. ''' class Solution: def isRobotBounded(self, instructions: str) -> bool: x = y = 0 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] i = 0 while True: for do in instructions: if do == 'G': x += directions[i][0] y += directions[i][1] elif do == 'R': i = (i + 1) % 4 else: i = (i - 1) % 4 if i == 0: return x == 0 and y == 0
''' You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34". Return the number of different integers after performing the replacement operations on word. Two integers are considered different if their decimal representations without any leading zeros are different. ''' class Solution: def numDifferentIntegers(self, word: str) -> int: s = word s = list(s) for i in range(len(s)): if s[i].isnumeric(): continue else: s[i] = ' ' s = ''.join(s) s = s.split() s = set(map(lambda x: int(x), s)) res = len(s) print(res) return res
''' Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: The height of the tree is height and the number of rows m should be equal to height + 1. The number of columns n should be equal to 2height+1 - 1. Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]). For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1]. Continue this process until all the nodes in the tree have been placed. Any empty cells should contain the empty string "". Return the constructed matrix res. ''' class Solution: # 28 ms, 92.33%. Time: O(N). Space: O(H) def printTree(self, root: TreeNode) -> List[List[str]]: def get_depth(node): if not node: return 0 return max(get_depth(node.left), get_depth(node.right)) + 1 def insert_value(node, lo, hi, depth=0): if not node: return mid = (lo + hi) // 2 output[depth][mid] = str(node.val) insert_value(node.left, lo, mid, depth + 1) insert_value(node.right, mid, hi, depth + 1) depth = get_depth(root) output = [[""] * (2**depth - 1) for _ in range(depth)] insert_value(root, 0, 2**depth - 1) return output ------------------------------------------- def printTree(self, root: TreeNode) -> List[List[str]]: def getHeight(node=root): return 1+max(getHeight(node.left), getHeight(node.right)) if node else 0 height = getHeight()-1 columns = 2**(height+1)-1 res = [[""]*columns for _ in range(height+1)] queue = deque([(root, (columns-1)//2)]) r = 0 while queue: for _ in range(len(queue)): node, c = queue.popleft() res[r][c] = str(node.val) if node.left: queue.append((node.left, c-2**(height-r-1))) if node.right: queue.append((node.right, c+2**(height-r-1))) r += 1 return res ----------------------------------------------------------------------------------------------- class Solution: def printTree(self, root: Optional[TreeNode]) -> List[List[str]]: height = self.getHeight(root) width = 2**height-1 self.result = [["" for i in range(width)] for j in range(height)] self.dfs(root,0,0,width-1) return self.result def dfs(self,root,level,left,right): if root is None: return mid = (left+right)//2 self.result[level][mid] = str(root.val) self.dfs(root.left,level+1,left,mid-1) self.dfs(root.right,level+1,mid+1,right) def getHeight(self,root): if root is None: return 0 left = self.getHeight(root.left) right = self.getHeight(root.right) return max(left,right)+1
''' You are given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value val in the range [1, 2n - 1 - 1] has two children where: The left node has the value 2 * val, and The right node has the value 2 * val + 1. You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each query, solve the following problem: Add an edge between the nodes with values ai and bi. Find the length of the cycle in the graph. Remove the added edge between nodes with values ai and bi. Note that: A cycle is a path that starts and ends at the same node, and each edge in the path is visited only once. The length of a cycle is the number of edges visited in the cycle. There could be multiple edges between two nodes in the tree after adding the edge of the query. Return an array answer of length m where answer[i] is the answer to the ith query. ''' class Solution: def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]: ans = [] for p, q in queries: path = 0 while p != q: path += 1 if p > q: p >>= 1 else: q >>= 1 ans.append(path + 1) # to account for path between p and q return ans
''' Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. ''' class Solution: def triangleNumber(self, nums: List[int]) -> int: #a+c > b #a+b > c #b+c > a nums.sort() res = 0 for i in range(len(nums)-2): a = nums[i] k = i +2 for j in range(i+1, len(nums)): b = nums[j] while k < len(nums) and a + b > nums[k]: k+=1 if k > j: res += k-j-1 return (res) ----------------------------------------------------------------------------------------- class Solution: def triangleNumber(self, T: List[int]) -> int: L, t, _ = len(T), 0, T.sort() for i in range(L-2): k = i + 2 for j in range(i+1,L-1): M = T[i] + T[j] - 1 if M < T[j]: continue while k < L and T[k] <= M: k += 1 t += min(k, L) - (j + 1) return t ---------------------------------------------------------- class Solution(object): ''' As we know inorder to check if a triangle is valid or not, if its sides are given:=> A triangle is a valid triangle, If and only If, the sum of any two sides of a triangle is greater than the third side. For Example, let A, B and C are three sides of a triangle. Then, A + B > C, B + C > A and C + A > B. Following the same we can apply this in code... ''' def isValidTriangle(self,index,nums): l,r = 0, index-1 ans = 0 while l < r: if nums[l] + nums[r] > nums[index]: ans += r - l r -= 1 else: l += 1 return ans def triangleNumber(self, nums): if len(nums) < 3: return 0 nums.sort() res = 0 for i in range(2, len(nums)): res += self.isValidTriangle(i, nums) return res ----------------------------------------------------------------------------------------------------------------- #2 pointer approach class Solution: def triangleNumber(self, nums: List[int]) -> int: res = 0 nums.sort # O(nlogn) # Loop till (n-2) elements, coz we need to fix one number every time and deal with the other two! # O(n^2) for i in range(len(nums)-1, 1, -1): fix = nums[i] # Fix a number strt = 0 end = i-1 # Deal with the other two numbers every time! while strt < end: if nums[strt]+nums[end] > fix: res += end-strt end -= 1 else: strt += 1 return res
''' You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below: ''' class Solution: def minimumLines(self, stockPrices: List[List[int]]) -> int: # key point: never use devision to judge whether 3 points are on a same line or not, use the multiplication instead !! n = len(stockPrices) stockPrices.sort(key = lambda x: (x[0], x[1])) if n == 1: return 0 pre_delta_y = stockPrices[0][1] - stockPrices[1][1] pre_delta_x = stockPrices[0][0] - stockPrices[1][0] num = 1 for i in range(1, n-1): cur_delta_y = stockPrices[i][1] - stockPrices[i+1][1] cur_delta_x = stockPrices[i][0] - stockPrices[i+1][0] if pre_delta_y * cur_delta_x != pre_delta_x * cur_delta_y: num += 1 pre_delta_x = cur_delta_x pre_delta_y = cur_delta_y return num -------------------------------------------------------------------- def minimumLines(self, A: List[List[int]]) -> int: n = len(A) res = n - 1 A.sort() for i in range(1, n - 1): a, b, c = A[i-1], A[i], A[i+1] if (b[0] - a[0]) * (c[1] - b[1]) == (c[0] - b[0]) * (b[1] - a[1]): res -= 1 return res
''' Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise. For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3. Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's. ''' class Solution: def checkZeroOnes(self, s: str) -> bool: res = [list(g) for c, g in itertools.groupby(s)] ones = 0 zeros = 0 for i in range(len(res)): if res[i][0] == '1': res[i] = ['1', len(res[i])] else: res[i] = ['0', len(res[i])] for i in range(len(res)): if res[i][0] == '1': if res[i][1] > ones: ones = res[i][1] else: if res[i][1] > zeros: zeros = res[i][1] print('ones', ones) print('zeros', zeros) return ones > zeros class Solution: def checkZeroOnes(self, s: str) -> bool: s1 = s.split('0') s0 = s.split('1') r1 = max([len(i) for i in s1]) r0 = max([len(i) for i in s0]) return r1>r0
''' You are given a 0-indexed array of string words and two integers left and right. A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a', 'e', 'i', 'o', and 'u'. Return the number of vowel strings words[i] where i belongs to the inclusive range [left, right]. ''' class Solution: def vowelStrings(self, words: List[str], left: int, right: int) -> int: res = 0 for i in range(left, right+1): word = words[i] if any(word.startswith(vowel) for vowel in 'aeiou') and any(word.endswith(vowel) for vowel in 'aeiou'): res+=1 return res
''' Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang. A boomerang is a set of three points that are all distinct and not in a straight line. ''' class Solution: def isBoomerang(self, points: List[List[int]]) -> bool: (x0, y0), (x1, y1), (x2, y2) = points return (y2 - y1) * (x0 - x1) != (x2 - x1) * (y0 - y1)
''' You are given a positive integer n. Continuously replace n with the sum of its prime factors. Note that if a prime factor divides n multiple times, it should be included in the sum as many times as it divides n. Return the smallest value n will take on. ''' class Solution: def prime_factors(self, n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors def smallestValue(self, n: int) -> int: num = n seen = set() while num > 0: factors = self.prime_factors(num) if len(factors) == 1: return factors[0] num = sum(factors) if num in seen: break seen.add(num) return num
''' There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'. ''' class Solution: def minTimeToType(self, word: str) -> int: total = 0 last = 'a' for ch in word: val = (ord(ch) - ord(last) ) % 26 total += min(val, 26-val)+1 last = ch return total
''' Given the root of a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values. ''' class Solution: def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: seen = collections.defaultdict(int) res = [] def helper(node): if not node: return sub = tuple([helper(node.left), node.val, helper(node.right)]) if sub in seen and seen[sub] == 1: res.append(node) seen[sub] += 1 return sub helper(root) return res --------------------------------------------------------------------------- class Solution: def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: subtrees = {} mono_id = 1 visited = set() res = [] def helper(node: TreeNode) -> int: nonlocal mono_id if not node: return 0 left_id = helper(node.left) right_id = helper(node.right) key = (node.val, left_id, right_id) if key in subtrees: # already seen this unique subtree if key not in visited: # first time re-visiting this unique subtree visited.add(key) res.append(node) else: # first time seeing this unique subtree subtrees[key] = mono_id mono_id += 1 return subtrees[key] helper(root) return res --------------------------------------------------------------------------------------- class Solution: def dfs(self, root, lookup, duplicates): if not root: return '.' subtree = str(root.val) + '-' + self.dfs(root.left, lookup, duplicates) + '-' + self.dfs(root.right, lookup, duplicates) if subtree in lookup: if lookup[subtree] == 1: duplicates.append(root) lookup[subtree] += 1 else: lookup[subtree] = 1 return subtree def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: lookup, duplicates = {}, [] self.dfs(root, lookup, duplicates) return duplicates
''' Дан список чисел arr. Написать функцию perms, которая возвращает список из кортежей со всеми возможными перестановками из исходных чисел. ''' import itertools class Answer: def perms(self, arr): return list(itertools.permutations(arr))
''' You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k. Return the number of non-empty subarrays in nums that have a median equal to k. Note: The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element. For example, the median of [2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4. A subarray is a contiguous part of an array. ''' def countSubarrays(self, nums: List[int], k: int) -> int: prefix_sum_of_balance = Counter([0]) # Dummy value of 0's frequency is 1. running_balance = ans = 0 found = False for num in nums: if num < k: running_balance -= 1 elif num > k: running_balance += 1 else: found = True if found: ans += prefix_sum_of_balance[running_balance] + prefix_sum_of_balance[running_balance - 1] else: prefix_sum_of_balance[running_balance] += 1 return ans
''' The value of an alphanumeric string can be defined as: The numeric representation of the string in base 10, if it comprises of digits only. The length of the string, otherwise. Given an array strs of alphanumeric strings, return the maximum value of any string in strs. ''' #my own solution class Solution: def maximumValue(self, strs: List[str]) -> int: res = float('-inf') for w in strs: if w.isdigit(): res = max(res, int(w,10)) else: res = max(res, len(w)) return res ---------------------------------------------------------------------------------- class Solution: def maximumValue(self, strs: List[str]) -> int: ans = 0 for s in strs: if s.isnumeric(): ans = max(ans,int(s)) else: ans = max(ans,len(s)) return ans
''' Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders. Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order. ''' class Solution: def displayTable(self, orders: List[List[str]]) -> List[List[str]]: allDishes=set() myFood={} for name,tableNo,dish in orders: if dish not in allDishes: allDishes.add(dish) if (tableNo) in myFood: if dish in myFood[(tableNo)]: myFood[(tableNo)][dish]=myFood[(tableNo)][dish]+1 else: myFood[(tableNo)][dish]=1 else: myFood[(tableNo)]={dish:1} print(myFood) allDishes=sorted(allDishes) allFood=["Table"] +[d for d in allDishes ] res=[] res.append(allFood) for table in sorted(myFood, key=int): #int to sort tables ascendingly t=[] t.append((table)) for i in range(1,len(allFood)): currDish=allFood[i] if currDish in myFood[(table)]: t.append(str(myFood[(table)][currDish])) else: t.append('0') res.append(t) return res ------------------------------------------------------ def displayTable(self, orders: List[List[str]]) -> List[List[str]]: dict_ = defaultdict(lambda: defaultdict(int)) # nested dictionary of [table][item] storing counts items = sorted(set(item for name,table,item in orders)) # unique items sorted lexicographically tables = sorted(set(table for name,table,item in orders), key=int) # unique table numbers sorted # build dictionary for name,table,item in orders: dict_[table][item] += 1 # build result table row/column headers res = [['Table']+items] for table in tables: res.append([table]) # append each value to result table based on row/column headers for i in range(1, len(res)): for j in range(1, len(res[0])): table, item = res[i][0], res[0][j] count = str(dict_[table][item]) res[i].append(count) return res --------------------------------------------------------- def displayTable(self, orders): map_={} res=[] arr=[] set_=set() for i in range(0, len(orders)): if int(orders[i][1]) not in map_: map_[int(orders[i][1])]=[orders[i][2]] else: map_[int(orders[i][1])].append(orders[i][2]) map_=sorted(map_.items(), key=lambda x:x[0]) for i in range(0, len(orders)): set_.add(orders[i][2]) set_=list(set_) set_.sort() set_.insert(0,"Table") res.append(set_) # print(res) for i in map_: arr.append(str(i[0])) for j in set_[1:]: arr.append(str(i[1].count(j))) res.append(arr) arr=[] # print(res) return res
''' You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations. You can perform the following operation at most maxOperations times: Take any bag of balls and divide it into two new bags with a positive number of balls. For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls. Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations. Return the minimum possible penalty after performing the operations. ''' class Solution: def minimumSize(self, nums: List[int], maxOperations: int) -> int: l, r = 1, max(nums) while l < r: mid = (l + r) // 2 if sum([(n - 1) // mid for n in nums]) > maxOperations: l = mid + 1 else: r = mid return l --------------------------------------------------------------------------------------- Given a threshold t (max number of balls per final bag), we need at least ceil(n / t) of bags to split n balls. The required operations is then ceil(n / t) - 1. For example a bag of n = 10 balls and threshold t = 4, we need to split them into (4, 4, 2) 3 bags, which requires 2 split operations. Binary search on the threshold which takes O(logM) time, where M is the maximum number of balls in each bags. Checking if a certain threshold is feasible take O(N) for N bags. Together, the time complexity is O(N log M). from math import ceil def minimumSize(self, nums: List[int], maxOperations: int) -> int: def required(n, t): """ Required N of operations to split a bag with n balls into bags each with fewer than or equals to t balls """ return int(ceil(n / t)) - 1 def possible(t): """ Is it possible to have less than t balls per bag with maxOperations? """ if t <= 0: return False sum_req = 0 for x in nums: sum_req += required(x, t) if sum_req > maxOperations: return False return True nums = sorted(nums, reverse=True) r = nums[0] # known minimum possible threshold l = 0 # known maximum impossible threshold while r - l > 1: mid = (r + l) // 2 if possible(mid): r = mid else: l = mid return r
''' You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix. Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if: For each cell matrix[row][col] (0 <= col <= n - 1) where matrix[row][col] == 1, col is present in s or, No cell in row has a value of 1. You need to choose numSelect columns such that the number of rows that are covered is maximized. Return the maximum number of rows that can be covered by a set of numSelect columns. ''' class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: m, n = len(mat), len(mat[0]) maxRows = 0 colToChoose = list(combinations(list(range(n)), cols)) for col in colToChoose: col = set(col) rowHidden = 0 for row in mat: canHide = True for i in range(n): if(row[i] and i not in col): canHide = False break if(canHide): rowHidden += 1 maxRows = max(maxRows, rowHidden) return maxRows ------------------------------------------------------------------------------------------------------------------------------- class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: n,m = len(mat),len(mat[0]) ans = 0 def check(state,row,rowIncludedCount): nonlocal ans if row==n: if sum(state)<=cols: ans = max(ans,rowIncludedCount) return check(state[::],row+1,rowIncludedCount) for j in range(m): if mat[row][j]==1: state[j] = 1 check(state,row+1,rowIncludedCount+1) check([0]*m,0,0) return ans
''' Given two sparse vectors, compute their dot product. Implement class SparseVector: SparseVector(nums) Initializes the object with the vector nums dotProduct(vec) Compute the dot product between the instance of SparseVector and vec A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector. Follow up: What if only one of the vectors is sparse? ''' Suggestions to make it better are always welcomed. We can write 1 liners for below code as well. Approach: If dotProduct() is called million times, it will be good if we consider only the non-zero values to save time. So, let's use dictionary. Now, we can multiply the values for same indexes in both the dictionaries. What if 1 dictionary is thousand times bigger than the other? Can we reduce the time it takes to get the result? If we compare the lengths and loop on the smaller dictionary, we can get result much faster. Time complexity still remains O(len(dictionary)) but it's better. class SparseVector: def __init__(self, nums: List[int]): self.nums = {i: n for i, n in enumerate(nums) if n} def dotProduct(self, vec: 'SparseVector') -> int: result = 0 if len(self.nums) < len(vec.nums): for key in self.nums.keys(): if key in vec.nums: result += self.nums[key] * vec.nums[key] else: for key in vec.nums.keys(): if key in self.nums: result += self.nums[key] * vec.nums[key] return result ---------------------------------------- We are instructed to store the sparse vector efficently. This is a clue to use a dict/map. class SparseVector: def __init__(self, nums): self.ix = {i: x for i, x in enumerate(nums) if x} def dotProduct(self, vec): a, b = self.ix, vec.ix return sum(a[i] * b[i] for i in a if i in b) If one vector is sparse, and the other is not, we can update dotProduct() to iterate through the shorter: class SparseVector: # as above def dotProduct(self, vec): a, b = self.ix, vec.ix if len(a) > len(b): a, b = b, a return sum(a[i] * b[i] for i in a if i in b) We can also use this question as an opporunity to showcase familiarity with supporting Python's built-in functions. See Slatkin's "Effective Python" Item 28 for details. class SparseVector: def __init__(self, nums: List[int]): self.ix = {i: x for i, x in enumerate(nums)} def __getitem__(self, i): return self.ix.__getitem__(i) def __contains__(self, i): return self.ix.__contains__(i) def __iter__(self): return self.ix.__iter__() def __len__(self): return self.ix.__len__() def dotProduct(self, vec: 'SparseVector') -> int: a, b = self, vec if len(a) > len(b): a, b = b, a return sum(a[i] * b[i] for i in a if i in b) --------------------------------------------- class SparseVector: def __init__(self, nums: List[int]): self.sparse = [(i, v) for i, v in enumerate(nums) if v] # Return the dotProduct of two sparse vectors def dotProduct(self, vec: 'SparseVector') -> int: product = 0 i1 = 0 i2 = 0 while i1 < len(vec.sparse) and i2 < len(self.sparse): if vec.sparse[i1][0] < self.sparse[i2][0]: i1 += 1 elif vec.sparse[i1][0] > self.sparse[i2][0]: i2 += 1 else: product += vec.sparse[i1][1] * self.sparse[i2][1] i1 += 1 i2 += 1 return product ------------------------------------- class SparseVector: def __init__(self, nums: List[int]): self.vect = {i:n for i,n in enumerate(nums) if n != 0} # Return the dotProduct of two sparse vectors def dotProduct(self, vec: 'SparseVector') -> int: tot = 0 for k, v in self.vect.items(): tot += v * vec.vect.get(k, 0) return tot ---------------------------------- class SparseVector: def __init__(self, nums: List[int]): self.nums=nums # Return the dotProduct of two sparse vectors def dotProduct(self, vec: 'SparseVector') -> int: sum=0 for i,v in zip(self.nums,vec.nums): sum+=(i*v) return sum ----------------------------------
''' Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. ''' class Solution: def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]: wordSet = set(words) res = set() def dfs(s): if not s: return True for i in range(len(s)): if s[:i + 1] in wordSet: if dfs(s[i + 1:]): return True return False for word in wordSet: wordSet.remove(word) # We need to not match the word with itself if dfs(word): res.add(word) wordSet.add(word) return res ----------------------------------------------------------------------------------------------------------- class Solution: def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]: trie = dict() mem = set(words) for w in words: cur = trie for c in w: if c not in cur: cur[c] = dict() cur = cur[c] cur["*"] = w def helper(w, level): cur = trie for i, c in enumerate(w): if c not in cur: return False cur = cur[c] if "*" in cur: if i == len(w) - 1: return level > 1 else: if w[i + 1:] in mem or helper(w[i + 1:], level + 1): return True return False ans = list() for w in words: if helper(w, 1): ans.append(w) return ans
''' Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties. Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins. ''' class Solution: def stoneGame(self, nums: List[int]) -> bool: n = len(nums) @cache def dfs(i, j): if i == j: return nums[i] pick_left = nums[i] - dfs(i+1, j) pick_right = nums[j] - dfs(i, j-1) return max(pick_left, pick_right) return dfs(0, n-1) >= 0
''' A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation: Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F'). Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times. ''' class Solution: def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: ifTrueIsAnswer = self.confuseStudents(answerKey, k, "T") ifFalseIsAnswer = self.confuseStudents(answerKey, k, "F") return max(ifTrueIsAnswer, ifFalseIsAnswer) def confuseStudents(self, array, k, key): left, result = 0, 0 for right in range(len(array)): if array[right] == key: k -= 1 if k < 0: result = max(result, right-left) while k < 0: if array[left] == key: k += 1 left += 1 return max(result, right+1-left) ------------------------------------------------------------------------------------------------ One left and one right pointer to determine a window, calculate the amount of T and F in that window, when one of them is less than k, we can change all those letters to another, so that all the letters in the window are the same, then the window size is an alternative answer. Traverse the entire string to get maximum value. Slide the right pointer to calculate the number of T and F in the window If the number of T and F are both greater than k, that is, all letters in the window cannot be changed to be the same by modifying one letter, and the left pointer needs to be moved After the left pointer is moved, the window size can be used as the answer, compared with the current maximum value and updated Runtime: 332 ms, faster than 82.95% of Python3 online submissions for Maximize the Confusion of an Exam. Memory Usage: 14.4 MB, less than 83.16% of Python3 online submissions for Maximize the Confusion of an Exam. class Solution: def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: n = len(answerKey) left = ret = numT = numF = 0 for right in range(n): if answerKey[right]=='T': numT+=1 else: numF+=1 while numT>k and numF>k: if answerKey[left]=='T': numT-=1 else: numF-=1 left+=1 ret = max(ret, right-left+1) return ret
''' An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. ''' class Solution(object): # DFS: iterative implement. def isAdditiveNumber(self, num): length = len(num) for i in range(1, length/2+1): for j in range(1, (length-i)/2 + 1): first, second, others = num[:i], num[i:i+j], num[i+j:] if ((len(first) > 1 and first[0] == "0") or (len(second) > 1 and second[0] == "0")): continue while others: sum_str = str(int(first) + int(second)) if sum_str == others: return True elif others.startswith(sum_str): first, second, others = ( second, sum_str, others[len(sum_str):]) else: break return False ------------------------------------------------------------------------------- class Solution: def isAdditiveNumber(self, num: str) -> bool: def isadditive(num1,num2,st): if len(st) == 0: return True num3 = str(num1+num2) l = len(num3) return num3 == st[:l] and isadditive(num2,int(num3),st[l:]) for i in range(1,len(num)-1): for j in range(i+1,len(num)): if num [0] == "0" and i != 1: break if num[i] == "0" and i+1 != j: break if isadditive(int(num[:i]),int(num[i:j]),num[j:]): return True return False
''' You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2]. ''' class Solution: def visiblePoints(self, points: List[List[int]], angle: int, l: List[int]) -> int: # start from east, build angles for each point, exclude point same as stand point res = sorted([math.degrees(math.atan2((p[1] - l[1]), (p[0] - l[0]))) for p in points if p != l]) # build slide window angles = res + [x + 360 for x in res] i = 0 best = 0 for j, ang in enumerate(angles): while ang - angles[i] > angle: i += 1 best = max(best, j - i + 1) return best + (len(points) - len(res)) --------------------------------------------------------------------------------------- class Solution(object): def visiblePoints(self, points, angle, location): """ :type points: List[List[int]] :type angle: int :type location: List[int] :rtype: int """ x0,y0 = location # to radians angle *= pi/180 # transform points to location + filter + transform to polar angle angles = sorted([atan2(x-x0,y-y0) for x,y in points if x!=x0 or y!=y0]) n = len(angles) angles += [2*pi+a for a in angles] l,r = 0,0 maxview=0 while l<n: while r<2*n and angles[r]-angles[l]<=angle: r+=1 maxview = max(maxview,r-l) while l<n and angles[r]-angles[l]>angle: l+=1 return maxview + len(points)-n
''' You are given a string s consisting of n characters which are either 'X' or 'O'. A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same. Return the minimum number of moves required so that all the characters of s are converted to 'O'. ''' #my own solution class Solution: def minimumMoves(self, s: str) -> int: if s.count('X') == 0: print('no x found') return 0 i = 0 c = 0 while i < len(s): print('--------i------', i) print() if s[i] == 'X': i += 3 c += 1 else: i += 1 print('count', c) print('end') return c #another class Solution: def minimumMoves(self, s: str) -> int: sl=list(s) out=0 for i in range(0,len(sl)-2): if sl[i]=="X": sl[i]="O" sl[i+1]="O" sl[i+2]="O" out+=1 elif sl[i]=="O": continue if sl[-1]=="X" or sl[-2]=="X": out+=1 return out #another solution 2 class Solution: def minimumMoves(self, s: str) -> int: i, m = 0, 0 l = len(s) while i < l: if s[i] != 'X': i += 1 elif 'X' not in s[i:i+1]: i += 2 elif 'X' in s[i:i+2]: m += 1 i += 3 return m class Solution(object): def minimumMoves(self, s): """ :type s: str :rtype: int """ ans, l = 0, 0 while l < len(s): if s[l] == 'X': l+=3 ans +=1 else: l+=1 return ans
''' You have a binary tree with a small defect. There is exactly one invalid node where its right child incorrectly points to another node at the same depth but to the invalid node's right. Given the root of the binary tree with this defect, root, return the root of the binary tree after removing this invalid node and every node underneath it (minus the node it incorrectly points to). Custom testing: The test input is read as 3 lines: TreeNode root int fromNode (not available to correctBinaryTree) int toNode (not available to correctBinaryTree) After the binary tree rooted at root is parsed, the TreeNode with value of fromNode will have its right child pointer pointing to the TreeNode with a value of toNode. Then, root is passed to correctBinaryTree. ''' Explanation q: Deque for level order traversal p: Hash table to store a tuple indicates the parent of key {cur_node: (parent_node, is_left_node)} visited: Hash set to determine whether node is visited Process: Start with level order traversal If same node being visited twice, meaning we meet the child of the wrong node (we call it cur) Find the grandparent of cur, and let the grandparent node (grand_p) de-link its child (the wrong node) Return root Implementation class Solution: def correctBinaryTree(self, root: TreeNode) -> TreeNode: q = collections.deque([root]) p, visited = dict(), set() while q: cur = q.popleft() if cur in visited: grand_p, is_left = p[p[cur][0]] if is_left: grand_p.left = None else: grand_p.right = None return root visited.add(cur) if cur.left: p[cur.left] = (cur, 1) q.append(cur.left) if cur.right: p[cur.right] = (cur, 0) q.append(cur.right) return root ------------------------------------------------------------------------------------ Algo Traverse the tree and find the invalid node. Implementation DFS class Solution: def correctBinaryTree(self, root: TreeNode) -> TreeNode: seen = set() stack = [(root, None)] while stack: node, prev = stack.pop() if node.right and node.right.val in seen: if node == prev.left: prev.left = None if node == prev.right: prev.right = None return root seen.add(node.val) if node.left: stack.append((node.left, node)) if node.right: stack.append((node.right, node)) BFS class Solution: def correctBinaryTree(self, root: TreeNode) -> TreeNode: queue = [(root, None)] seen = set() for node, prev in queue: if node.right and node.right.val in seen: if node == prev.left: prev.left = None if node == prev.right: prev.right = None return root seen.add(node.val) if node.right: queue.append((node.right, node)) if node.left: queue.append((node.left, node)) ------------------------------------------------------------------- Find the node using dfs with the help of dictionary that keeps track of parent and child. If a node is pointing to some other node and then it will be visited twice. So, when you come across a node that is visited twice, fetch the parent. This is the from_node. Now just delete the from_node by returning None. This deletes the node. When you return None or just nothing, the child node is treated as None. Hence, it is deleted. :) class Solution: def correctBinaryTree(self, root: TreeNode) -> TreeNode: self.seen = defaultdict(int) self.from_node = None def find_from_node(root, parent): if not root: return if root.val in self.seen: self.from_node = self.seen[root.val] return self.seen[root.val] = parent.val if parent else None find_from_node(root.left, root) find_from_node(root.right, root) find_from_node(root, None) def traverse(root): if not root: return if root.val == self.from_node: return root.left = traverse(root.left) root.right = traverse(root.right) return root traverse(root) return root
''' A parentheses string is valid if and only if: It is the empty string, It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string. For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))". ''' class Solution: def minAddToMakeValid(self, s: str) -> int: ans = bal = 0 for i in s: if i == '(': bal+=1 else: bal-=1 if bal == -1: ans+=1 bal+=1 return ans+bal ------------------------------------------------- def minAddToMakeValid(self, s: str) -> int: stack = [] for ch in S: if ch == '(': stack.append(ch) else: if len(stack) and stack[-1] == '(': stack.pop() else: stack.append(ch) return len(stack) ----------------------------------------------------------- #my own solution class Solution: def minAddToMakeValid(self, s: str) -> int: stack = list() for elem in s: if elem == '(': stack.append(elem) else: if elem == ')' and len(stack)!= 0 and stack[-1] == '(' : stack.pop() else: stack.append(elem) return len(stack)
''' Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: answer[0] is a list of all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct integers in nums2 which are not present in nums1. Note that the integers in the lists may be returned in any order. ''' class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: f1 = set() f2 = set() for i in range(len(nums1)): if nums1[i] not in nums2: f1.add(nums1[i]) for i in range(len(nums2)): if nums2[i] not in nums1: f2.add(nums2[i]) answer = list() f1 = list(f1) f2 = list(f2) answer.append(f1) answer.append(f2) return answer #another def findDifference(self, a: List[int], b: List[int]) -> List[List[int]]: return [set(a)-set(b), set(b)-set(a)]
''' Given an array of distinct strings words, return the minimal possible abbreviations for every word. The following are the rules for a string abbreviation: Begin with the first character, and then the number of characters abbreviated, followed by the last character. If there is any conflict and more than one word shares the same abbreviation, a longer prefix is used instead of only the first character until making the map from word to abbreviation become unique. In other words, a final abbreviation cannot map to more than one original word. If the abbreviation does not make the word shorter, then keep it as the original. ''' class Solution: def wordsAbbreviation(self, words: List[str]) -> List[str]: def makeAbbr(word, k): # create abbreviation from word # k - # of letters that should be changed if k >= len(word)-2: return word wordAbbr = word[:k] wordAbbr += str(len(word) - 1 - k) wordAbbr += word[-1] return wordAbbr l = len(words) ans = [''] * l prefix = [0] * l # create max abbriviation for words for i in range(l): prefix[i] = 1 ans[i] = makeAbbr(words[i], 1) for i in range(l): # this value only for while loop a = 0 while a == 0: hashSet = [] for j in range(i+1, l): # looking duplicates and add index in list if ans[j] == ans[i]: hashSet.append(j) if len(hashSet) == 0: # if we don't have duplicates abbreviation a = 1 hashSet.append(i) # we should add index of 1st duplicate word if len(hashSet) > 1: # if we have 2 words with same abbreviation for k in hashSet: prefix[k] += 1 # increase prefix ans[k] = makeAbbr(words[k], prefix[k]) # change abbreviation return ans --------------------------------------- validAbbs_table = {} words = dict def formAbb(word,prefix): pre = word[:prefix] return pre+str(len(word)-len(pre)-1)+word[-1] def validate(arr): table = {} invalidAbbs = [] for i in arr: if i[1] in table: table[i[1]].append(i[0]) else: table[i[1]] = [i[0]] for i in table: if len(table[i]) == 1: abb = (i,table[i][0]) if len(i) >= len(table[i][0]): abb = (table[i][0],table[i][0]) validAbbs_table[abb[1]] = abb[0] else: invalidAbbs.extend(table[i]) return invalidAbbs def abbreviate(dict,count): if not dict: return [validAbbs_table[i] for i in words] arr = [] for i in dict: abb = formAbb(i,count) arr.append((i,abb)) invalidAbbs = validate(arr) return abbreviate(invalidAbbs,count+1) return abbreviate(dict,1)
''' Design a text editor with a cursor that can do the following: Add text to where the cursor is. Delete text from where the cursor is (simulating the backspace key). Move the cursor either left or right. When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds. Implement the TextEditor class: TextEditor() Initializes the object with empty text. void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text. int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted. string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor. string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor. ''' class Node: def __init__(self, val): self.val = val self.left = None self.right = None class TextEditor: def __init__(self): self.cursor = Node(-1) def addText(self, text: str) -> None: curr = self.cursor last = curr.right for c in text: curr.right = Node(c) curr.right.left = curr curr = curr.right curr.right = last if last: last.left = curr self.cursor = curr def deleteText(self, k: int) -> int: curr = self.cursor last = curr.right tot = 0 while k and curr.val != -1: curr = curr.left k -= 1 tot += 1 if last: last.left = curr curr.right = last self.cursor = curr return tot def cursorLeft(self, k: int) -> str: while k and self.cursor.val != -1: self.cursor = self.cursor.left k -= 1 return self.getvals(self.cursor) def cursorRight(self, k: int) -> str: while k and self.cursor.right: self.cursor = self.cursor.right k -= 1 return self.getvals(self.cursor) def getvals(self, curr): vals = deque() k = 10 while k and curr.val != -1: vals.appendleft(curr.val) curr = curr.left k -= 1 return "".join(vals) ---------------------------------------------------------------- class TextEditor: def __init__(self): self.left = deque() self.right = deque() def addText(self, text: str) -> None: self.left.extend(list(text)) def deleteText(self, k: int) -> int: tot = 0 while k and self.left: self.left.pop() k -= 1 tot +=1 return tot def cursorLeft(self, k: int) -> str: while k and self.left: self.right.appendleft(self.left.pop()) k -= 1 return self.getvals() def cursorRight(self, k: int) -> str: while k and self.right: self.left.append(self.right.popleft()) k -= 1 return self.getvals() def getvals(self): N = len(self.left) return "".join(self.left[i] for i in range(max(N-10, 0), N)) --------------------------------------------------------------------------------------- class TextEditor: def __init__(self): self.txt = '' self.ptr = 0 def addText(self, text: str) -> None: self.txt = self.txt[:self.ptr] + text + self.txt[self.ptr:] self.ptr += len(text) def deleteText(self, k: int) -> int: org = len(self.txt) self.txt = self.txt[:max(self.ptr - k, 0)] + self.txt[self.ptr:] self.ptr = max(self.ptr - k, 0) return org - len(self.txt) def cursorLeft(self, k: int) -> str: self.ptr = max(self.ptr - k, 0) return self.txt[max(0, self.ptr - 10):self.ptr] def cursorRight(self, k: int) -> str: self.ptr = min(self.ptr + k, len(self.txt)) return self.txt[max(0, self.ptr - 10):self.ptr] ------------------------------------------------------------------------------------------------- class Node: def __init__(self, c, pre=None, next=None): self.c = c self.pre = pre self.next = next class TextEditor: def __init__(self): self.head = Node(0) self.tail = Node(1) self.head.next = self.tail self.tail.pre = self.head self.curr = self.tail def addText(self, text: str) -> None: pre = self.curr.pre post = self.curr for c in text: curr = Node(c) pre.next = curr curr.pre = pre pre = curr pre.next = post post.pre = pre def deleteText(self, k: int) -> int: ans = 0 curr = self.curr pre = curr.pre for _ in range(k): if pre.c == 0: break ans += 1 pre = pre.pre pre.next = curr curr.pre = pre return ans def cursorLeft(self, k: int) -> str: curr = self.curr pre = curr.pre for _ in range(k): if pre.c == 0: break self.curr = pre pre = pre.pre return self.rt_txt() def cursorRight(self, k: int) -> str: for _ in range(k): if self.curr.c == 1: break post = self.curr.next self.curr = post return self.rt_txt() def rt_txt(self,): s = "" pre = self.curr.pre for _ in range(10): if pre.c == 0: break s = pre.c + s pre = pre.pre return s
''' Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2. ''' class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: ''' здесь я тупо не понял задачу и сидел решал не то - тут даны m, n - а они нужны чтоб вести отсчет! ''' p1 = m - 1 p2 = n - 1 i = m+n-1 while p2 >= 0: if p1 >= 0 and nums1[p1] > nums2[p2]: nums1[i] = nums1[p1] i = i-1 p1 = p1-1 else: nums1[i] = nums2[p2] i = i-1 p2 = p2-1 return nums1
''' You are given two 0-indexed strings word1 and word2. A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j]. Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one move. Return false otherwise. ''' class Solution: def insertAndRemove(self, mp, toInsert, toRemove): mp[toInsert]+=1 mp[toRemove]-=1 if(mp[toRemove]==0): del mp[toRemove] # if freq of that char reaches zero, then remove the key from dict def isItPossible(self, word1: str, word2: str) -> bool: mp1, mp2 = Counter(word1), Counter(word2) # Get freq of chars using Counter """ # If you are not familiar with Counters, you can simply do this: mp1=defaultdict(int) mp2=defaultdict(int) for w1 in word1: mp1[w1]+=1; #store freq of chars in word1 in mp1 for w2 in word2: mp2[w2]+=1; #store freq of chars in word2 in mp2 """ for c1 in string.ascii_lowercase: # this for loop iterates through c1='a' to c1='z' for c2 in string.ascii_lowercase: # this for loop iterates through c2='a' to c2='z' if c1 not in mp1 or c2 not in mp2: # if any of the char is not present then skip continue self.insertAndRemove(mp1, c2, c1); # insert c2 to word1 and remove c1 from word1 self.insertAndRemove(mp2, c1, c2); # insert c1 to word2 and remove c2 from word2 if len(mp1)== len(mp2): # if size of both dicts are equal then possible return true return True # reset back the maps self.insertAndRemove(mp1, c1, c2); # insert c1 back to word1 and remove c2 from word1 self.insertAndRemove(mp2, c2, c1); # insert c2 back to word2 and remove c1 from word2 return False ---------------------------------------------------------------------------------------------------------------- class Solution: def isItPossible(self, word1: str, word2: str) -> bool: c1 = Counter(word1) c2 = Counter(word2) for ch1 in c1: for ch2 in c2: new_c1 = c1 - Counter({ch1: 1}) + Counter({ch2: 1}) new_c2 = c2 + Counter({ch1: 1}) - Counter({ch2: 1}) if len(new_c1) == len(new_c2): return True return False
import numpy as np import pandas as pd from scipy.stats import norm import pandas_datareader as web import datetime # If we want to calculate VaR for tomorrow def value_at_risk(position, c, mu, sigma): alpha = norm.ppf(1 - c) var = position * (mu - sigma * alpha) return var # We want to calculate VaR in n days time # We have to consider that the mean and standard deviation will change # mu = mu * n and sigma = sigma * sqrt(n) we have to uso these transformations def value_at_risk_long(S, c, mu, sigma, n): alpha = norm.ppf(1 - c) var = S * (mu * n - sigma * alpha * np.sqrt(n)) return var if __name__ == '__main__': # historical data to approximate mean and standard deviation start_date = datetime.datetime(2014, 1, 1) end_date = datetime.datetime(2017, 10, 15) # Download stock related data from Yahoo Finance citi = web.DataReader('C', data_source='yahoo', start=start_date, end=end_date) # We can use pct_change() to calculate daily returns citi['returns'] = citi['Adj Close'].pct_change() S = 1e6 # this is the investiment (stocks or whatever) c = 0.99 # condifence level: this time it is 99% # We can assume daily returns to be normally sidtributed: mean and variance (standard deviation) # Can describe the process mu = np.mean(citi['returns']) sigma = np.std(citi['returns']) print('Value at risk is: $%0.2f' % value_at_risk(S, c, mu, sigma))
#ch4-1 list L = ['Adam', 95.5, 'Lisa', 85, 'Bart', 59] print L #4-2 index list L = [95.5,85,59] print L[0] print L[1] print L[2] print L[3] #4-3 invert list L = [95.5, 85, 59] print L[-1] print L[-2] print L[-3] print L[-4] #4-4 insert to list L = ['Adam', 'Lisa', 'Bart'] L.insert(2, 'Paul') print L #4-5 pop from list L = ['Adam', 'Lisa', 'Paul', 'Bart'] L.pop(3) L.pop(2) print L #4-6 replace among list L = ['Adam', 'Lisa', 'Bart'] L[0]='Bart' L[-1]='Adam' print L #4-7 tuple t = (0,1, 2, 3, 4, 5, 6, 7, 8, 9) print t #4-8 singel element tuple t = ('Adam',) print t #4-9 editable tuple t = ('a', 'b', ('A', 'B')) print t
a=0 b=0 c=0 d=0 e=0 while d==0 or c!=0: e=int(input("dati cifra:")) d=e%2 c=e%3 if(d==0): b=e+a a=b print(b)
import verify # Used for verifying that the algorithm is working as intended ''' Selection Sort: Selection sort takes an array and sorts a single element during each iteration. It sets the left most unsorted value as the smallest value and iterates through the values. If a value is the equal or greater to the smallest value, it continues to the next value, but if the value is smaller then it sets the current value as the smallest index. After the final value is reached, the values at the target index and smallest indexs are flipped. This is performed until all the values are sorted. Has a run time of O(n^2) ''' # Algorithm def selection_sort_itertive(sequence): # Accepts a sequence. Doesn't check if the sequence is sorted or not. for i in range(len(sequence)): target_index = i # The index of the value being compared to the other values in the array smallest_index = i # The index of the smallest value within the sequence. It is initially the same as the target index. for x in range(i, len(sequence)): # Iterates through the values to the right of the target index if sequence[smallest_index] > sequence[x]: # Executes if a smaller value is found smallest_index = x # Replaces the smallest index with the index of the current value # Swaps the values at the target and smallest indexes with the help of a temporary variable. temp = sequence[target_index] sequence[target_index] = sequence[smallest_index] sequence[smallest_index] = temp return sequence # Verify that the algorithm works unsorted = verify.get_unsorted_list() print("Unsorted Sequence:", unsorted) sorted = selection_sort_itertive(unsorted) print("Sorted Sequence: ", sorted) print("Sorted?", verify.verify(sorted))
n = int(input("so dau: ")) m = int(input("so cuoi: ")) for i in range(n,m+1): if i%2==0: print(i)
from turtle import * speed (0) shape("turtle") color("green") n = int(input("How many circles do you want to draw?")) for i in range(n): circle(100) left(360/n) mainloop()
import random word_list = ["Chelsea", "Poker", "Finance", "Electricity", "Lamp", "Excessive"] #print("Here is my pretty awesome word list: ") #print(*word_list, sep=", ") loop = 2 while loop == 2: word = random.choice(word_list) shuffled = list(word) random.shuffle(shuffled) shuffled = ''.join(shuffled) print(*shuffled, sep=" ") guess = input("your guess: ") loop = 1 while loop == 1: if guess != word: print("Try again!") guess = input("your guess: ") else: print("IMPRESSIVE") choice = input("Continue? (Y/N) ").upper() if (choice == "Y"): loop = 2 elif (choice == "N"): loop = 0
print("hello world") n = input("DOB please ") print(n) print("your age:",2018-n)
from flask import Flask, jsonify, request,render_template import sqlite3 as sql con=sql.connect('user_database.db') con.execute('CREATE TABLE IF NOT EXISTS User (ID INTEGER PRIMARY KEY AUTOINCREMENT,' + 'username TEXT, password TEXT)') con.execute('CREATE TABLE IF NOT EXISTS SavedPass (ID INTEGER PRIMARY KEY AUTOINCREMENT,' + 'userId TEXT,website TEXT, password TEXT)') con.close() # creating a Flask app app = Flask(__name__) @app.route('/signuppage') def signuppage(): return render_template('signup.html') @app.route('/loginpage') def loginpage(): return render_template('login.html') @app.route('/savesite') def savepage(): return render_template('savesite.html') @app.route('/app/user',methods=['POST']) def signup(): username=request.form['username'] password=request.form['password'] print(username,password) try: con = sql.connect('user_database.db') c = con.cursor() # cursor print(username,password) query="INSERT INTO User (username,password) VALUES ('{0}','{1}')".format(username,password) print(query) c.execute(query) con.commit() return "account created" except con.Error as err: # if error return "account can't be created" finally: con.close() # close the connection @app.route('/app/user/auth',methods=['POST']) def login(): username=request.form['username'] password=request.form['password'] try: con = sql.connect('user_database.db') c = con.cursor() # cursor print("yaha aaya kya") query="Select * from User where username='{0}';".format(username) print(query) c.execute(query) print("yaha bhui aata kya") row=c.fetchone() print(row) if row==None: return "username not found" con.commit() # apply changes if row[1]==username and row[2]==password: return jsonify({'status':'success',"userId":row[0]}) except con.Error as err: # if error return "account can't be created" finally: con.close() # close the connection @app.route('/app/sites/:userId',methods=['POST']) def saveWebsite(): website=request.form['website'] username=request.form['username'] password=request.form['password'] try: con = sql.connect('user_database.db') c = con.cursor() # cursor print(username,password,website) query1="Select * from User where username='{0}'".format(username) print(query1) c.execute(query1) row=c.fetchone() if row!=None: print(row) query="INSERT INTO SavedPass (userId,website,password) VALUES ('{0}','{1}','{2}')".format(row[0],website,password) print(query) c.execute(query) con.commit() return jsonify({'status':'success'}) return "Error" except con.Error as err: # if error return "Error" finally: con.close() # close the connection @app.route('/app/sites/list/<int:userId>',methods=['GET']) def listSites(userId): #userId=request.args.get('') try: con = sql.connect('user_database.db') c = con.cursor() # cursor print(userId) query1="Select * from SavedPass where userId='{0}'".format(userId) print(query1) c.execute(query1) row=c.fetchall() if row!=None: return jsonify(row) return "Error" except con.Error as err: # if error return "Error" finally: con.close() # close the connection if __name__ == '__main__': app.run(debug = True)
def speeding(x): if x <= 50: return "Pass" elif x <= 55: return "10 euros" elif x <= 60: return "20 euros" elif x <= 65: return "30 euros" elif x <= 70: return "40 euros" elif x <= 75: return "50 euros" elif x <= 80: return "60 euros" else: return "Goodbye License" boete = speeding(40) print(boete)
# def foo(*args): # # for a in args: # # a = a.upper() # # print(a) # print(f"the type of args is {type(args)}") # print(*args, sep = "------") # print("a", "b", "c", "d", sep = "------") # foo("a", "b", "c", "d") # # def sum_elements(*elements): # sum_ = 0 # for e in elements: # sum_ += e # # return sum_ # # print(sum_elements(1, 2, 3, 4)) # # name_tuple = ("Nikita", "Max", "Armen", "Narek") # print(*name_tuple, sep = "\n") # def foo(name, *args): # for a in args: # a = a.upper() # print(a) # print(f"the type of args is {type(args)}") # print(*args, sep = "------") # print("a", "b", "c", "d", sep = "------") # # # foo("name") # foo() # number = input("tell me the number and see the half of it\n") # try: # number = int(number) # except ValeError: # print("this is not a number so you'll get 0") # number = 0 # half = number/2 # print(half) # number = input("tell the number and I'll return the half of it: ") # try: # half = float(number) # except ValueError: # print("print only numbers") # except ValueError: # num_1 = int(input("tell me number only number")) from typing import Type password = input("tell the password! ") try: if len(password) < 8: raise ValueError("at least 8 symbols ") check = True for i in password: if i.isalpha() and i.isupper(): check = False if check: raise TypeError("Password should contain at least one uppercase character: ") check_symbols = True for i in password: if not i.isaplpha() and not i.isdigit() and i != " ": break else: raise TypeError("password should contain at least one symbol") except: pass
#ex1 before_ = [17, 11, 17, 11, 23, 7] after_ = [] for i in before_: if i not in after_: after_.append(i) print(after_) #ex1.1 frst = [10, 12, 36, 44, 77, 85, 113, 231, 344, 4655, 789] scnd = [10, 12, 35, 45, 77, 85, 113, 231, 340, 4655, 789, 2, 6] res = [] for i in frst: if i in scnd and i not in res: res.append(i) print(res) #ex 2 divisors = [10, 12, 36, 44, 77, 85, 113, 231, 344, 4655, 789] res = [] for i in divisors: if i % 5 == 0: res.append(i) print(res) #ex3 txt = input("enter any text: ") def function(name): x = txt.split() res = x[::-1] return res print(function(txt)) #ex4 my_tuple = ("armen", 16, "Muradyan") print(my_tuple[::-1]) #ex5 my_list = ["armen", True, 0, False, "Hello", 34, 35.5, 3.3] str_ = [] bool_ = [] int_ = [] float_ = [] for i in my_list: if type(i) == str: str_.append(i) elif type(i) == bool: bool_.append(i) elif type(i) == int: int_.append(i) elif type(i) == float: float_.append(i) print(str_) print(int_) print(float_) print(bool_) #ex6?
import random computer_random = [1, 2, 3, 4, 5, 6, 7, 8, 9] board = ["_","_","_", "_","_","_", "_","_","_",] def board_function(): print(board[0] + "|" + board[1] + "|" + board[2]) print(board[3] + "|" + board[4] + "|" + board[5]) print(board[6] + "|" + board[7] + "|" + board[8]) def gamer_choose(): x_or_o = input("X or O?, 1-X 2-O\n") if x_or_o == "1": pos = input("Choose a position from 1-9\n") pos = int(pos) - 1 random_O = random.choice(computer_random) board[pos] = "X" if random_O != pos: board[random_O-1] = "O" print(f"computer choise = {random_O}") elif x_or_o == "2": pos = input("Choose a position from 1-9\n") pos = int(pos) - 1 board[pos] = "O" random_X = random.choice(range(1,10)) print(random_X) board_function() gamer_choose()
# print("Fahrenheit to celsus converter") # fahrenheit = input("set the weather in fahrenheit: ") # celsus = (int(fahrenheit) - 32) * 0.5556 # print(f"The weather in celsus is {celsus}") # menu = input("What you want, pizza or Kebab? 1 for pizza(1500) 2 for kebab(1000)\n") # sauce = input("Do you want any sauces, Ketchup or Mayo? 1 for ketchup(500) 2 for Mayo(700), 3 if you don't want\n") # if menu == "1" and sauce == "1": # print("You ordered Pizza with ketchup: Price - 2000") # elif menu == "1" and sauce == "2": # print("You ordered Pizza with Mayo: Price - 2200") # elif menu == "2" and sauce == "1": # print("You ordered Kebab with ketchup: Price - 1500") # elif menu == "2" and sauce == "2": # print("You ordered Kebab with Mayo: Price - 1700") # elif menu == "1" and sauce == "3": # print("You orderef only pizza: Price 1500") # elif menu == "2" and sauce == "3": # print("You orderef only Kebab: Price 1000") # else: # print("wrong") # kilometers = int(input("set the distance in kilometers\n")) # miles = int(kilometers / 1.609) # print(f"{kilometers} kilometers is {miles} miles") # from repeatbase import amd_dollar # from repeatbase import ruble_dollar # choise_ = input("choise the value, dram or ruble:1 for dram 2 for ruble\n") # if choise_ == "1": # amount = int(input("enter the amount: ")) # print(int(amd_dollar * amount)) # elif choise_ == "2": # amount = int(input("enter the amount: ")) # print(int(ruble_dollar * amount))
import pandas as pd filedata = 'data.csv' #Read File : data = pd.read_csv(filedata) #Make an object out of an object: data_Age = data["Age"] #Make a list from object of data["Age"] from object of data: # data_Age = data["Age"].tolist() #Use python to find out how many players' age equal and over 30: # A = [] # for i in range(len(data_Age)): # if data_Age[i] >= 30: # A.append(data_Age[i]) # print (len(A)) #Shorter verion of the operation above: # B = 0 # for i in range(len(data_Age)): # if data_Age[i] >= 30: # B += 1 # print (B) #print how many columns and how many row in each column (does not count cell without any values) # print (data.count()) #print how many row in columns Age # print (data_Age.count()) #given the condition of Age >= 30, find out how many players in data file using SQL: #This SQL count include every columns counts # print ((data[data.Age >= 30]).count()) #Using SQL to count: First select only column Age (of table data) where Age >= 30, then start counting #For this SQL count, have to decide which column , which condition first to narrow the result, then using index of #data file to start counting. # print ((data[data.Age >= 30])["Age"].count()) ######################## #which player under 30 get paid the most? #Remember: to strip an object, we use .item() #SELECT Name #From data #Where Age < 30 #Order by Salary DESC, #Limit 1 # print (data[data.Age < 30].sort_values('Value',ascending = False)["Name"][0:1].item()) ######################### #which player has the most potential but get paid the least? #SELECT Name #From data #Order by Potential DESC, Wage #Limit 1 # print (data.sort_values((["Wage"],descending=False))(["Potential"], ascending=False)) # sorted = data.sort_values(by=['Potential', 'Wage'], ascending=[False, True])[0:1]["ID"].item() # print(sorted) sorted2 = data.sort_values(by=['Potential', 'Wage'], ascending=[False, True])[0:2]["Name"] print(sorted2)
"""Snake Game Python Tutorial youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo current time: 33:00 """ import sys import math import random import pygame from pygame.locals import * import tkinter as tk from tkinter import messagebox WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) class cube(object): """ """ rows = 20 #set number of rows w = 500 #set pixel screen width def __init__(self,start,dirnx=1,dirny=0,color=RED): self.pos = start self.dirnx = 1 self.dirny = 0 self.color = color def move(self,dirnx,dirny): """ move cube, by adding new direction to previous position """ self.dirnx = dirnx self.dirny = dirny self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny) def draw(self,surface,eyes=False): """ drawing: convert x,y grid position to pixel position """ dis = self.w // self.rows #distance between x and y values #variables for easy coding i = self.pos[0] # row j = self.pos[1] # column #draw just a little bit less, so we draw inside of the square. and we dont cover grid. pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 )) #draw eyes if eyes: centre = dis//2 radius = 3 circleMiddle = (i*dis+centre-radius, j*dis+8 ) #eye 1 circleMiddle2 = (i*dis+dis-radius*2, j*dis+8 ) #eye 2 pygame.draw.circle(surface, BLACK, circleMiddle, radius) pygame.draw.circle(surface, BLACK, circleMiddle2, radius) class snake(object): """ class for snake """ body = [] #list of cube objects turns = {} #dictionary of turns ADDING A KEY OF--> # key = current position of snake head # value = direction of turn] def __init__(self,color,pos): self.color = color self.head = cube(pos) self.body.append(self.head) # snake starts with one cube = head self.dirnx = 0 #direction moving x 1, -1 self.dirny = 1 #direction moving y 1, -1 def move(self): """ moving our snake in x,y thinking LEFT (self.dirnx=-1, self.dirny=0) RIGHT (self.dirnx=1, self.dirny=0) UP (self.dirnx=0, self.dirny=1) DOWN (self.dirnx=0, self.dirny=-1) """ for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_LEFT]: self.dirnx = -1 self.dirny = 0 # we mustremember where we turned, so other cubes can follow # add a new key #example - here we turned in thar way self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_RIGHT]: self.dirnx = 1 self.dirny = 0 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_UP]: self.dirnx = 0 self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirnx = 0 self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] #look trough all position of snake #we get the index=i and the cube=c of body for i, c in enumerate(self.body): p = c.pos[:] #for each of the sube, we grab position and check turn #if this position in turns, than we move if p in self.turns: turn = self.turns[p] #here we store direction where to move c.move(turn[0],turn[1]) #if we are on the last cube of the snake, remove the turn, we finished it if i == len(self.body)-1: self.turns.pop(p) else: #CHECK IF WE REACHED EDGE OF THE SCREEN #if MOVE LEFT & we are at the left side of screen if (c.dirnx == -1) and (c.pos[0] <= 0): c.pos = (c.rows-1,c.pos[1]) #c.pos = (c.rows-1,c.pos[1]) #if MOVE RIGHT & we are at the left side of screen elif (c.dirnx == 1) and (c.pos[0] >= c.rows-1): c.pos = (0,c.pos[1]) #if MOVE DOWN & we are at the left side of screen elif (c.dirny == 1) and (c.pos[1] >= c.rows-1): c.pos = (c.pos[0],0) #if MOVE UP & we are at the left side of screen elif (c.dirny == -1) and (c.pos[1] <= 0): c.pos = (c.pos[0],c.rows-1) #normal move of cube else: c.move(c.dirnx,c.dirny) def reset(self,pos): pass def addCube(self): pass def draw(self,surface): for index, cube in enumerate(self.body): #check where to draw eyes for snake head if index == 0: cube.draw(surface,True) #with eyes else: cube.draw(surface,False) #without eyes def drawGrid(w,rows,surface): """ This function draws a square grid on main display """ #distance between grid lines sizeBtwn = w // rows x = 0 y = 0 #create grid by drawing lines for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn #vertical lines pygame.draw.line(surface, WHITE, (x,0), (x,w)) #horizontal lines pygame.draw.line(surface, WHITE, (0,y), (w,y)) def redrawWindow(surface): global rows, width, s #background surface.fill(BLACK) s.draw(surface) #draw grid drawGrid(width, rows, surface) #update display pygame.display.update() def randomSnack(rows,items): pass def message_box(subject,content): pass def key_events(): pass #directions = {"right":(1,0), "left":(0,-1), "up":(0,-1), "down":(0,1)} def main(): global width, rows, s #create game display width = 500 rows = 20 win = pygame.display.set_mode((width, width)) #square display #snake start position s = snake(color=RED, pos=(10,10)) clock = pygame.time.Clock() flag = True FPScount = 0 print(FPScount) while flag: #pygame.time.delay(50) clock.tick(10) #game max speed 10 FPS s.move() redrawWindow(win) FPScount += 1 print(f'FPScount:{FPScount}') #rows = 0 #w = 0 #h = 0 #cube.rows = rows #cube.w = w main() pygame.quit() sys.exit()
print("type (q) = Exit") while True: user_input = input("type input") if user_input == "q": break print(user_input)
# -*- coding: utf-8 -*- """ There are six steps to making text appear on the screen: 1. Create a pygame.font.Font object. 2. Create a Surface object with the text drawn on it by calling the Font object’s render() method. 3. Create a Rect object from the Surface object by calling the Surface object’s get_rect() method. This Rect object will have the width and height correctly set for the text that was rendered, but the top and left attributes will be 0. 4. Set the position of the Rect object by changing one of its attributes. On line 15, we set the center of the Rect object to be at 200, 150. 5. Blit the Surface object with the text onto the Surface object returned by pygame.display.set_mode(). 6. Call pygame.display.update() to make the display Surface appear on the screen. """ import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Hello World!') FPS = 30 # frames per second setting fpsClock = pygame.time.Clock() WHITE = (255, 255, 255) GREEN = (0, 255, 0) BLUE = (0, 0, 128) fontObj = pygame.font.Font('freesansbold.ttf', 32) textSurfaceObj = fontObj.render('Hello world!', True, GREEN, BLUE) textRectObj = textSurfaceObj.get_rect() textRectObj.center = (200, 150) while True: # main game loop DISPLAYSURF.fill(WHITE) DISPLAYSURF.blit(textSurfaceObj, textRectObj) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() # must be called after display.update fpsClock.tick(FPS)
""" Jumping and variables video: https://www.youtube.com/watch?v=2-DNswzCkqk&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5&index=2 1. constraing are where we can move 2. jumping IF JUMPING: dont move left right """ import pygame from pygame.locals import * from rgb_color_dictionary import * pygame.init() #create window win = pygame.display.set_mode((500,500)) #set windows title pygame.display.set_caption("First Game") #character variables x = 50 y = 50 width = 40 height = 60 vel = 20 isJump = False jumpCount = 10 #clock=pygame.time.Clock() #main game loop run = True while run: pygame.time.delay(100) #this will be a clock for the game keys = {'left':False,'right':False, 'up':False, 'down':False} for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False vx = 0 vy = 0 keystate = pygame.key.get_pressed() #straight moves with screen constraints #cant move up if keystate[pygame.K_UP] and y > vel: vy = -vel #cant move down if keystate[pygame.K_DOWN] and y < 500 - height - vel: vy = vel if not isJump: #cant move off the left screen border if keystate[pygame.K_LEFT] and x > vel: vx = -vel #cant move off the right screen border if keystate[pygame.K_RIGHT] and x < 500 - width - vel: vx = vel #-----------------jump--------------- if keystate[pygame.K_SPACE]: isJump = True else: if jumpCount >= -10: # we jump for 10 pixels neg = 1 if jumpCount < 0: #when we get to the top of jump neg = -1 y -= (jumpCount ** 2) * 0.5 * neg jumpCount -= 1 else: isJump = False jumpCount = 10 #diagonals must be slower for sq(2)= 1.414 pitagora if vx != 0 and vy != 0: vx /= 1.414 vy /= 1.414 x += vx y += vy #draw rectangle win.fill(BLACK) pygame.draw.rect(win,RED,(x,y,width,height)) pygame.display.update()
import pygame pygame.init() #---------display------------- display_width = 800 display_height = 600 #color var black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) gameDisplay = pygame.display.set_mode((display_width,display_height)) #set title pygame.display.set_caption('Race Game') clock = pygame.time.Clock() carImg = pygame.image.load('race_car_transp_v2.png') #function to display a car def car(x,y): gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface x = display_width*0.45 y = display_height*0.8 #for computers (x=0,y=0) is top left corner #------------main game loop--------- chrashed = False while not chrashed: for event in pygame.event.get(): if event.type == pygame.QUIT: chrashed = True #------------------------------------ #first draw background, dont paint over car gameDisplay.fill(white) car(x,y) pygame.display.update() clock.tick(60) #------------------------------------ pygame.quit() quit()
# -*- coding: utf-8 -*- """ Created on Sun Dec 27 16:29:01 2020 @author: crtom https://www.youtube.com/watch?v=Qdeb1iinNtk&list=PLX5fBCkxJmm1fPSqgn9gyR3qih8yYLvMj&index=2 Pygame Tutorial - Making a Platformer ep. 2: Images, Input, and Collisions """ import sys import pygame from pygame.locals import* import random #from settings import * import time import math from gameobjects.vector2 import Vector2 from RGB import * WIDTH, HEIGHT = 400, 400 # initialize pygame and create a window pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Platformer") #all_sprites = pygame.sprite.Group() # create background background = pygame.Surface((WIDTH, HEIGHT)) background.fill(WHITE) screen.blit(background, (0,0)) # create player image player_image = pygame.Surface((50, 50)) player_image.fill(BLACK) player_pos = Vector2(200, 150) player_speed = 300 screen.blit(player_image, (player_pos.x, player_pos.y)) # game loop clock = pygame.time.Clock() running = True while running: # process input (events) for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False pressed_keys = pygame.key.get_pressed() key_direction = Vector2(0, 0) if pressed_keys[K_LEFT]: key_direction.x = -1 elif pressed_keys[K_RIGHT]: key_direction.x = +1 if pressed_keys[K_UP]: key_direction.y = -1 elif pressed_keys[K_DOWN]: key_direction.y = +1 key_direction.normalize() time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 #---------- player_pos += key_direction * player_speed * time_passed_seconds # draw/render screen.blit(background, (0,0)) #all_sprites.draw(screen) # screen.blit(player_image, (50, 50)) screen.blit(player_image, (player_pos.x, player_pos.y)) # after drawing everything, flip the display pygame.display.update() pygame.quit()
import math class Vector2: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "(%s, %s)"%(self.x, self.y) def from_points(P1, P2): return Vector2( P2[0] - P1[0], P2[1] - P1[1] ) def get_magnitude(self): return math.sqrt( self.x**2 + self.y**2 ) def normalize(self): magnitude = self.get_magnitude() self.x /= magnitude self.y /= magnitude def __add__(self, rhs): return Vector2(self.x + rhs.x, self.y + rhs.y) def __sub__(self, rhs): return Vector2(self.x - rhs.x, self.y - rhs.y) def __neg__(self): return Vector2(-self.x, -self.y) def __mul__(self, scalar): return Vector2(self.x * scalar, self.y * scalar) def __truediv__(self, scalar): return Vector2(self.x / scalar, self.y / scalar) A = (10.0, 20.0) B = (30.0, 35.0) AB = Vector2.from_points(A, B) step = AB * .1 position = Vector2(*A) for n in range(10): position += step print(position)
keys_list = [1, 2, 3, 4, 5, 6] values_list = ['Paul', 'Oxana', 'Angelina', 'Katerine', 'Maxime', 'asdasd', 2123, 12] result_dict = { } def dict_from_keys(keys, values): return dict(zip(keys, values + [None] * (len(keys) - len(values)))) print(dict_from_keys(keys_list, values_list))
import pandas as pd trials = pd.read_csv('/Users/apple/desktop/manipulatingDataFrames/dataset/trials_01.csv') print(trials) trials = trials.set_index(['treatment', 'gender']) print(trials) # NOTE: pivot cant work because of multi index # unstack a multi-index(1) unstack = trials.unstack(level='gender') # NOTE: level refers to the layer of index, here we unstack 1 layer print(unstack) # unstack a multi-index(2) | the result is the same as above trial_by_gender = trials.unstack(level=1) print(trial_by_gender) # stack: make a wide df thinner and longer print(trial_by_gender.stack(level='gender')) # NOTE: gender level is the innermost level # NOTE: the result is the same as when we set_index() # swaplevel() method: swap the inner and outer index level stacked = trial_by_gender.stack(level='gender') swapped = stacked.swaplevel(0,1) # NOTE: swap the first and second level print(swapped) sorted = swapped.sort_index() print(sorted)
def gcd(a,b): if a==0: return b else: return gcd(b%a,a) print(gcd(35,15))
t=int(input()) if t==2: print('NO') else: if t%2==0: print('YES') else: print('NO')
import csv def parse_csv(input_file): with open(input_file, "r") as f: reader = csv.reader(f, delimiter=",") for i, line in enumerate(reader): if i == 0: continue #Skip the header yield line
import unittest from operator import itemgetter, attrgetter class Person: def __init__(self, first_name: str, last_name: str, age: int): self.first_name = first_name self.last_name = last_name self.age = age class People: def __init__(self, *people: Person): self.people = people def add_person(self, person: Person): self.people += (person,) def by_age_desc(self): return sorted(self.people, key=attrgetter('age'), reverse=True) def by_age_asc(self): return sorted(self.people, key=attrgetter('age')) def by_last_name(self): return sorted(self.people, key=attrgetter('last_name', 'first_name')) def vowel_count(some_string: str) -> int: c = 0 for character in some_string: if character in 'aeiouAEIOU': c += 1 return c class SortedTest(unittest.TestCase): def test_it_sorts(self): self.assertEqual([1, 2, 3, 4, 5], sorted([5, 4, 3, 2, 1])) def test_list_sort(self): my_list = [5, 4, 3, 2, 1] s = sorted(my_list) my_list.sort() self.assertEqual(s, my_list) def test_it_sorts_keys(self): my_dict = {3: 'Foo', 2: 'Bar', 1: 'Zoo'} self.assertEqual([1, 2, 3], sorted(my_dict)) my_dict = {'first_name': 'Dick', 'last_name': 'Brouwers'} self.assertEqual(['first_name', 'last_name'], sorted(my_dict)) my_list = ['Talitha', 'Jackie', 'Dick'] self.assertEqual(['Dick', 'Jackie', 'Talitha'], sorted(my_list)) my_list = ['Talitha', 'jackie', 'dick'] self.assertEqual(['dick', 'jackie', 'Talitha'], sorted(my_list, key=str.lower)) def test_it_sorts_complex_structures(self): talitha = {'first_name': 'Talitha', 'last_name': 'Ringers', 'age': 41} dick = {'first_name': 'Dick', 'last_name': 'Brouwers', 'age': 54} jackie = {'first_name': 'Jackie', 'last_name': 'Brouwers', 'age': 11} people = [jackie, talitha, dick] people_ordered_by_first_name = sorted(people, key=lambda person: person['first_name']) self.assertEqual([dick, jackie, talitha], people_ordered_by_first_name) people_ordered_by_age = sorted(people, key=lambda person: person['age']) self.assertEqual([jackie, talitha, dick], people_ordered_by_age) people_ordered_by_last_name_and_first_name_secondly = sorted(people, key=itemgetter('last_name', 'first_name')) self.assertEqual([dick, jackie, talitha], people_ordered_by_last_name_and_first_name_secondly) def test_it_sorts_objects(self): dick = Person('Dick', 'Brouwers', 54) jackie = Person('Jackie', 'Brouwers', 11) talitha = Person('Talitha', 'Ringers', 41) people = People() people.add_person(dick) people.add_person(jackie) people.add_person(talitha) self.assertEqual([dick, talitha, jackie], people.by_age_desc()) self.assertEqual([jackie, talitha, dick], people.by_age_asc()) self.assertEqual([dick, jackie, talitha], people.by_last_name()) def test_it_counts_vowels(self): self.assertEqual(12, vowel_count('itCountsTheNumberOfVowelsInAString')) def test_it_sorts_by_highest_number_of_vowels(self): self.assertEqual(['foobar', 'foo', 'yo'], sorted(['foobar', 'yo', 'foo'], key=vowel_count, reverse=True)) self.assertEqual(['yo', 'foo', 'foobar'], sorted(['foobar', 'yo', 'foo'], key=vowel_count)) def test_it_sorts_by_absolute_value(self): self.assertEqual([1, -2, -3, 4], sorted([-3, -2, 1, 4], key=abs)) def test_it_sorts_by_the_sum_of_each_inner_lists_numbers(self): sequence = [[4, 5, 6], [1, 2, 3], [7, 8, 9]] expected = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] self.assertEqual(expected, sorted(sequence, key=sum))
with open('/usr/share/dict/words') as word_list: vowels = {'a', 'e', 'i', 'o', 'u'} for w in (word.strip() for word in word_list if vowels < set(word)): print(w)
import unittest def hex_to_int(v: str) -> int: result = 0 for power, val in enumerate(reversed(v)): result += int(val, 16) * (16 ** power) return result def hex_to_int_two(v: str) -> int: result = 0 for power, val in enumerate(reversed(v)): result += (convert_single_char(val) * (16 ** power)) return result def convert_single_char(c: str) -> int: result = ord(c) if result > 56: return result - 87 return (result - 48) class TestHexaDecimalOutput(unittest.TestCase): def test_hexa_decimal_output(self): self.assertEqual(64, hex_to_int('40')) self.assertEqual(64, hex_to_int_two('40')) # print(hex_to_int_two('60')) # print(hex_to_int_two('c')) # print(hex_to_int('50')) # print(hex_to_int_two('50')) print(hex_to_int('40')) print(hex_to_int_two('40')) print(hex_to_int('555')) print(hex_to_int_two('555')) print(hex_to_int('1234')) print(hex_to_int_two('1234')) # print(hex_to_int('30')) # print(hex_to_int('20')) # print(hex_to_int('10'))
import unittest class User: def __init__(self, name: str, secret: str): self.name = name self.secret = secret class UserRepository: __users = {} def __init__(self, *users: User): for user in users: self.save(user) def save(self, user: User): self.__users.update({user.name: user}) def find(self, name: str) -> User: if name not in self.__users.keys(): raise Exception return self.__users.get(name) class UserService: def __init__(self, repository: UserRepository): self.__repository = repository def login(self, name: str, secret: str) -> bool: try: user = self.__repository.find(name) except Exception: return False return user.secret is secret class LoginTestCase(unittest.TestCase): def test_login_with_username_and_password(self): repository = UserRepository(User('dick', 'secret'), User('foo', 'bar')) user_service = UserService(repository) self.assertTrue(user_service.login('dick', 'secret')) self.assertTrue(user_service.login('foo', 'bar'))
x = 41 def iseven(x): if x % 2 == 0: print "even" else: print "odd" return " " print "Number x = ", x, " is even? ", iseven(x) def size2digits(x): if x < 10 == 0: print "one digit" elif x < 100: print "two digits" else: print "too much digits" return "" print "Number = ", x, " size = ", size2digits(x) print "Number = 123 size = ", size2digits(123)
# -*- coding: utf-8 -*- """ Created on Sun Jan 04 21:18:01 2015 @author: tianyi """ def fib(n): if n == 1 or n == 2: return 1 else: return fib(n - 1) + fib(n - 2) n = int(raw_input('input n:')) for i in range(1,11): if fib(i) < n: print i, fib(i)
# -*- coding: utf-8 -*- """ Created on Sun Jan 04 21:27:40 2015 @author: tianyi """ def hanoi(n, A, B, C): if n == 1: print "move", n, 'from', A, 'to', C #移动过程 return 1 else: count = hanoi(n - 1, A, C, B) #将前 n-1 个盘子, 通过 C, 从 A 移动到 B print 'move', n,'from', A, 'to', C #移动过程 只剩一个盘子 count += 1 count += hanoi(n - 1, B, A, C) # 将前 n-1 个盘子, 通过 A, 从 B 移动到 C return count if __name__ == '__main__': x = int(raw_input('input x:')) count = hanoi(x, 'left', 'mid' , 'right' ) print 'total steps:', count
# -*- coding: utf-8 -*- """ Created on Sat Jan 03 00:33:36 2015 @author: tianyi """ x = float(raw_input("please input x:")) low = 0 high = x guess = (low + high) / 2 while abs(guess ** 2 - x) > 1e-5: if guess ** 2 < x: low = guess else: high = guess guess = (low + high) / 2 print guess
from animal import Animal class Reptile(Animal): # Inheriting from animal class def __init__(self): # note the (self), if this is missing it can cause errors, check for this in exam super().__init__() # super is used to inherit everything from the parent class, this may come up in the exam self.cold_blooded = True self.tetrapods = None self.heart_chambers = [3, 4] def seek_heat(self): return "It's chilly looking have fun in the sun" def hunt(self): return "Keep working hard to find food" def use_venom(self): return "If I have it I will use it" # Let's create an object of Reptile class # smart_reptile = Reptile() # print(smart_reptile.breathe()) # breathe method is inherited from Animal class # print(smart_reptile.hunt()) # hunt() is available in Reptile class # print(smart_reptile.eat()) # print(smart_reptile.move()) # print(smart_reptile.hunt())
''' DFS ''' import collections from typing import List def word_numbers(input): "iterate on current element and each time keep append to your previos result" digit_map = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz', } input = str(input) ret = [''] for char in input: letters = digit_map.get(char, '') res = [] for letter in letters: for prefix in ret: res.append(prefix + letter) ret = res return ret def island(): """ Outer two for loops will iterate and find results. checker function will keep resetting values marking visited node to 0 and traverse in all direction :return: """ grid = [ ["1", "1", "0", "0", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "1", "0", "0"], ["0", "0", "0", "1", "1"] ] def dfs(): rows = len(grid) cols = len(grid[0]) count = 0 for i in range(0, rows): for j in range(0, cols): if grid[i][j] == '1': check_valid(i, j, grid) count = count + 1 return count def check_valid(i, j, grid=None): rows = len(grid) cols = len(grid[0]) if not 0 <= i < rows or not 0 <= j < cols or grid[i][j] != '1': return grid[i][j] = '0' check_valid(i + 1, j, grid) check_valid(i - 1, j, grid) check_valid(i, j + 1, grid) check_valid(i, j - 1, grid) return dfs() def wordsearch(): board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]] def exist(board: List[List[str]], word: str) -> bool: idx = 0 result = [] for i in range(len(board)): for j in range(len(board[i])): if board[i][j] is not None and board[i][j] in word: check_valid(i, j, board, word, result, idx) return ''.join(result) == word def check_valid(i, j, board, word, result, idx): if (not 0 <= i < len(board) or not 0 <= j < len(board[0]) or board[i][j] is None or idx >= len(word) or board[i][j] != word[idx] or ''.join(result) == word): return False print(f"word index at {idx} Char at {i}, {j}: {board[i][j]}, result is {result}") result.append(board[i][j]) board[i][j] = None check_valid(i + 1, j, board, word, result, idx + 1) check_valid(i - 1, j, board, word, result, idx + 1) check_valid(i, j + 1, board, word, result, idx + 1) check_valid(i, j - 1, board, word, result, idx + 1) return True exist(board, 'SFCS') def splitword(): def numSplits(s: str) -> int: """ Input: s = "aacaba" Output: 2 Explanation: There are 5 ways to split "aacaba" and 2 of them are good. ("a", "acaba") Left string and right string contains 1 and 3 different letters respectively. ("aa", "caba") Left string and right string contains 1 and 3 different letters respectively. ("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aacab", "a") Left string and right string contains 3 and 1 different letters respectively. :param s: :return: """ left_count = collections.Counter() right_count = collections.Counter(s) res = 0 for c in s: left_count[c] += 1 right_count[c] -= 1 if right_count[c] == 0: del right_count[c] if len(left_count) == len(right_count): res += 1 return res class Node: def __init__(self, start, end): self.right = self.left = None self.start = start self.end = end def insert(self, node) -> bool: if node.start >= self.end: if not self.right: self.right = node return True else: self.right.insert(node) elif node.end <= self.start: if not self.left: self.left = node return True else: self.left.insert(node) else: return False class MyCalendar(object): def __init__(self): self.root = None def book(self, start, end): if self.root is None: self.root = Node(start, end) return True return self.root.insert(Node(start, end)) class TimeMap(object): def __init__(self): self.dic = collections.defaultdict(list) def set(self, key, value, timestamp): self.dic[key].append([timestamp, value]) def get(self, key, timestamp): arr = self.dic[key] n = len(arr) left = 0 right = n while left < right: mid = (left + right) / 2 if arr[mid][0] <= timestamp: left = mid + 1 elif arr[mid][0] > timestamp: right = mid return "" if right == 0 else arr[right - 1][1] class SnapshotArray: def __init__(self, length): self.id = -1 self.items = [] self.dict_map = {} def set(self, index, val): self.dict_map[index] = val def snap(self): self.items.append(self.dict_map) self.dict_map = self.dict_map.copy() self.id += 1 return self.id def get(self, index, snap_id): try: d = self.items[snap_id] return d[index] except KeyError: return 0 sanpshotArr = SnapshotArray(3) print(sanpshotArr.set(0, 5),sanpshotArr.snap(),sanpshotArr.set(1, 6),sanpshotArr.get(0, 0))
from collections import deque # Node class for holding the Binary Tree class TreeNode: def __init__(self, data=None): self.val = data self.left = None self.right = None self.next = None def __str__(self): return (f" {self.val}") class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None Q = deque() # Helper function helps us in adding data # to the tree in Level Order def insertValue(data, root): newnode = TreeNode(data) if Q: temp = Q[0] if root == None: root = newnode # The left child of the current Node is # used if it is available. elif temp.left == None: temp.left = newnode # The right child of the current Node is used # if it is available. Since the left child of this # node has already been used, the Node is popped # from the queue after using its right child. elif temp.right == None: temp.right = newnode atemp = Q.popleft() # Whenever a new Node is added to the tree, # its address is pushed into the queue. # So that its children Nodes can be used later. Q.append(newnode) return root # Function which calls add which is responsible # for adding elements one by one def createTree(a, root): for i in range(len(a)): root = insertValue(a[i], root) return root # Function for printing level order traversal def levelOrder(root): Q = deque() Q.append(root) while Q: temp = Q.popleft() print(temp.val, end=' ') if temp.left != None: Q.append(temp.left) if temp.right != None: Q.append(temp.right)
from collections import defaultdict class Trie: def __init__(self): self._end = '_end_' self.root = defaultdict(dict) def make_trie(self, *words): for word in words: current_dict = self.root for letter in word: current_dict = current_dict.setdefault(letter, {}) current_dict[self._end] = self._end return self.root def in_trie(self, trie, word): current_dict = trie for letter in word: if letter not in current_dict: return False current_dict = current_dict[letter] return self._end in current_dict t= Trie() x = t.make_trie('foo', 'bar', 'baz', 'barz') print(t.in_trie(x, 'bard'))
led.on() if (number != 10): # != resend key if (number < 10): self.input_string += str(number) elif (number == 14 or number == 15): # confire button try: self.state += 1 if (self.state == 0): self.task_number_from_keypad = int(self.input_string) self.input_string = "" if (self.state == 1): self.paramater_list[0] = int(self.input_string) self.input_string = "" if (self.state == 2): self.paramater_list[1] = int(self.input_string) self.input_string = "" if (self.state == 3): self.paramater_list[2] = int(self.input_string) self.input_string = "" if (self.state > 3): return except Exception as e: self.state = -1 self.input_string = "" self.paramater_list = [254, 254, 254] self.task_number_from_keypad = 0 elif (number == 11 or number == 12 or number == 13): # cancle button self.state = -1 self.input_string = "" self.paramater_list = [254, 254, 254] self.task_number_from_keypad = 0 # send data according to different task if (self.task_number_from_keypad != 0): send_signal(self.task_number_from_keypad, data=[self.paramater_list[0], self.paramater_list[1], self.paramater_list[2]]) print("key:", number, "task:", self.task_number_from_keypad, "p:", self.paramater_list) sleep_ms(150) led.off()
# Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ intervals.append(newInterval) intervals.sort(key=lambda x: x.start) res = [] for interval in intervals: if not res: res.append(interval) else: if res[-1].start <= interval.start <= res[-1].end: res[-1].end = interval.end if res[-1].end <= interval.end else res[-1].end else: res.append(interval) return res
class SimplifyPath(object): def simplifyPath(self, path): """ :param path: str :return: str tips: "/"->root directory ".."->upper directory "."->current_directory """ subDirectories = path.split('/') cur = '/' for subDirectory in subDirectories: if subDirectory == '..': if cur != '/': cur = cur[:cur.rfind('/')] if cur == '': cur = '/' elif subDirectory != '.' and subDirectory != '': cur += '/' + subDirectory if cur != '/' else subDirectory return cur
class FindSubstring(object): def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ dict = {} num = len(words) length = len(words[0]) res = [] for word in words: if word not in dict: dict[word] = 1 else: dict[word] += 1 # total number of possible combinations of all words for i in xrange(len(s)+1-num*length): curr = {} j = 0 while j < num: word = s[i+j*length:i+(j+1)*length] if word not in dict: break if word not in curr: curr[word] = 1 else: curr[word] += 1 if curr[word] > dict[word]: break j += 1 if j == num: res.append(i) return res if __name__ == '__main__': tb = FindSubstring() print tb.findSubstring("cbabcabcabcbacbabbcababcbacbab", ["a", "b", "c"])
class CountAndSay(object): def countAndSay(self, n): if n == 1: return '1' else: preSay = self.countAndSay(n - 1) say, tmp, count, = '', preSay[0], 0 for char in preSay: if char == tmp: count += 1 else: say += str(count) + tmp tmp, count = char, 1 say += str(count) + tmp return say # if __name__ == '__main__': # test = CountAndSay() # test.countAndSay(3)