text
stringlengths
37
1.41M
import math # Equação dada na questão def Equation(x): e = 2.7182818284590452353602874 y = pow(e, 0.3 * x) - 3 + (3 * x) return y # Derivada da equação dada na questão def DerivativeEquation(x): e = 2.7182818284590452353602874 y = 0.3 * pow(e, 0.3 * x) + 3 return y x0 = 0.7 # Estimativa inicial dada i = 0 # Numero de iterações print("i x1 ea\n") while (1): # No loop de repetição aplica o algoritmo de Newton-Raphson i = i + 1 # Aumenta a iteração x1 = x0 - Equation(x0) / DerivativeEquation(x0) ea = (x1 - x0) / x1 # Calculo do erro print(f'{i} {x1} {abs(ea)}') x0 = x1 if (abs(ea) < 0.02): # Condição de parada das iterações break
# -*- coding: utf-8 -*- """ Created on Sun Dec 23 18:06:10 2018 @author: 程甜甜 """ def found (): xiaotou = ['A','B','C','D'] #for(xiaotou='A';xiaotou<='D';xiaotou++): for xiaotou in ['A','B','C','D']: if(((xiaotou!='A')+(xiaotou=='D')+(xiaotou=='B')+(xiaotou!='D'))==1): print('小偷为'+xiaotou) #print(xiaotou) found ()
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the countTriplets function below. def countTriplets(arr, r): countDoubletPotentials = Counter() # Counts number of Doublet Potentials, i.e. the frequency of each possible number of values for the 2nd value in the Sequence countTripletPotentials = Counter() # Counts number of Triplet Potentials, i.e. the frequency of each possible number of values for the 3rd value in the Sequence counter = 0 # Counts number of complete Triplets # Loop over the entire Array for i in range(0, n): # If if countTripletPotentials[arr[i]] > 0: counter += countTripletPotentials[arr[i]] # Increase Complete Triplets by the number of Triplet Potentials that have now found their 3rd Value (i.e. value required to complete the triplet) if countDoubletPotentials[arr[i]] > 0: countTripletPotentials[(arr[i] * r)] += countDoubletPotentials[arr[i]] # Increase number of Triplet Potentials by the number of Doublet Potentials that have now found their 2nd Value (i.e. value required to complete the Doublet, so only 1 more value required to make a triplet) countDoubletPotentials[(arr[i] * r)] += 1 # Add the required 2nd value to be found to make a Doublet, i.e. counter of Doublet potentials. return counter if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from util.ZTree import * from util.List import * class Solution: # 2020-9-14 13:55:13 # 这类自己递归,再加一个子递归的题,还要加强 def isSubPath(self, head: ListNode, root: TreeNode) -> bool: def dfs(h: ListNode, r: TreeNode) -> bool: if not h: # 链表走完了 return True if not r: return False if h.val == r.val: return dfs(h.next, r.left) or dfs(h.next, r.right) # return dfs(h, r.left) or dfs(h, r.right) 这里不用再往下走了 return False if not root: return False # 注意这里递归又调用了isSubPath()自身 # return dfs(head, root) or dfs(head, root.left) or dfs(head, root.right) return dfs(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right)
class ListNode: def __init__(self, x): self.val = x self.next = None def toLinkedList(A): ptr = dummy = ListNode(-1) for ele in A: ptr.next = ListNode(ele) ptr = ptr.next return dummy.next def printLinkedList(head: ListNode): A = [] while head: A.append(str(head.val)) head = head.next print('[%s]' % ', '.join(A)) if __name__ == '__main__': test_A_1 = [1, 2, 3] head = toLinkedList(test_A_1) printLinkedList(head)
class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ res = [] candidates.sort() def dfs(cur_nums, path, cur_target): left = 0 while left < len(cur_nums): num = cur_nums[left] if num == cur_target: res.append(path + [num]) return elif num < cur_target: dfs(cur_nums[left + 1:], path + [num], cur_target - num) left += 1 # 找到下一位不相同的数,去重 while left < len(cur_nums) and cur_nums[left] == cur_nums[left - 1]: left += 1 else: break dfs(candidates, [], target) return res print(Solution().combinationSum2([10, 1, 2, 7, 6, 1, 5], 8)) print(Solution().combinationSum2([2, 5, 2, 1, 2], 5))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from util.ZTree import * class Solution: # others solution def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: if not nums: return None max_value = max(nums) max_index = nums.index(max_value) root = TreeNode(max_value) root.left = self.constructMaximumBinaryTree(nums[:max_index]) root.right = self.constructMaximumBinaryTree(nums[max_index + 1:]) return root # my solution # def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: # if not nums: # return None # # # end excluded # def construct(start: int, end: int) -> TreeNode: # if start >= end: # return None # root_index = start # for i in range(start + 1, end): # if nums[i] > nums[root_index]: # root_index = i # new_node = TreeNode(nums[root_index]) # new_node.left = construct(start, root_index) # new_node.right = construct(root_index + 1, end) # return new_node # # return construct(0, len(nums)) roo = Solution().constructMaximumBinaryTree([3, 2, 1, 6, 0, 5]) a = 1
from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: if not word: return True if not board: return False row_count = len(board) col_count = len(board[0]) queue = [] for i in range(row_count): for j in range(col_count): if board[i][j] == word[0]: queue.append([(i, j)]) while queue: cur_list = queue.pop() if len(cur_list) == len(word): return True last_pos = cur_list[-1] candidates = [(last_pos[0] - 1, last_pos[1]), (last_pos[0], last_pos[1] - 1), (last_pos[0] + 1, last_pos[1]), (last_pos[0], last_pos[1] + 1), ] for candi in candidates: if 0 <= candi[0] < row_count and 0 <= candi[1] < col_count: if candi not in cur_list and board[candi[0]][candi[1]] == word[len(cur_list)]: queue.append(cur_list + [candi]) return False board = [ ['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E'] ] word = "SEE" print(Solution().exist(board, word))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from util.ZTree import * from collections import deque class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: if not root: return [] queue, res = deque([root]), [] while queue: this_size, this_sum = len(queue), 0 for i in range(this_size): this_node = queue.popleft() this_sum += this_node.val if this_node.left: queue.append(this_node.left) if this_node.right: queue.append(this_node.right) res.append(this_sum / this_size) return res print(Solution().averageOfLevels())
# Definition for singly-linked list. # 每个节点右移k,k >= 0 # 1. k < N; k == N; k > N # 找到连接点,断开,重连 class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head or not head.next or k == 0: return head # k可能大于长度 N, ptr = 0, head while ptr: N += 1 ptr = ptr.next k = k % N # 再次判断 if k == 0: return head # 头结点会变 dummy = ListNode(-1) dummy.next = head slow, fast = dummy, dummy for _ in range(k): fast = fast.next while slow and fast.next: slow = slow.next fast = fast.next dummy.next = slow.next slow.next = None fast.next = head return dummy.next # def rotateRight(self, head: ListNode, k: int) -> ListNode: # if k == 0 or not head: # return head # n, ptr = 0, head # while ptr: # n += 1 # ptr = ptr.next # mod_k = k % n # k可能大于数组长度 # if mod_k == 0: # return head # A = B = head # for i in range(mod_k): # if not B: # return None # B = B.next # while B and B.next: # A = A.next # B = B.next # new_head, B.next, A.next = A.next, head, None # return new_head node1 = ListNode(0) node2 = ListNode(1) node3 = ListNode(2) node4 = ListNode(4) node5 = ListNode(5) node1.next = node2 node2.next = node3 # node3.next = node4 # node4.next = node5 node = Solution().rotateRight(node1, 4) a = 1
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from util.List import * class Solution: # 官方题解,先放到before、after两个链表中,再将before、after连接 def partition(self, head: ListNode, x: int) -> ListNode: before_head, after_head = ListNode(-1), ListNode(-1) before, after = before_head, after_head ptr = head while ptr: if ptr.val < x: before.next = ptr before = ptr else: after.next = ptr after = ptr ptr = ptr.next before.next = after_head.next after.next = None return before_head.next # 在原链表上删除、插入 # def partition(self, head: ListNode, x: int) -> ListNode: # if not head or not head.next: # return head # guard = dummy = ListNode(-1) # dummy.next = head # # guard:第一个大于等于x的结点的前一个结点 # while guard: # if guard.next and guard.next.val >= x: # break # guard = guard.next # # 都小于x,提前退出 # if not guard: # return head # soldier = guard # while soldier.next: # # 找到小于x的节点,从原位置删除,插入到guard之前 # if soldier.next.val < x: # tmp = soldier.next # soldier.next = tmp.next # guard_next = guard.next # guard.next = tmp # tmp.next = guard_next # guard = guard.next # else: # soldier = soldier.next # return dummy.next head = toLinkedList([3, 2]) res = Solution().partition(head, 3) printLinkedList(res)
from typing import List class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: # 运载能力为capacity时,需要几天可以运完 def countDays(capacity: int) -> int: count = 1 tmp = capacity for w in weights: if tmp >= w: tmp -= w else: count += 1 tmp = capacity - w return count # 下界是最重的物品,不然就运不走这个物品 lo, hi = max(weights), sum(weights) while lo < hi: mid = (lo + hi) >> 1 if D < countDays(mid): lo = mid + 1 else: hi = mid return lo assert Solution().shipWithinDays([1, 2, 3, 1, 1], 4) == 3 assert Solution().shipWithinDays([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 15 assert Solution().shipWithinDays([3, 2, 2, 4, 1, 4], 3) == 6
from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] res = nums[0] tmp = 0 for num in nums: if tmp > 0: tmp += num else: tmp = num res = max(res, tmp) return res print(Solution().maxSubArray([-2, -1]))
from typing import List class Solution: # O(1) 空间复杂度 # 标记第一行、第一列,但要注意其本身含有0 def setZeroes(self, matrix: List[List[int]]) -> None: m, n = len(matrix), len(matrix[0]) flag_row = flag_col = False for i in range(m): if matrix[i][0] == 0: flag_col = True break for j in range(n): if matrix[0][j] == 0: flag_row = True break for i in range(1, m): for j in range(1, n): if matrix[i][j] == 0: matrix[i][0] = matrix[0][j] = 0 for i in range(1, m): for j in range(1, n): if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 if flag_row: for j in range(n): matrix[0][j] = 0 if flag_col: for i in range(m): matrix[i][0] = 0 # O(m + n) 空间复杂度 # def setZeroes(self, matrix: List[List[int]]) -> None: # if not matrix or not matrix[0]: # return # m, n = len(matrix), len(matrix[0]) # row, col = [False] * m, [False] * n # for i in range(m): # for j in range(n): # if matrix[i][j] == 0: # row[i] = col[j] = True # for i in range(m): # for j in range(n): # if row[i] or col[j]: # matrix[i][j] = 0 matrix = [ [0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5] ] Solution().setZeroes(matrix) print(matrix)
# Definition for a binary tree node. import collections class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ # res = '' # # def dfs(node): # nonlocal res # if node: # res += str(node.val) + ',' # dfs(node.left) # dfs(node.right) # else: # res += '$,' # # dfs(root) # return res[:-1] if not root: return "[]" queue = collections.deque() queue.append(root) res = [] while queue: node = queue.popleft() if node: res.append(str(node.val)) queue.append(node.left) queue.append(node.right) else: res.append("null") return '[' + ','.join(res) + ']' def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if not data: return None split_list = data.split(',') i = 0 def dfs(): nonlocal i if i < len(split_list): node = None if split_list[i] == '$': i += 1 else: node = TreeNode(split_list[i]) i += 1 node.left, node.right = dfs(), dfs() return node return dfs() # root = TreeNode(1) # root.left = TreeNode(2) # root.right = right = TreeNode(3) # root.right.left = TreeNode(4) # root.right.right = TreeNode(5) root = TreeNode(5) root.left = TreeNode(2) root.right = TreeNode(3) root.right.left = TreeNode(2) root.right.right = TreeNode(4) root.right.left.left = TreeNode(3) root.right.left.right = TreeNode(1) # Your Codec object will be instantiated and called as such: codec = Codec() res = codec.serialize(root) print(res) # new_root = codec.deserialize(res) # print(new_root)
from typing import List class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: grids = [[False] * 9 for _ in range(9)] cols = [[False] * 9 for _ in range(9)] rows = [[False] * 9 for _ in range(9)] for i in range(9): for j in range(9): if board[i][j] != '.': idx = ord(board[i][j]) - ord('1') grid_i = (i // 3) * 3 + j // 3 if grids[grid_i][idx] or cols[j][idx] or rows[i][idx]: return False grids[grid_i][idx] = cols[j][idx] = rows[i][idx] = True return True assert Solution().isValidSudoku([ ["5", "3", ".", ".", "7", ".", ".", ".", "."], ["6", ".", ".", "1", "9", "5", ".", ".", "."], [".", "9", "8", ".", ".", ".", ".", "6", "."], ["8", ".", ".", ".", "6", ".", ".", ".", "3"], ["4", ".", ".", "8", ".", "3", ".", ".", "1"], ["7", ".", ".", ".", "2", ".", ".", ".", "6"], [".", "6", ".", ".", ".", ".", "2", "8", "."], [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"] ])
from typing import List class Solution: def letterCombinations(self, digits: str) -> List[str]: def dfs(i: int, cur_list: []): if i == n: ans.append(''.join(cur_list)) return for c in mapping[digits[i]]: cur_list.append(c) dfs(i + 1, cur_list) cur_list.pop() if not digits: return [] mapping = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz', } n, ans = len(digits), [] dfs(0, []) return ans print(Solution().letterCombinations('23'))
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ # 快慢指针 # slow = fast = head # while fast and fast.next: # slow = slow.next # fast = fast.next.next # if slow == fast: # return True # return False # 使用map lookup = {} while head: if head in lookup: return True lookup[head] = 0 head = head.next return False node1 = ListNode(3) node2 = ListNode(2) node3 = ListNode(0) node4 = ListNode(-4) # node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node2 print(Solution().hasCycle(node1))
from typing import List class Solution: # 当num<0时,最大值、最小值会发生转换 def maxProduct(self, nums: List[int]) -> int: if not nums: return None cur_min = nums[0] cur_max = nums[0] _max = nums[0] for i in range(1, len(nums)): if nums[i] < 0: cur_max, cur_min = cur_min, cur_max cur_max = max(nums[i], cur_max * nums[i]) cur_min = min(nums[i], cur_min * nums[i]) _max = max(_max, cur_max) return _max print(Solution().maxProduct([-2, 3, -4]))
from typing import List class Solution: # 文章序号为X,引用为Y,作图,寻找X=Y与图像的交点 # 排序后线性查找 def hIndex(self, citations: List[int]) -> int: n = len(citations) i = 0 citations.sort(reverse=True) while i < n and citations[i] > i: i += 1 return i assert Solution().hIndex([3, 0, 6, 1, 5]) == 3
from typing import List class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if not board or not board[0]: return m, n = len(board), len(board[0]) def dfs(i, j): if i < 0 or i > m - 1 or j < 0 or j > n - 1: return if board[i][j] != 'O': return board[i][j] = 'A' dfs(i - 1, j) dfs(i + 1, j) dfs(i, j - 1) dfs(i, j + 1) for i in range(m): dfs(i, 0) dfs(i, n - 1) for j in range(n): dfs(0, j) dfs(m - 1, j) for i in range(m): for j in range(n): if board[i][j] == 'A': board[i][j] = 'O' elif board[i][j] == 'O': board[i][j] = 'X'
# 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 from util.ZTree import * class Solution: def generateTrees(self, n: int) -> List[TreeNode]: def dfs(start: int, end: int) -> List[TreeNode]: if start >= end: # 一定要返回None,不然后面不会进循环 return [None] # 返回一个列表 res = [] for i in range(start, end): lt_children = dfs(start, i) rt_children = dfs(i + 1, end) for lt in lt_children: for rt in rt_children: node = TreeNode(i) node.left = lt node.right = rt res.append(node) return res return dfs(1, n + 1) if n else [] r = Solution().generateTrees(3) a = 1
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from util.ZTree import * # BST的中序遍历有序,第k大就是中序遍历中下标为n - k的元素,k从1开始。 # 给自己看的:前序、中序居然写错了!?所谓前、中指的是根节点的位置,中序LNR。 # 困难:树的大小n提前不可知,只有遍历一遍才能知道n,但如果要把遍历结果整个保存下来,显然n - k之后都在白作功; # 解决:但如果把中序遍历倒序变成RNL,那么只用找下标为k-1的元素,不再需要知道n,可以提前结束; class Solution: def kthLargest(self, root: TreeNode, k: int) -> int: stk, p = [], root while stk or p: # 想象一个右子树很长的树,从根开始一直到最底,逐个把节点加入栈中 while p: stk.append(p) p = p.right # 现在你到最底了,没有节点了, # 你再从栈中取一个节点,并访问 p = stk.pop() k -= 1 if k == 0: return p.val # 访问了根节点,再看看有没有左子树 p = p.left # def kthLargest(self, root: TreeNode, k: int) -> int: # def inorder_traversal(r: TreeNode): # if not r: # return # nonlocal res, count_down_k # 从外部函数共享 # inorder_traversal(r.right) # 倒序,先遍历right # if count_down_k == 0: # if res == -1: # 注意,一定要确保res之前没被改过,不然会被父节点的值覆盖了 # res = r.val # return # count_down_k -= 1 # inorder_traversal(r.left) # # count_down_k = k - 1 # res = -1 # inorder_traversal(root) # return res roo = buildTreeFromList([3, 1, 4, None, 2]) print(Solution().kthLargest(roo, 1))
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ p1 = m - 1 p2 = n - 1 p3 = m + n - 1 while p2 >= 0: if p1 < 0 or nums1[p1] <= nums2[p2]: nums1[p3] = nums2[p2] p2 -= 1 else: nums1[p3] = nums1[p1] p1 -= 1 p3 -= 1 nums1 = [1, 2, 3, 0, 0, 0] m = 3 nums2 = [2, 5, 6, ] n = 3 Solution().merge(nums1, m, nums2, n) print(nums1)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from util.List import * class Solution: # 双指针 def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: m, n = 0, 0 p, q = headA, headB while p: m += 1 p = p.next while q: n += 1 q = q.next if m < n: # 令A更长 headA, headB = headB, headA m, n = n, m for i in range(m - n): headA = headA.next while headA and headB: if headA == headB: return headA headA, headB = headA.next, headB.next return None
from typing import List class Solution: def evalRPN(self, tokens: List[str]) -> int: stk = [] for token in tokens: if token == '+': stk[-2] = stk[-1] + stk[-2] stk.pop() elif token == '-': stk[-2] = stk[-2] - stk[-1] stk.pop() elif token == '*': stk[-2] = stk[-2] * stk[-1] stk.pop() elif token == '/': stk[-2] = int(stk[-2] / stk[-1]) stk.pop() else: stk.append(int(token)) return stk[0] assert Solution().evalRPN(["4", "3", "-"]) == 1 assert Solution().evalRPN( ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] ) == 22 assert Solution().evalRPN(["2", "1", "+", "3", "*"]) == 9 assert Solution().evalRPN(["4", "13", "5", "/", "+"]) == 6
class Solution(object): def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ res = [] def dfs(cur_k, cur_n, index, path): for i in range(index, 10): if cur_k == 1 and cur_n == i: res.append(path + [i]) return elif cur_k > 0 and cur_n > i: dfs(cur_k - 1, cur_n - i, i + 1, path + [i]) else: return dfs(k, n, 1, []) return res print(Solution().combinationSum3(3, 9))
from typing import List class Solution: # 相等的时候,移谁都可以,之后的更大值,只有在两块板都移出去之后才会出现 def maxArea(self, height: List[int]) -> int: n = len(height) left = 0 right = n - 1 ans = 0 while left < right: if height[left] < height[right]: ans = max(ans, (right - left) * height[left]) left += 1 else: ans = max(ans, (right - left) * height[right]) right -= 1 return ans print(Solution().maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]))
from typing import List class Solution: # DFS def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: def dfs(i: int): visited.add(i) connected_nodes.append(i) for j in graph[i]: if j not in visited: dfs(j) n = len(s) s_list = list(s) # 建图 邻接矩阵 graph = [[] for _ in range(n)] for u, v in pairs: graph[u].append(v) graph[v].append(u) visited = set() for i in range(n): if i in visited: continue connected_nodes = [] dfs(i) connected_nodes.sort() char_list = sorted(s_list[i] for i in connected_nodes) for i, ch in zip(connected_nodes, char_list): s_list[i] = ch return ''.join(s_list) assert Solution().smallestStringWithSwaps('dcab', [[0, 3], [1, 2], [0, 2]]) == "abcd" assert Solution().smallestStringWithSwaps('dcab', [[0, 3], [1, 2]]) == 'bacd'
class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.push_stk = [] self.pop_stk = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.push_stk.append(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ # 1.如果pop_stk不为空,push_stk绝对不可以压入数据 if not self.pop_stk: # 2.push_stk如果要将数据压入pop_stk,必须一次压完 while self.push_stk: self.pop_stk.append(self.push_stk.pop()) if self.pop_stk: return self.pop_stk.pop() def peek(self) -> int: """ Get the front element. """ if self.pop_stk: return self.pop_stk[-1] elif self.push_stk: return self.push_stk[0] def empty(self) -> bool: """ Returns whether the queue is empty. """ return not self.push_stk and not self.pop_stk # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
# 题目来源:https://www.lintcode.com/problem/median # 无序数组,不是数学上的中位数,而是排在中间的数 # 奇数,中间的值;偶数,排序后第N//2个元素 # 1. 排序,O(NlogN) # 2. 大小为N//2+1的堆 # 3. 快速选择 class Solution: """ @param nums: A list of integers @return: An integer denotes the middle number of the array """ def median(self, nums): def partition(A, i, j): pivot = nums[i] m = i for k in range(i + 1, j): if A[k] < pivot: m += 1 A[k], A[m] = A[m], A[k] A[i], A[m] = A[m], A[i] return m def quick_find(A, lo, hi, k): if lo < hi: m = partition(A, lo, hi) if m == k: return A[m] elif m < k: return quick_find(A, m + 1, hi, k) else: return quick_find(A, lo, m, k) return quick_find(nums, 0, len(nums), (len(nums) + 1) // 2 - 1) assert Solution().median([7, 9, 4, 5]) == 5 assert Solution().median([4, 5, 1, 2, 3]) == 3
from typing import List class Solution: # 1. 英文字母可以用数组处理,因为只有26位 # 2. def equationsPossible(self, equations: List[str]) -> bool: def find(p: str) -> str: if equal_set[p] != p: equal_set[p] = find(equal_set[p]) return equal_set[p] def union(p: str, q: str): pRoot, qRoot = find(p), find(q) # 这里其实可以不要 # if pRoot == qRoot: # return equal_set[pRoot] = qRoot equal_set = {} non_equal_set = {} # 数组元素是数组,可以直接解构赋值 for p, a, b, q in equations: # p, a, b, q = eq if p not in equal_set: equal_set[p] = p if q not in equal_set: equal_set[q] = q if a == '!': li = non_equal_set.get(p, []) li.append(q) non_equal_set[p] = li else: union(p, q) for _key in non_equal_set: for _ele in non_equal_set[_key]: pRoot, qRoot = find(_key), find(_ele) if pRoot == qRoot: return False return True print(Solution().equationsPossible(["c==c", "b==d", "x!=z"])) assert not Solution().equationsPossible(["a==b", "b!=a"]) assert Solution().equationsPossible(["b==a", "a==b"]) assert Solution().equationsPossible(["a==b", "b==c", "a==c"]) assert not Solution().equationsPossible(["a==b", "b!=c", "c==a"])
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] def traversal(node, level): if not node: return if level > len(res): res.append([]) res[level - 1].append(node.val) traversal(node.left, level + 1) traversal(node.right, level + 1) traversal(root, 1) return res root = TreeNode(3) left = TreeNode(9) right = TreeNode(20) rightLeft = TreeNode(15) rightRight = TreeNode(7) root.left = left root.right = right right.left = rightLeft right.right = rightRight print(Solution().levelOrder(root))
weights = [2, 3, 4, 5] values = [3, 4, 5, 6] capacity = 8 # 最优解10 def knapsack(w: list, v: list, C: int) -> int: N = len(w) dp = [0] * (C + 1) for i in range(N): for c in range(C, w[i] - 1, -1): dp[c] = max(dp[c], dp[c - w[i]] + v[i]) print(dp) return dp[-1] print(knapsack(weights, values, capacity))
#lex_auth_0127667345256611843470 # Problem Statement # Now we know that comparison and swapping are two basic operations required for sorting, let’s write a function to swap two numbers in a list. # Complete the given function by following the instructions provided in template code. Test your code by passing different values for num_list, first_index and second_index. def swap(num_list, first_index, second_index): #Remove pass and write your logic here #As python lists are mutable, num_list need not be returned after swapping # pass num_list[first_index],num_list[second_index]=num_list[second_index],num_list[first_index] #Pass different values to the function and test your program num_list=[2,3,89,45,67] print("List before swapping:",num_list) swap(num_list, 1, 2) print("List after swapping:",num_list)
#lex_auth_0127438939341373441628 # The TwinkleStar kindergarten kids are given a new game everyday to play among themselves. The teacher has come up with an idea for the kids to learn grouping and sorting. The teacher has given a container full of colored balls. Assume that the container has the following balls: # Color Red Blue Yellow Blue Yellow Green Green Red # Name A B B A A B A B # There are two each (A,B) of red, green ,blue and yellow balls in the container. # The task for the children is to take out the balls one at a time from the container and put it in four different containers based on the color. After that, the balls should be arranged such that the corresponding colored ball A is on top in all the four containers. # Note : The diameter of all the five containers are equal to that of a single ball, hence balls should be arranged one on top of the other. # Use the Ball class and list of balls to implement the class Game as given in the class diagram. # 1. In the constructor of Game class create lists to store balls of different color separately # 2. Display the color and name of the balls before and after grouping and arranging them in order. # Note: You may use the appropriate data structure(s) for solving this problem # __init__(ball_stack) Initializes the ball container # grouping_based_on_color() Used to group the balls based on the color # rearrange_balls() Used for rearranging the balls such that ball A would be on the top of the container # display_ball_details() # Used for displaying the color and type of the balls #lex_auth_0127438939341373441628 #lex_auth_0127438939341373441628 #lex_auth_0127438939341373441628 class Queue: def __init__(self,max_size): self.__max_size=max_size self.__elements=[None]*self.__max_size self.__rear=-1 self.__front=0 def is_full(self): if(self.__rear==self.__max_size-1): return True return False def is_empty(self): if(self.__front>self.__rear): return True return False def enqueue(self,data): if(self.is_full()): print("Queue is full!!!") else: self.__rear+=1 self.__elements[self.__rear]=data def dequeue(self): if(self.is_empty()): print("Queue is empty!!!") else: data=self.__elements[self.__front] self.__front+=1 return data def display(self): for index in range(self.__front, self.__rear+1): print(self.__elements[index]) def get_max_size(self): return self.__max_size #You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): msg=[] index=self.__front while(index<=self.__rear): msg.append((str)(self.__elements[index])) index+=1 msg=" ".join(msg) msg="Queue data(Front to Rear): "+msg return msg class Stack: def __init__(self,max_size): self.__max_size=max_size self.__elements=[None]*self.__max_size self.__top=-1 def is_full(self): if(self.__top==self.__max_size-1): return True return False def is_empty(self): if(self.__top==-1): return True return False def push(self,data): if(self.is_full()): print("The stack is full!!") else: self.__top+=1 self.__elements[self.__top]=data def pop(self): if(self.is_empty()): print("The stack is empty!!") else: data= self.__elements[self.__top] self.__top-=1 return data def display(self): if(self.is_empty()): print("The stack is empty") else: index=self.__top while(index>=0): print(self.__elements[index]) index-=1 def get_max_size(self): return self.__max_size #You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): msg=[] index=self.__top while(index>=0): msg.append((str)(self.__elements[index])) index-=1 msg=" ".join(msg) msg="Stack data(Top to Bottom): "+msg return msg class Ball: def __init__(self,color,name): self.__color=color self.__name=name def __str__(self): return (self.__color+" "+self.__name) def get_color(self): return self.__color def get_name(self): return self.__name #Implement Game class here class Game: def __init__(self,ball_stack): self.ball_container=ball_stack self.red_balls_container=Stack(2) self.blue_balls_container=Stack(2) self.green_balls_container=Stack(2) self.yellow_balls_container=Stack(2) def grouping_based_on_color(self): while(not self.ball_container.is_empty()): a=self.ball_container.pop() if(a.get_color()=="Red"): self.red_balls_container.push(a) elif(a.get_color()=="Blue"): self.blue_balls_container.push(a) elif(a.get_color()=="Yellow"): self.yellow_balls_container.push(a) else: self.green_balls_container.push(a) def rearrange_balls(self,color): if(color=="Red"): b=self.red_balls_container elif(color=="Blue"): b=self.blue_balls_container elif(color=="Yellow"): b=self.yellow_balls_container else: b=self.green_balls_container popped1=b.pop() if(popped1.get_name()!="A"): popped2=b.pop() b.push(popped1) b.push(popped2) else: b.push(popped1) def display_ball_details(self,color): if(color=="Red"): b=self.red_balls_container elif(color=="Blue"): b=self.blue_balls_container elif(color=="Yellow"): b=self.yellow_balls_container else: b=self.green_balls_container b.display() #Use different values to test your program ball1=Ball("Red","A") ball2=Ball("Blue","B") ball3=Ball("Yellow","B") ball4=Ball("Blue","A") ball5=Ball("Yellow","A") ball6=Ball("Green","B") ball7=Ball("Green","A") ball8=Ball("Red","B") ball_list=Stack(8) ball_list.push(ball1) ball_list.push(ball2) ball_list.push(ball3) ball_list.push(ball4) ball_list.push(ball5) ball_list.push(ball6) ball_list.push(ball7) ball_list.push(ball8) g1=Game(ball_list) g1.grouping_based_on_color() # print(g1) g1.rearrange_balls("Red") # print(g1) g1.display_ball_details("Red") #Create objects of Game class, invoke the methods and test the program
#lex_auth_0127667391112806403379 # Problem Statement # The International Cricket Council (ICC) wanted to do some analysis of international cricket matches held in last 10 years. # Given a list containing match details as shown below: # [match_detail1,match_detail2……] # Format of each match_detail in the list is as shown below: # country_name : championship_name : total_number_of_matches_played : number_of_matches_won # Example: AUS:CHAM:5:2 means Australia has participated in Champions Trophy 5 times and have won 2 times. # Write a python program which performs the following: # find_matches (country_name): Accepts the country_name and returns the list of details of matches played by that country. # max_wins(): Returns a dictionary containing the championship name as the key and the list of country/countries which have won the maximum number of matches in that championship as the value. # find_winner(country1,country2): Accepts name of two countries and returns the country name which has won more number of matches in all championships. If both have won equal number of matches, return "Tie". # Perform case sensitive string comparison wherever necessary. # match_list – ['ENG:WOR:2:0', 'AUS:CHAM:5:2', 'PAK:T20:5:1', 'AUS:WOR:2:1', 'SA:T20:5:0', 'IND:T20:5:3', 'PAK:WOR:2:0', 'SA:WOR:2:0', 'SA:CHAM:5:1', 'IND:WOR:2:1'] # Sample Input # Expected Output # find_matches ("AUS") # ['AUS':CHAM:5:2','AUS:WOR:2:1'] # max_wins() # {'WOR': ['AUS', 'IND'], 'CHAM': ['AUS'], 'T20': ['IND']} # find_winner("AUS","IND") # IND def find_matches(country_name): #Remove pass and write your logic here # pass country_match=[] for i in match_list: name=i.split(':')[0] if(name == country_name): country_match.append(i) return country_match def max_wins(): cham,wor,t20,tmp,ret = [],[],[],[],dict() """ChampionShip Check""" for detail in match_list: split_detail = detail.split(":") if split_detail[1] == "CHAM": cham.append(split_detail[0]) tmp.append(split_detail[3]) if len(tmp) !=0: while (min(tmp)!=max(tmp)): cham.pop(tmp.index(min(tmp))) tmp.pop(tmp.index(min(tmp))) ret ["CHAM"] = cham """T20 Check""" tmp = [] for detail in match_list: split_detail = detail.split(":") if split_detail[1] == "T20": t20.append(split_detail[0]) tmp.append(split_detail[3]) if len(tmp) !=0: while (min(tmp)!=max(tmp)): t20.pop(tmp.index(min(tmp))) tmp.pop(tmp.index(min(tmp))) ret ["T20"] = t20 """World Cup Check""" tmp = [] for detail in match_list: split_detail = detail.split(":") if split_detail[1] == "WOR": wor.append(split_detail[0]) tmp.append(split_detail[3]) if len(tmp) !=0: while (min(tmp)!=max(tmp)): wor.pop(tmp.index(min(tmp))) tmp.pop(tmp.index(min(tmp))) ret ["WOR"] = wor return ret def find_winner(country1,country2): #Remove pass and write your logic here count1=0 count2=0 for i in match_list: if(i.split(':')[0]==country1): count1+=int(i.split(':')[3]) elif(i.split(':')[0]==country2): count2+=int(i.split(':')[3]) if(count1>count2): return country1 elif(count2>count1): return country2 else: return "Tie" #Consider match_list to be a global variable match_list=["AUS:CHAM:5:2","AUS:WOR:2:1","ENG:WOR:2:0","IND:T20:5:3","IND:WOR:2:1","PAK:WOR:2:0","PAK:T20:5:1","SA:WOR:2:0","SA:CHAM:5:1","SA:T20:5:0"] #Pass different values to each function and test your program print("The match status list details are:") print(match_list) c=find_matches("AUS") print(c) print(max_wins()) print(find_winner("IND", "AUS"))
n = input() sm = 0 for v in n: sm += int(v) if sm % 9 == 0: print("Yes") else: print("No")
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jul 28 00:57:34 2020 @author: satyam """ from Book import Book class User: def __init__(self, name, location, age, aadhar_id): self.name = name self.location = location self.age = age self.aadhar_id = aadhar_id class Member(User): def __init__(self,name, location, age, aadhar_id,student_id): super().__init__(name, location, age, aadhar_id) self.student_id = student_id self.bookc = {} self.bookd = {} def no_of_book(self,name,book): if name not in self.bookc: self.bookc[name] = [book] return len(self.bookc[name]) else: if len(self.bookc[name]) <= 2: self.bookc[name].append(book) return len(self.bookc[name]) else: return len(self.bookc[name]) def issue_book(self,book,name,days = 10): if book in Book.Count_book_dict.keys(): if book.Count_book_dict[book][0]>=1: if (book,name) not in self.bookd.keys(): if self.no_of_book(name,book)<=2: self.bookd.update({(book,name):days}) Book.Count_book_dict[book][0] -= 1 for value in self.bookd.keys(): if value == (book,name): print("Book is issued by you") else: print("you can issue only 2 books") else: print("the book is already issued") else: print("the book is not available") else: print("this book is not available") def return_book(self,book,name): if (book,name) in self.bookd.keys(): self.bookc[name].remove(book) self.bookd.pop((book,name)) Book.Count_book_dict[book][0] += 1 print("returned sucessfully") else: print("please give correct detail") class Librarian(User): def __init__(self,name, location, age, aadhar_id,librarian_id): super().__init__(name, location, age, aadhar_id) self.librarian_id = librarian_id def addBook(self,book_name,quantity, author,publish_date, pages): if quantity>0: if book_name in Book.Count_book_dict.keys(): Book.Count_book_dict[book_name][0]+=quantity else: Book.Count_book_dict.update({book_name:[quantity, author,publish_date, pages]}) print("book is added") else: print("please enter valid number") def removebook(self,book_name,quantity,author,publish_date,pages): if quantity>0: if book_name in Book.Count_book_dict.keys(): if Book.Count_book_dict[book_name][0]>=1: Book.Count_book_dict[book_name][0]-=quantity if Book.Count_book_dict[book_name][0] < 0 : Book.Count_book_dict[book_name][0]+=quantity print("enter correct quantity") else: print("book removed") else: Book.Count_book_dict.pop(book_name) print("sorry we dont have this book") else: print("enter correct book name and quantity") else: print("enter valid number")
lis1=[] while True: str1=raw_input("enter the details ") if not str1: break tup1=str1.split(",") lis1.append((tup1[0],int(tup1[1]),int(tup1[2]))) lis1.sort() print lis1
# -*- coding: utf-8 -*- """ Created on Mon May 14 13:16:19 2018 @author: mansi sharma """ str1=raw_input("enter string") print str1 dict1={} for i in str1: r=str1.count(i) dict1[i]=r print dict1
# get data # create two articles on with punctuation and the other with any punctuations # count word frequency with the second type of article # find the most relevant sentences from 1 st article based on word frequency # use these sentences as summary by joining all these articles #from gensim.summarization import summarize def final_summary_text(text,nos): import re import urllib.request import requests from bs4 import BeautifulSoup from nltk.corpus import stopwords from string import punctuation import nltk nltk.download('punkt') import sys stop_words=stopwords.words('english') punctuation=punctuation + '\n' def get_semiclean_content(text): #obj=requests.get(url) #text=obj.text #soup=BeautifulSoup(text,features="lxml") #paras=soup.find_all("p") #newtext=' ' #for para in paras: #newtext+=para.text text=nltk.sent_tokenize(text) semi_cleaned=semi_cleaned_text(text) return semi_cleaned def semi_cleaned_text(doc): # Removing Square Brackets and Extra Spaces newdoc=' ' for sen in doc: newdoc+=sen newdoc= re.sub(r'\[[0-9]*\]', ' ', newdoc) newdoc= re.sub(r'\s+', ' ', newdoc) return newdoc def cleaned_text(doc): newdoc=' ' for sen in doc: newdoc+=sen newdoc = re.sub('[^a-zA-Z]'," ",newdoc) # only alphabets newdoc= re.sub('\s+'," ",newdoc) return newdoc def get_clean_content(text): #obj=requests.get(url) #text=obj.text #soup=BeautifulSoup(text,features="lxml") #paras=soup.find_all("p") #newtext=' ' #for para in paras: #newtext+=para.text text=nltk.sent_tokenize(text) cleaned=cleaned_text(text) return cleaned final=get_clean_content(text) semi_final=get_semiclean_content(text) sentences=nltk.sent_tokenize(final) word_frequencies= {} for word in nltk.word_tokenize(final): if word.lower() not in stop_words: if word not in word_frequencies.keys(): word_frequencies[word] = 1 else: word_frequencies[word] += 1 mx=max(word_frequencies.values()) for word in word_frequencies.keys(): word_frequencies[word]=word_frequencies[word]/mx sentences=nltk.sent_tokenize(semi_final) total=len(sentences) scores= {} for sen in sentences: for word in nltk.word_tokenize(sen.lower()): if word in word_frequencies.keys(): if len(sen.split(' ')) < 50: if sen not in scores: scores[sen]=word_frequencies[word] else: scores[sen]+=word_frequencies[word] import heapq number=nos summary_sen=heapq.nlargest(number,scores,key=scores.get) summary= ' '.join(summary_sen) return summary
def say_hello(): print('Hello World') say_hello() #function_parameter def print_max(a,b): if a > b: print(a, 'is maxium') elif a == b: print(a,' is equal to'. b) else: print(b,'is maxium') print_max(3, 4) x = 8 y = 11 print_max(x, y) #Local Variables def func(x): print('x is', x) x = 2 print('Changed local x to', x) x = 50 func(x) print('x is still', x) ====== x = 30 def func(x): x = 2 print('x is', x) def funx(x): x = 10 print('x is', x) func(x) funx(x) x ========== #Global Statement def func(): global x print('x is', x) x = 2 print('Changed global x to', x) x = 50 func() print('Value of x is', x) ======= #Default Argument Values def say(message, times=1): print(message * times) say('Hello') say('World', 5) say('Good Bye') #Keyword Arugment def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3, 8) func(24, c=26) func(c=29, a=39) #VarArgs parameters #Function_VarArgs.py def total(a=5, *numbers, **phonebook): print('a', a) for single_item in numbers: print('single_item', single_item) for first_part, second_part in phonebook.items(): print(first_part, second_part) total(10, 1, 2, 3, Jack=1123, John=2232, Inge=1459) #Return Statement def maximum(x, y): if x > y: return x elif x == y: return 'The numbers are equal' else: return y print(maximum(3,8)) print(maximum(20, 10))
a = int(input("Введите первый аргумент >>>")) b = int(input("Введите второй аргумент >>>")) c = int(input("Введите третий аргумент >>>")) def my_func(a, b, c): s = sorted((a, b, c), reverse=True) return s[0] + s[1] resilt = my_func(a, b, c) print(resilt)
#ASSIGNMENT1_SPICE1 from sys import argv, exit #sys is a module containing functions(argv()) #argv is a function is the list commandline arguments to program CIRCUIT = '.circuit' #assigning .circuit and .end END = '.end' if len(argv) != 2: #to check if there are two arguments(code & circuit) print('\nERROR: %s does not have an <inputfile>!!' % argv[0]) exit() #terminate the operation if arguments are not two try: f=open(argv[1]) #opening the file lines = f.readlines() #reading the each line f.close() #closing file after reading start = -1; #(closing the file is mandetory after reading or writing the file to save changes) end = -2 for line in lines: if CIRCUIT == line[:len(CIRCUIT)]: start = lines.index(line) #fecthing netlist file elif END == line[:len(END)]: end = lines.index(line) #end of file and avoid any junk break if start >=end: print('Wrong circuit description!') #checking for discrepancy if any exit(0) reverse_list=[] for line in reversed(lines[start+1:end]): token= line.split('#')[0].split() word=' '.join(reversed(token)) print(word) except IOError: print('Invalid file!') #terminate the code if any error occured exit()
import generator def test_ランダムな人名を生成できること(): random_name = generator.random_name() # LAST_NAME + FIRST_NAME で少なくとも2文字以上になる assert len(random_name) >= 2 def test_5回ランダムな人名を生成して重複がないこと(): name_list = [] for i in range(5): name_list.append(generator.random_name()) duplicated_list = [x for x in set(name_list) if name_list.count(x) > 1] assert len(duplicated_list) == 0 def test_ランダムな書籍名を生成できること(): random_book_name = generator.random_book_name() # 上の句 + 下の句 で少なくとも2文字以上になる assert len(random_book_name) >= 2 def test_ランダムな書籍名を5回生成して重複がないこと(): book_name_list = [] for i in range(5): book_name_list.append(generator.random_book_name()) # list を set に変換し、set 内の出現回数が 1 より大きい要素を抽出する duplicated_list = [x for x in set(book_name_list) if book_name_list.count(x) > 1] assert len(duplicated_list) == 0 def test_ランダムなemailを生成できること(): random_email = generator.random_email_address() assert random_email.endswith('@sample.test') assert len(random_email) >= 17 # 固定文字列 + ランダム文字列の最小の長さ assert len(random_email) <= 200 # 固定文字列 + ランダム文字列の最大の長さ def test_ランダムなemailを5回生成して重複がないこと(): email_list = [] for i in range(5): email_list.append(generator.random_email_address()) duplicated_list = [x for x in set(email_list) if email_list.count(x) > 1] assert len(duplicated_list) == 0
def multiples(): counter = 0 for i in range(1000): if(i%3==0 or i%5==0): counter += i print(counter) multiples()
# -*- coding: utf-8 -*- import operator def main(): index = [] keyword_main = [] book = [] page = [] print( "-----------------------------------------------------------------------") print( "| SANS Index Generator |") print( "-----------------------------------------------------------------------") print( "Please specify the current book that you are indexing (Ex. '542.2')" ) working_book = input("Current Book: ") print( "Please enter the book page keyword(s) and then the page number(s) for each entry." ) print( "Type 'quit' or 'exit' to save progress, generate html file, and exit this script.\n" ) with open('index.html', 'w') as file: file.write("<style>.title{color: black;font-weight: bold;}</style>\n") file.write("<style>.topic{color: blue;font-weight: bold;}</style>\n") file.write("<style>.command{color: red;font-weight: bold;}</style>\n\n") while True: keyword = '' keyword = input('Enter topic keyword(s) : ') if keyword == 'quit': break elif keyword == 'exit': break insert_book = str(working_book).strip() insert_page = input('Enter page number(s) : ') line = keyword + '\t' + insert_book + '\t' + insert_page with open('data_file', 'a') as output_file: output_file.write(line) output_file.write('\n') print ( 'Entry Added...\n' ) with open('data_file', 'r') as out_file: for line in out_file: line_list = line.strip().split('\t') keyword_list = line_list[0].split(' ') keyword_list[0] = keyword_list[0].capitalize() keyword_list = ' '.join(keyword_list) keyword_main.append(keyword_list) book.append(line_list[1]) page.append(line_list[2]) items = len(keyword_main) i = 0 while items > 0: index.append([keyword_main[i], book[i], page[i]]) i += 1 items -= 1 pos = 0 sorted_list = sorted(index, key=operator.itemgetter(0)) with open('index.html', 'a') as file: for item in sorted_list: key = item[0].strip('"').rstrip('"') # Create Section Header if key.startswith("A"): if pos == 0: file.write("<span class = 'title'>A</span><br>\n") pos = 1 elif key.startswith("B"): if pos != 2: file.write("<br><span class = 'title'>B</span><br>\n") pos = 2 elif key.startswith("C"): if pos != 3: file.write("<br><span class = 'title'>C</span><br>\n") pos = 3 elif key.startswith("D"): if pos != 4: file.write("<br><span class = 'title'>D</span><br>\n") pos = 4 elif key.startswith("E"): if pos != 5: file.write("<br><span class = 'title'>E</span><br>\n") pos = 5 elif key.startswith("F"): if pos != 6: file.write("<br><span class = 'title'>F</span><br>\n") pos = 6 elif key.startswith("G"): if pos != 7: file.write("<br><span class = 'title'>G</span><br>\n") pos = 7 elif key.startswith("H"): if pos != 8: file.write("<br><span class = 'title'>H</span><br>\n") pos = 8 elif key.startswith("I"): if pos != 9: file.write("<br><span class = 'title'>I</span><br>\n") pos = 9 elif key.startswith("J"): if pos != 10: file.write("<br><span class = 'title'>J</span><br>\n") pos = 10 elif key.startswith("K"): if pos != 11: file.write("<br><span class = 'title'>K</span><br>\n") pos = 11 elif key.startswith("L"): if pos != 12: file.write("<br><span class = 'title'>L</span><br>\n") pos = 12 elif key.startswith("M"): if pos != 13: file.write("<br><span class = 'title'>M</span><br>\n") pos = 13 elif key.startswith("N"): if pos != 14: file.write("<br><span class = 'title'>N</span><br>\n") pos = 14 elif key.startswith("O"): if pos != 15: file.write("<br><span class = 'title'>O</span><br>\n") pos = 15 elif key.startswith("P"): if pos != 16: file.write("<br><span class = 'title'>P</span><br>\n") pos = 16 elif key.startswith("Q"): if pos != 17: file.write("<br><span class = 'title'>Q</span><br>\n") pos = 17 elif key.startswith("R"): if pos != 18: file.write("<br><span class = 'title'>R</span><br>\n") pos = 18 elif key.startswith("S"): if pos != 19: file.write("<br><span class = 'title'>S</span><br>\n") pos = 19 elif key.startswith("T"): if pos != 20: file.write("<br><span class = 'title'>T</span><br>\n") pos = 20 elif key.startswith("U"): if pos != 21: file.write("<br><span class = 'title'>U</span><br>\n") pos = 21 elif key.startswith("V"): if pos != 22: file.write("<br><span class = 'title'>V</span><br>\n") pos = 22 elif key.startswith("W"): if pos != 23: file.write("<br><span class = 'title'>W</span><br>\n") pos = 23 elif key.startswith("X"): if pos != 24: file.write("<br><span class = 'title'>X</span><br>\n") pos = 24 elif key.startswith("Y"): if pos != 25: file.write("<br><span class = 'title'>Y</span><br>\n") pos = 25 elif key.startswith("Z"): if pos != 26: file.write("<br><span class = 'title'>Z</span><br>\n") pos = 26 if item[0] != "": file.write("<br><span class = 'topic'>%s </span><i>[book: %s / page(s): %s]</i><br>\n" % (item[0].strip('"').rstrip('"'), item[1], item[2])) else: pass if __name__ == "__main__": main()
"""https://twitter.com/Al_Grigor/status/1357028887209902088""" the_data = "aaaabbbcca" expected = [("a", 4), ("b", 3), ("c", 2), ("a", 1)] from timeit import timeit from datetime import datetime def solve1(data): return [("a", 4), ("b", 3), ("c", 2), ("a", 1)] start = datetime.now() print(solve1(the_data)) stop = datetime.now() assert solve1(the_data) == expected print(f"Found the solution in {stop - start} us") # print(f"Solved in {timeit(f'the_data'), setup='from __main__ import the_data, solve1'):3f} us") print("You did it!!!!") def solve2(data): character = data[0] c_count = 1 result = [] for c_next in data[1:]: if character == c_next: c_count = c_count + 1 else: result.append((character, c_count)) c_count = 1 character = c_next result.append((character, c_count)) return result print(solve1(the_data)) stop = datetime.now() assert solve2(the_data) == expected, solve2(the_data) print(f"Found the solution in {stop - start} us") print("You did it again!!!!") from itertools import groupby def solve3(data): result = [] for character, obj in groupby(data): result.append((character, len(list(obj)))) return result print(solve3(the_data)) stop = datetime.now() assert solve3(the_data) == expected, solve3(the_data) print(f"Found the solution in {stop - start} us") print("You did it again and again!!!!")
#!/usr/bin/env python3 # This script models the logic of the paginator used on the blog page. RANGE = 2 MAX = 17 CURRENT = 12 start = CURRENT - RANGE end = CURRENT + RANGE if start < 1: end = end + ((start * -1) + 1) start = 1 if end > MAX: start = start - (end - MAX) end = MAX if start < 1: start = 1 paginator = "|" if CURRENT != 1: paginator += " < PREV |" if start != 1: paginator += " << |" if start > 2: paginator += " ... |" for page in range(start, end + 1): page = page if page != CURRENT else "*{}*".format(page) paginator += " {} |".format(page) if end < MAX - 1: paginator += " ... |" if end != MAX: paginator += " >> |" if CURRENT != MAX: paginator += " NEXT > |" # Print the paginator view and start/end. print() print(start, end) print() print(paginator) print()
arr=[] arr.append(1); arr.append(1); for i in range(2,50): arr.append(arr[i-1]+arr[i-2]) for i in range(1,20): print arr[2*i-1]*arr[2*i]
class Service: # >>>> 답지 보고 추가1>>>> MOVE_TYPES = ('R', 'L', 'U', 'D',) def __init__(self, n, moves): self.n = self._make_map(n) self.move_li = [move for move in moves.split(" ")] self.location = [1, 1] self.move_fn = (self._right_move, self._left_move, self._up_move, self._down_move,) pass def __repr__(self): return f'{self.__class__}' @staticmethod def _make_map(n): li = list() for i in range(n): row = [] for j in range(n): row.append([i + 1, j + 1]) li.append(row) print(li) return li def run(self): for _, move in enumerate(self.move_li): for i, move_type in enumerate(self.MOVE_TYPES): if move_type == move: self.move_fn[i]() continue return self.location def _current_location(self, row, column): row -= 1 column -= 1 limit = len(self.n) - 1 if not (limit >= column >= 0 and limit >= row >= 0): print(row, column) print(self.location) print("좌표값을 벗어났습니다.") return self.location self.location = self.n[row][column] def _left_move(self): row, column = self.location column -= 1 self._current_location(row, column) def _right_move(self): row, column = self.location column += 1 self._current_location(row, column) def _up_move(self): row, column = self.location row -= 1 self._current_location(row, column) def _down_move(self): row, column = self.location row += 1 self._current_location(row, column)
class Person(object): """docstring for Person""" def __init__(self, name): self.name = name self.spent_money = 0 self.borrow = {} self.spent = 0 def spending(self, spent_money): self.spent_money += spent_money def paid(self, money, *args): self.spent += money self_money = money / len(args) for Person_obj in args: Person_obj.spending(self_money) self.set_borrow(Person_obj, self_money) def set_borrow(self, Person_obj, self_money): if Person_obj.name != self.name: if Person_obj.name in self.borrow: if self.borrow.get(Person_obj.name) <= self_money: diff = self_money - self.borrow.get(Person_obj.name) print("------------") print(diff, self.borrow.get(Person_obj.name), self_money) Person_obj.update_borrow(diff, self.name) self.borrow.update({Person_obj.name: 0}) elif self.borrow.get(Person_obj.name) > self_money: diff = self.borrow.get(Person_obj.name) - self_money print("++++++++++++") print(diff, self.borrow.get(Person_obj.name), self_money) self.borrow.update({Person_obj.name: diff}) else: Person_obj.update_borrow(self_money, self.name) def update_borrow(self, money, name): if self.borrow.get(name): money += self.borrow.get(name) self.borrow.update({name: money}) Dimas = Person("Dimas") Orest = Person("Orest") Vitalik = Person("Vitalik") Orest.paid(10, Dimas, Orest) Dimas.paid(20, Dimas, Orest) Dimas.paid(20, Dimas, Orest) Dimas.paid(200, Orest, Vitalik) Orest.paid(10, Dimas, Orest) Orest.paid(1000, Dimas, Orest, Vitalik) Dimas.paid(200, Dimas, Orest) Vitalik.paid(10, Dimas, Orest) Vitalik.paid(1000, Dimas, Orest) print(Dimas.name, Dimas.spent, Dimas.spent_money, Dimas.borrow) print() print(Orest.name, Orest.spent, Orest.spent_money, Orest.borrow) print() print(Vitalik.name, Vitalik.spent, Vitalik.spent_money, Vitalik.borrow) print()
#!/usr/bin/env python3 import colors as c from utils import ask text = '''My Crazy Pet once my pet {animal} was running around my {a place in your house} with a {explosive thing} straped to {his or her} back and then i lit the {same explosive you chose before} and went flying out of my front door and then exploded in my neighbors front yard. The End''' words = { "animal" : None, "a place in your house" : None, "explosive thing" : None, "his or her" : None, "same explosive you chose before" : None, } for key in words: words[key] = c.red + ask(key.rstrip('0123456789') + ': ') + c.reset print(c.clear + text.format(**words))
#!/usr/bin/env python3 import colors as c print(c.clear + c.blue + ''' Who shall cross the bridge of death must answer me three questions three 'Ere the other side he see. ''' + c.reset) def prompt(question): print(c.red + question + c.reset) answer = input('>' + c.base3).lower().strip() print(c.reset) return answer def live(): print('go ahead across the bridge') def die(): print('swim with the ACID!!!!!') name = prompt('what is your name?') quest = prompt('What is your quest?') if name in ['lancelot','galahad']: color = prompt('what is your favorite color') if color == 'blue': live() else: die() elif name == 'robin': capital = prompt ('What is the capital of Assyria?') if capital in ['assur','ashur']: live() else: die() elif name == 'arthur': speed = prompt('What is the air speed velocity of an unladen swallow?') if speed == '24mph': live() elif 'african or european swallow' in speed: print('Bridgekeeper dies.') live() else: die()
from cv2 import cv2 import numpy as np import os """A module for converting an image to sepia using only python. The module contains two functions: - sepia_filter for converting, and saving, an image to sepia - python_color2sepia for converting a ndarray representing an image to sepia """ def python_color2sepia(image_array): """Converts a color image array to sepia. Args: image (ndarray): 3D array of unsigned integers representing the color image. Returns: ndarray: 3D array of unsigned integers representing the sepia image. """ sepia_array = np.array(image_array) for row_index, row in enumerate(image_array): for column_index, column in enumerate(row): for channel in range(3): if channel == 0: # Blue B_weight = 0.131 G_weight = 0.534 R_weight = 0.272 elif channel == 1: # Green B_weight = 0.168 G_weight = 0.686 R_weight = 0.349 elif channel == 2: # Red B_weight = 0.189 G_weight = 0.769 R_weight = 0.393 B = column[0] * B_weight G = column[1] * G_weight R = column[2] * R_weight weighted_sum = B + G + R sepia_array[row_index, column_index, channel] = weighted_sum if weighted_sum < 255 else 255 return sepia_array.astype("uint8") def sepia_filter(input_filename): """Converts, and saves, a color image to sepia. The sepia image is written to the same directory as the original with _sepia appended to the original name. Args: input_filename (string): the image's filepath. Returns: ndarray: 3D array of unsigned integers, representing the sepia image. """ image_array = cv2.imread(input_filename) sepia_image = python_color2sepia(image_array) filename, file_extension = os.path.splitext(input_filename) cv2.imwrite(filename + "_sepia" + file_extension, sepia_image) return sepia_image
from requesting_urls import get_html import re def _get_num_month(text): """Returns the numerical value of month as string. Args: text (str): The month as a string. E.g. "Jan" or "January". Returns: str: The numerical value of the month as a string. """ #Shortened this method down to a list months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] for i, month in enumerate(months): if month in text: if i+1 < 10: return "0" + str(i+1) return str(i+1) return "" def _get_correct_day(day): """Returns the day with two digits as string. Args: day (str): The day E.g. "5" or "15". Returns: str: The day as a string with two digits. E.g. "05" or "15". """ if len(day) == 2: return day if len(day) == 1: return "0" + day return "" def find_dates(html, output=None): """Finds the dates in a string, and optionally saves the list to a file. The following date formats are supported: DMY: 13 October 2020 AND October 2020 MDY: October 13, 2020 AND October, 2020 YMD: 2020 October 13 ISO: 2020-10-13 Year must be between 0000 - 2999 Args: html (str): The string output (str, optional): The filename for saving the list of dates. Defaults to None. Returns: list of str: A list of the dates, sorted and without duplicates. """ dates = [] # Regex patterns # Date can be single digit date = r"((?:0?[1-9])|(?:[12][0-9])|(?:3[01]))" # Month can be abbreviated month = r"((?:(?:Jan)|(?:Feb)|(?:Mar)|(?:Apr)|(?:May)|(?:Jun)|(?:Jul)|(?:Aug)|(?:Sep)|(?:Oct)|(?:Nov)|(?:Dec))[a-z]{0,6})" # Year must be between 0000 - 2999 year = r"([012][0-9]{3})" # DMY (date optional) pattern_DMY = fr"\b{date}? ?{month} {year}\b" dates += [f"{date[2]}/{_get_num_month(date[1])}/{_get_correct_day(date[0])}" if len(date[0]) != 0 else f"{date[2]}/{_get_num_month(date[1])}" for date in re.findall(pattern_DMY, html, flags=re.M)] # MDY (date optional) pattern_MDY = fr"\b{month} ?{date}?, {year}\b" dates += [f"{date[2]}/{_get_num_month(date[0])}/{_get_correct_day(date[1])}" if len(date[1]) != 0 else f"{date[2]}/{_get_num_month(date[0])}" for date in re.findall(pattern_MDY, html, flags=re.M)] # YMD pattern_YMD = fr"\b{year} {month} {date}\b" dates += [f"{date[0]}/{_get_num_month(date[1])}/{_get_correct_day(date[2])}" if len(date[2]) != 0 else f"{date[0]}/{_get_num_month(date[1])}" for date in re.findall(pattern_YMD, html, flags=re.M)] # ISO (date can't be single digit) pattern_ISO = fr"\b{year}-((?:0[1-9])|(?:1[0-2]))-((?:0[1-9])|(?:[12][0-9])|(?:3[01]))\b" dates += [f"{date[0]}/{date[1]}/{date[2]}" for date in re.findall(pattern_ISO, html, flags=re.M)] # Sort and remove duplicates dates_sorted = sorted(set(dates)) if output is not None: with open(f"./filter_dates_regex/{output}.txt", "w") as file: file.write("\n".join(dates_sorted)) return dates_sorted if __name__ == "__main__": urls = ["https://en.wikipedia.org/wiki/Linus_Pauling", "https://en.wikipedia.org/wiki/Rafael_Nadal", "https://en.wikipedia.org/wiki/J._K._Rowling", "https://en.wikipedia.org/wiki/Richard_Feynman", "https://en.wikipedia.org/wiki/Hans_Rosling"] outputs = ["Linus_Pauling", "Rafael_Nadal", "JK_Rowling", "Richard_Feynman", "Hans_Rosling"] for url, output in zip(urls, outputs): html = get_html(url).text find_dates(html, output)
# ################################### №1 # my_list = [2, 400, 52, 560, 82, 14] # for symbol in my_list: # if symbol > 100: # print(symbol) # # ################################### №2 # my_list = [2, 400, 52, 560, 82, 14] # my_result = [] # for symbol in my_list: # if symbol > 100: # my_result.append(symbol) # print(my_result) # # ################################### №3 # my_list = [2, 22, 54, 124, 1, 2] # if len(my_list) < 2: # my_list.append(0) # else: # my_list.append(my_list[-1] + my_list[-2]) # print(my_list) # # #################################### №4 # value = input("Ввелите число с точкой:") # # try: # value = float(value) # print(value ** -1) # except (ValueError, ZeroDivisionError): # print("Неверный ввод") # # #################################### №5 # # my_list = [1, 11, 20, 100] # for index, symbol in enumerate(my_list): # if not (index + symbol) % 2: # print(symbol) # # #################################### №6 # my_list = [1, 11, 20, 100] # my_list_2 = [3, 33, 30, 300] # for index in range(len(my_list)): # print(my_list[index], my_list_2[index]) # # ############### or ##################### №6 # my_list = [1, 11, 20, 100] # my_list_2 = [3, 33, 30, 300] # for index, symbol in enumerate(my_list): # print(my_list[index], my_list_2[index]) #################################### №7 my_string_1 = "0123456789" my_string_2 = "0123456789" my_list = [] for symb_1 in my_string_1: for symb_2 in my_string_2: my_list.append(int(symb_1 + symb_2)) print(my_list)
# ------------------------------------------------------- # code template for assignment-1 # ------------------------------------------------------- import time import string def profanityFilter(aString, badWordList, subsitute_string="#%@$!"): # Write a function that replaces badWords in aString with the substitute string... # Note: do not change the substitute_string prior to submission remove = string.punctuation + string.whitespace # check for each bad words from badWordList for word in badWordList: #Check if the line has the bad word if word.lower() in aString.translate(None, remove).lower(): j = 0 #Begin from the start of the string and keep jumping to places #where first alphabet of the bad word is present while j < (len(aString) - len(word) + 1): start_position = aString[j:].lower().find(word[0]) if start_position < 0: break start_position = start_position + j; #Check if the immediate next set of alphabets(ignoring special charatcers) #has the remaining letters of the bad word if aString[start_position:].translate(None, remove)[0:len(word)].lower() == word.lower(): aString = aString[:start_position] + subsitute_string[0] + aString[start_position+1:] #overwrote first alphabet of bad word current_position = start_position+1 #Keep looking for other alphabets of the bad word and keep replacing them for i in range(1,len(word)): start_position = aString[current_position:].lower().find(word[i].lower()) aString = aString[:start_position+current_position] + subsitute_string[i] + aString[start_position+current_position+1:]; current_position = current_position + start_position + 1 j = current_position else: j = start_position + 1; return aString # ------------------------------------------------------- if __name__ == "__main__": theStartTime = time.time() #here we open a file that contains the list of badwords to be removed... with open('unsavoury_word.txt') as theBadWordFile: badWords = filter(None, (line.rstrip() for line in theBadWordFile)) #Here we send sample user input from a given file to your profanity filter... with open('input.txt') as theSampleInputFile, open('out.txt', 'w') as theOutputFile: for theSampleInput in theSampleInputFile: theOutputFile.write(profanityFilter(theSampleInput, badWords) + '\n') theOutputFile.write('elapsed: ' + str( time.time() - theStartTime) + '\n')
n = int(input()) li = list(map(int, input().split())) def is_prime(a): if a == 2: return True elif a == 1 or a % 2 == 0: return False else: for i in range(3, int(a ** 0.5), 2): if a % i == 0: return False return True def chck(a): s = int(a ** 0.5) if s * s == a and is_prime(s): return "YES" else: return "NO" for l in li: print(chck(l))
import math def calc_delta(a,b,c): delta = b**2 - 4 * a * c return delta a = float(input("a: ")) b = float(input("b: ")) c = float(input("c: ")) delta = calc_delta(a, b, c) if delta > 0: x1 = (-b + math.sqrt(delta)) / (2*a) x2 = (-b - math.sqrt(delta)) / (2*a) print(f"x1: {x1} e x2: {x2}") elif delta == 0: x = (-b + math.sqrt(delta)) / (2*a) print(f"x: {x}") else: print("Não possui raízes reais")
#Swap var x = "abc" y = "defij" print("before swap: x = ", x, " y = ", y) x = x + y y = x[:len(x)-len(y)] x = x[len(y):] print("after swap: x = ", x, " y = ", y)
##Code to do Bubble Sort### # Keep left part of the array sorted # Big O : O(N*N) #global step_counter; step_counter = 0; def selection_sort(list): global step_counter; for j in range(0,len(list)-1): step_counter += 1; index = find_smallest ( list[j:len(list)] ) + j; if (index != j): list[index], list[j] = list[j], list[index]; print("The sorted list is :" + str(list)) print("Steps needed to sort :" + str(step_counter)); def find_smallest(list): global step_counter; smallest_num = list[0]; smallest_num_index = 0; for i in range(0, len(list)-1): step_counter += 1; if(smallest_num > list[i+1]): smallest_num = list[i+1]; smallest_num_index = (i+1); return smallest_num_index; a = [0, 11, 2, -7, 200]; selection_sort(a);
import sys class Handler: """ Base class for all handlers. Does nothing until subclassed. """ def __init__(self): pass def run(self, input, retcode, frame): """ Default behavior is to call action first to do whatever actions the user specifies in a custom handler, then finish to determine the next step (call next command, exit, etc...). Override this method to define custom behavior for a handler. """ out = self.action(input, retcode, frame) return self.finish(out, retcode, frame) def action(self, input, retcode, frame): print "You need to override this method to do anything useful." def finish(self, output, retcode, frame): print "You need to override this method to do anything useful." class OutHandler(Handler): """ Basic handler attached to a command to call the next command in the pipe. Subclass this and override the action method to create custom output handlers for your needs. """ def __init__(self): """ Set the type of the handler """ self.type = "out" def action(self, input, retcode, frame): """ Does nothing but pass the stdout of the command into self.finish() """ # print "stdout: {0}".format(input[0]) return input[0] def finish(self, output, retcode, frame): """ Flow control: If there are more handlers to be run, call the next handler Else if there is a next command, call next command with this output Otherwise, return the output. """ if frame.hasHandler(): handler = frame.nextHandler() return handler.run(output, retcode, frame) elif frame.hasCommand(): cmd = frame.nextCommand() return cmd.execute(output, frame) else: return output class ErrHandler(Handler): """ Basic error handler attached to a command to define behavior in the case of an error occuring. Default behavior is to print the error and then exit the pipe. Subclass this and override action to define custom error handling behavior, and override finish if you don't want to exit upon error. """ def __init__(self): """ Set the type of the handler """ self.type = "err" def action(self, input, retcode, frame): """ Print an error message with the command that errored, then print the stderr stream of the command. """ cmd = frame.currentCommand() print >> sys.stderr, "Error encountered in Command: {cmd}\n".format(cmd=" ".join(cmd.cmd)) print >> sys.stderr, input[1] print >> sys.stderr, "exit code: {0}".format(retcode) return None def finish(self, output, retcode, frame): """ Exit the pipe """ sys.exit(retcode)
"""Luke Sexton""" def main(): valid_password = password_checker() while valid_password is False: print("Invalid.") valid_password = password_checker() for star in range(valid_password): print('*', end=' ') def password_checker(): length_min = 5 user_password = input("Please enter a password with 6 or more characters: ") if len(user_password) <= length_min: return False else: count_character = 0 for char in user_password: if char.isalpha(): count_character += 1 return count_character main()
# Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. def fileToList(file): alist = [] with open(file, 'r') as open_file: line = open_file.readline() while line: line = line.strip() if line not in alist: alist.append(line) line = open_file.readline() return alist happylist = fileToList("happynumbers.txt") primelist = fileToList("primenumbers.txt") commonlist = [] commonlist = [a for a in happylist if a in primelist] print (commonlist) print ("Lists have",len(commonlist),"elements in common")
# Asks the user how many Fibonacci numbers to generate and then generates them. f = [] number = int(input ("how many Fibonnaci numbers do you want? ")) def seqGen(number): for x in range (number): if len(f) > 1: y = f[x-1]+f[x-2] f.append(y) else: f.append(1) return f print (seqGen(number))
def split_sentence(stri): """ Rule 1) split sentence with '.' . Output as list""" sentences = stri.split('.') return sentences def split_words(sentence): """ Output as list""" sentence = sentence.strip() words = sentence.split(' ') return words def detect_keyword(word): return word.isupper() def check_keyword_type(): """Detect <> <<>> and return keyword type""" pass string = """IF you are not BULKING, THEN follow ORDER 1)INCREASE PROTEIN, 2)INCREASE FAT, 3)INCREASE CARBOHYDRATE. IF you are <FAT>, THEN first CUT your existing body fat WITH save your existing muscle mass. by calory deplet, then if you are lean go to calory surplus.""" sentences = split_sentence(string)[:-1] for sentence in sentences: words = split_words(sentence) keywords = [word for word in words if detect_keyword(word)] print(keywords)
""" Você deve fazer um programa que leia um valor qualquer e apresente uma mensagem dizendo em qual dos seguintes intervalos ([0,25], (25,50], (50,75], (75,100]) este valor se encontra. Obviamente se o valor não estiver em nenhum destes intervalos, deverá ser impressa a mensagem “Fora de intervalo”. """ # Entrada n = float(input()) # Cálculo/Saída if n >= 0.0 and n <= 25.0: print('Intervalo [0,25]') elif n > 25.0 and n <= 50.0: print('Intervalo (25,50]') elif n > 50.0 and n <= 75.0: print('Intervalo (50,75]') elif n > 75.0 and n <= 100.0: print('Intervalo (75,100]') else: print('Fora de intervalo')
""" Leia um valor inteiro. A seguir, calcule o menor número de notas possíveis (cédulas) no qual o valor pode ser decomposto. As notas consideradas são de 100, 50, 20, 10, 5, 2 e 1. A seguir mostre o valor lido e a relação de notas necessárias. """ # Entrada n = int(input()) print(n) # Saída m = [100, 50, 20, 10, 5, 2, 1] for x in m: r = int(n / x) n = n % x print('{} nota(s) de R$ {},00'.format(r, x)) # while n > 0: # x = n // m[i] # n = n % m[i] # print('{} nota(s) de R$ {},00'.format(x, m[i])) # i += 1
""" Leia 3 valores de ponto flutuante A, B e C e ordene-os em ordem decrescente, de modo que o lado A representa o maior dos 3 lados. A seguir, determine o tipo de triângulo que estes três lados formam, com base nos seguintes casos, sempre escrevendo uma mensagem adequada: se A ≥ B+C, apresente a mensagem: NAO FORMA TRIANGULO se A2 = B2 + C2, apresente a mensagem: TRIANGULO RETANGULO se A2 > B2 + C2, apresente a mensagem: TRIANGULO OBTUSANGULO se A2 < B2 + C2, apresente a mensagem: TRIANGULO ACUTANGULO se os três lados forem iguais, apresente a mensagem: TRIANGULO EQUILATERO se apenas dois dos lados forem iguais, apresente a mensagem: TRIANGULO ISOSCELES Entrada A entrada contem três valores de ponto flutuante de dupla precisão A (0 < A) , B (0 < B) e C (0 < C). Saída Imprima todas as classificações do triângulo especificado na entrada. """ # Testes # n = '7.0 5.0 7.0'.split() # TRIANGULO ACUTANGULO / TRIANGULO ISOSCELES # n = '6.0 6.0 10.0'.split() # TRIANGULO OBTUSANGULO / TRIANGULO ISOSCELES # n = '6.0 6.0 6.0'.split() # TRIANGULO ACUTANGULO / TRIANGULO EQUILATERO # n = '5.0 7.0 2.0'.split() # NAO FORMA TRIANGULO # n = '6.0 8.0 10.0'.split() # TRIANGULO RETANGULO # Entrada de dados n = input().split() # Ordenar dados n = [float(i) for i in n] n.sort(reverse=True) # Converter dados A, B, C = n A = float(A) B = float(B) C = float(C) # Configurar mensagem msg=[] if A >= B + C: msg.append('NAO FORMA TRIANGULO') elif A**2 == B**2 + C**2: msg.append('TRIANGULO RETANGULO') elif A**2 > B**2 + C**2: msg.append('TRIANGULO OBTUSANGULO') elif A**2 < B**2 + C**2: msg.append('TRIANGULO ACUTANGULO') if A == B == C: msg.append('TRIANGULO EQUILATERO') elif A == B or B == C or C == A: msg.append('TRIANGULO ISOSCELES') # Print print(*msg, sep='\n')
''' Leia os quatro valores correspondentes aos eixos x e y de dois pontos quaisquer no plano, p1(x1,y1) e p2(x2,y2) e calcule a distância entre eles, mostrando 4 casas decimais após a vírgula, segundo a fórmula: ''' # Teste # p1 = '12.1 7.3'.split(' ') # p2 = '-2.5 0.4'.split(' ') # 16.1484 # Entrada p1 = input().split(' ') p2 = input().split(' ') # Atribuir valores x1,x2,y1,y2 x1 = float(p1[0]) y1 = float(p1[1]) x2 = float(p2[0]) y2 = float(p2[1]) # Cálculo d = ((x2 - x1)**2 + (y2 - y1)**2)**(1/2) # Saída print('{:.4f}'.format(d))
def longest(sentence): list1 = sentence.split(" ") max = 0 for item in list1: if len(item)>max and len(item)%2==0: max=item actual_item=item print(actual_item)
from math import sin, cos, sqrt, atan2, radians from features_from_response import df #функция расчета между координатами комнаты и центром (условно Кремль) kreml_lat = 55.7522 kreml_lng = 37.6156 #функция расчета между координатами комнаты и центром (условно Кремль) def distances(data): # approximate radius of earth in km R = 6373.0 dlat = [lat for lat in data['lat'] - kreml_lat] dlon = [lng for lng in data['lng'] - kreml_lng] dist = {'lat': [lat for lat in data['lat'] - kreml_lat], 'lng': [lng for lng in data['lng'] - kreml_lng]} # dist = zip(dlat, dlon) print(type(dist)) print(len(dist), len(data['lat']), len(data['lng']), len(dlat), len(dlon)) distances = [] for dlat, dlon in dist.items(): lat2 = radians((int(dlat)) + int(kreml_lat)) dlat = radians(dlat) dlon = radians(dlon) a = sin(dlat / 2)**2 + cos(kreml_lat) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c distances.append(distance) return distances df['distance'] = distances(df)
"""Exercício Python 063: Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. """ n = int(input('Número: ')) a1 = -1 a2 = 1 for c in range(0, n ): a3 = a1 + a2 print(a3, end=' ') a1 = a2 a2 = a3
"""Exercício Python 056: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos.""" lista = [] velho = 0 cont = 0 soma = 0 nome = '' for c in range(1, 5): print('-------------{}ª pessoa------------'.format(c)) n = input('Nome: ') ida = int(input('Idade: ')) gen = str(input('Gênero[F/M]: ')).lower().strip() soma += ida if gen in 'f' and ida < 20: cont += 1 if ida > velho: if gen == 'm': nome = n velho = ida print('Média de idade do grupo: {}' '\nNome do homem mais velho: {}' '\nNúmero de mulheres com menos de 20 anos: {}'.format(soma / 5, nome, cont))
"""Exercício Python 077: Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais.""" lista = ('banana', 'maça', 'salada', 'ferro', 'cobre', 'matematica', 'carro', 'isopor') for palavra in lista: print(f'\n{palavra} → ', end='') for letra in palavra: if letra.lower() in 'aeiou': print(f'{letra} ', end='')
#Exercício Python 045: Crie um programa que faça o computador jogar Jokenpô com você. from random import randint from time import sleep lista = ('pedra', 'papel', 'tesoura') escolha = int(input('[0]Pedra ' '\n[1]Papel ' '\n[2]Tesoura ' '\nEscolha uma das opções: ')) pc = int(randint(0, 2)) print('Pedra...') sleep(1) print('Papel...') sleep(1) print('Tesoura!!!') sleep(0.5) if escolha == 0 or escolha == 1 or escolha == 2: print('Você jogou {} e o Computador jogou {}'.format(lista[escolha], lista[pc])) else: print('Valor inválido!') if escolha == pc: print('EMPATE') elif escolha == 0 and pc == 1 or escolha == 1 and pc == 2 or escolha == 2 and pc == 0: print('VOCÊ PERDEU!!!') elif escolha == 0 and pc == 2 or escolha == 1 and pc == 0 or escolha == 2 and pc == 1: print('VOCÊ GANHOU!!!')
"""Exercício Python 073: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times. b) Os últimos 4 colocados. c) Times em ordem alfabética. d) Em que posição está o time da Chapecoense.""" time = ('Flamengo', 'Santos', 'Palmeiras', 'Grêmio', 'Athletico-PR', 'São Paulo', 'Internacional', 'Corinthians', 'Fortaleza', 'Goiás', 'Bahia', 'Vasco da Gama', 'Atlético-MG', 'Fluminense', 'Botafogo', 'Ceará SC', 'Cruzeiro', 'CSA', 'Chapecoense', 'Avaí') c = time.index('Chapecoense') print(f'a) {time[0:5]} ' f'\nb) {time[-4:]} ' f'\nc) {sorted(time)} ' f'\nd) {c + 1}')
def linha(): linha = ("*"*35) return linha print(linha()) hora = float(input(f"Quanto você ganha por hora: R$ ")) mes = float(input(f"Quantas horas você trabalha por mes: ")) resultado = (hora * mes) print(linha()) print(f'Seu Salário Bruto no final do mês é R$ {resultado}') print(linha()) ir = (11 * resultado)/100 inss = (8*resultado)/100 sindicato = (5*resultado)/100 print("Descontos: \n" f"Imposto de Renda - 11% = R$ {ir}\n" f"Imposto - 8% = R$ {inss} \n" f"Sindicato - 5% = R$ {sindicato}" ) print(linha()) print(f"Total de decontos - R$ {ir + inss + sindicato}") print(linha()) print(f"Com os descontos mensais seu salário liquido no final do mês é de R$ {resultado - ir - inss- sindicato}") print("*"*75)
from __future__ import annotations from typing import List class Node(object): def __init__(self, value: str, children: List[Node], is_word: bool): self.is_word = is_word self.value = value self.children = children def __repr__(self): return ( f"value: {self.value}\n" + f"children: {self.children}\n" + f"is_word: {self.is_word}\n" ) class Trie: def __init__(self, root: Node): self.root = root def insert(self, word: str) -> bool: word = word.lower() # Start at root and see if the prefix exists current_node = self.root for i, char in enumerate(word): if i == 0: for j, node in enumerate(current_node.children): if node.value == char: current_node = current_node.children[j] break else: # If we are at the end of the word is_word is true is_word = True if i == len(word) - 1 else False current_node.children.append(Node(char, [], is_word)) current_node = current_node.children[-1] if i > 0: # If it exists, check the next etc.. if char == current_node.value: continue if char != current_node.value: for j, node in enumerate(current_node.children): if node.value == char: current_node = current_node.children[j] break else: # If we are at the end of the word is_word is true is_word = True if i == len(word) - 1 else False current_node.children.append(Node(char, [], is_word)) current_node = current_node.children[-1] def search(self, word: str) -> bool: word = word.lower() current_node = self.root for i, char in enumerate(word): if i == 0: for j, node in enumerate(current_node.children): if node.value == char: current_node = current_node.children[j] break else: return False if i > 0: # If it exists, check the next etc.. if char == current_node.value: continue if char != current_node.value: for j, node in enumerate(current_node.children): if node.value == char: current_node = current_node.children[j] break else: return False return current_node.is_word if __name__ == "__main__": root = Node("", [], False) trie = Trie(root) trie.insert("dap") trie.insert("data") print(trie.search("dap")) print(trie.search("pad")) trie.insert("pad") print(trie.search("pady")) print(root.children[0].children[0].children)
""" Split an array in such a way that both sides are equal in value. If this is not possible, return -1 """ def splitArr(array): total = 0 leftSubArr = [] rightSubArr = [] for i in range(len(array)): total += array[i] target = total / 2 leftSum = 0 lastLeft = 0 for i in range(len(array)): if leftSum < target: leftSum += array[i] leftSubArr.append(array[i]) else: lastLeft = i break rightSum = 0 for j in range(lastLeft, len(array)): if rightSum < target or j == len(array): rightSum += array[j] rightSubArr.append(array[j]) else: break if leftSum == rightSum: print(leftSubArr) print(rightSubArr) return True return False print(splitArr([1, 6, 4, 3])) print(splitArr([1, 4, 6, 3])) print(splitArr([1, 2, 3, 4, 5, 5]))
def triple_step(n): ls = [None] * (n + 1) if n == 0: return 1 if n == 1: return 2 ls[0] = 0 ls[1] = 1 ls[2] = 1 for i in range(3, n + 1): ls[i] = ls[i - 1] + ls[i - 2] + ls[i - 3] return ls[-1] if __name__ == "__main__": print(triple_step(5))
""" Checks if a string is a rotation of another string """ def is_substring(s1, s2): return (s1 in s2) or (s2 in s1) def omni_rotate(l, n): return l[-n:] + l[:-n] def string_rotation(s1, s2): if len(s1) != len(s2): return False if s1 == s2: return True for i in range(0, len(s1)): new_s = omni_rotate(list(s2), i) if ''.join(new_s) != s1: continue else: return True return False def string_rotation_option(s1, s2): return is_substring((s1 + s1), s2) if len(s1) == len(s2) else False print(string_rotation('waterbottle', 'erbottlewat')) print(string_rotation('water', 'rwate')) print(string_rotation('lala', 'laul')) print('Other method') print(string_rotation_option('waterbottle', 'erbottlewat')) print(string_rotation_option('water', 'rwate')) print(string_rotation_option('lala', 'laul'))
""" Left rotation rotates an array left. [1, 2, 3, 4, 5, 6, 7] After 2 rotations [3, 4, 5, 6, 7, 1, 2] d = number of rotations n = size of array """ def left_rotation(array, d, n): while d is not 0: temp = array[0] for i in range(n - 1): array[i] = array[i + 1] array[n-1] = temp d -= 1 return array print(left_rotation([1, 2, 3, 4, 5, 6, 7], 2, 7))
""" Calculates the determinant via the laplace expansion """ def det(A): dets = [] coeffs = {} det_helper(A, coeffs, dets) for k, v in coeffs.items(): dets[k] = multiply_each(dets[k], v) return formulate(dets) def formulate(ls): total = ls[0] neg = True for i in range(1, len(ls)): if neg: total -= ls[i] neg = False else: total += ls[i] neg = True return total def multiply_each(v, ls): for i in ls: v *= i return v def safe_add(coeefs, key, value): if key not in coeefs: coeefs[key] = [] coeefs[key].append(value) return coeefs def construct_intermediate_mat(small_mat, bad_col_idx): new_mat = [] for row in small_mat: new_mat.append([*row[0:bad_col_idx], *row[bad_col_idx + 1:]]) return new_mat def remove_top(mat): new_mat = [] for i in range(1, len(mat)): new_mat.append(mat[i]) return new_mat def p(A): string = "[\n" for l in A: string += f"{repr(l)}\n" string += "]\n" return string def det_helper(A, coeffs, dets): print(p(A)) if len(A) == 2: det = (A[0][0] * A[1][1]) - (A[0][1] * A[1][0]) # print(" dets.append(det) return None top_row = A[0] for i, coef in enumerate(top_row): coeffs = safe_add(coeffs, i, coef) new_mat = construct_intermediate_mat(remove_top(A), i) det_helper(new_mat, coeffs, dets) if __name__ == "__main__": # print(det([[1, 2, 3], [2, 1, 3], [3, 2, 1]])) print(det([[1, 2, 3, 4], [2, 1, 3, 4], [3, 2, 1, 4], [4, 3, 2, 1]]))
numbers = list(range(1000)) def isPrime(num): output = True for x in range(2,num): if num % x == 0 and num !=x: output = False return output def theFilter(data,f): result = [] for x in data: result.append(x) return result filtered2 = theFilter(numbers,isPrime) print(filtered2) #filtered = list(filter(isPrime,numbers)) #print(filtered)
def mymap(f,list1): result = [] for i in list1: result.append(f(i)) return result def calculate(list1,c): return mymap(c,list1) def g(x): return x * x numbers = [1,2,3,4,5,6] print(calculate(numbers,g)) #print(calculate(numbers,g))
def du(l): if len(l) == 0 or len(l) == 1: return l else: if l[0] in l[1:]: return du(l[1:]) else: return [l[0]] + du(l[1:]) print(du([5,33,5]))
class Solution: def assignBikes(self, workers: [[int]], bikes: [[int]]) -> [int]: workerBikePair = [] for i in range(len(workers)): for j in range(len(bikes)): workerBikePair.append((self.manhattanDistance(workers[i],bikes[j]),i,j)) workerBikePair.sort() isBikeAssigned={x:False for x in range(len(bikes))} assignment=[-1 for i in range(len(workers))] for i in range(len(workerBikePair)): if assignment[workerBikePair[i][1]]==-1 and not isBikeAssigned[workerBikePair[i][2]]: assignment[workerBikePair[i][1]]=workerBikePair[i][2] isBikeAssigned[workerBikePair[i][2]]=True return assignment def manhattanDistance(self,p1,p2): return abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) print(Solution().assignBikes([[0,0],[2,1]],[[1,2],[3,3]]))
import sys import wifi_activate filename = "/etc/wpa_supplicant/wpa_supplicant.conf" #file to be changed to add a network def connect(name, password): key_mgmt = "WPA-PSK" #default type check= bool(True) # read the file and check SSID and Psk fh =open(filename,"r") for line in fh: split_list=line.split('"') if name in split_list: next_line= fh.next() split_list_password=next_line.split('"') if password in split_list_password: print "Already configured" check= False break fh.close() # append to the config file if not configured already if check: Fh_append= open(filename,"a") string1 = "\nnetwork={\n" string2=' ssid="{s}"\n psk="{p}"\n key_mgmt={k}'.format(s= name,p= password,k= key_mgmt) string3="\n}\n\n" string_concated= string1+ string2 +string3 # formatting the string to appropriate one Fh_append.write(string_concated) Fh_append.close() get_value=wifi_activate.activate() # calls "activate" function from the "wifi_activate" module to activate the change print get_value
def actual_printing(word): print(word.upper()) print(word.lower()) def printing_letters(word): for letter in word: print(letter) def main(): word = input("type in a sentence.") actual_printing(word) printing_letters(word) if __name__ == '__main__': main()
name = "John" print ("Hello %s!" %name) age=23 print("%s is %s years old."%(name,age) ) mylist = [1,2,3] print ("A list: %s" %mylist)
####################################################################### # This script compares the speed of the computation of a polynomial # for different in-memory libraries: numpy and numexpr. Always using # a single thread here. # # Author: Francesc Alted # Date: 2013-09-04 ####################################################################### from time import time from numpy import linspace, sin, cos import numexpr as ne N = 10*1000*1000 # the number of points to compute expression x = linspace(-10, 10, N) # the x in range [-1, 1] expr = ".25*x**3 + .75*x**2 - 1.5*x - 2" # 1) the polynomial to compute #expr = "((.25*x + .75)*x - 1.5)*x - 2" # 2) a computer-friendly polynomial #expr = "x" # 3) the identity function #expr = "sin(x)**2+cos(x)**2" # 4) a transcendental function what = "numpy" # uses numpy for computations #what = "numexpr" # uses numexpr for computations ne.set_num_threads(1) # the number of threads for numexpr computations def compute(): """Compute the polynomial with `nt` threads.""" global expr if what == "numpy": if expr == "x": # Trick to force a copy with NumPy y = x.copy() y = eval(expr) else: y = ne.evaluate(expr) return y if __name__ == '__main__': print(f'Computing: {expr} using {what} with {N} points') t0 = time() result = compute() ts = time() - t0 print(f'*** Time elapsed: {ts:.3f} s')
import csv import pandas as pd df = pd.read_csv('./bosydi.csv') baseDf = df.drop_duplicates('name.2') #this is the df i will be using throughout listOfBP = baseDf['name'].unique() checker = True chcker = False ################################TESTING############################################################# #print(baseDf['name.2'].unique()) #print(len(baseDf['name.2'].unique())) #print(baseDf['name.1'].unique()) #print(len(baseDf['name.1'].unique())) #print(baseDf['name'].unique()) #print(len(baseDf['name'].unique())) #print(df.nunique()) #print(len(df)) ################################TESTING############################################################# #To get the body part and the symptoms from th user23-77 print("what part of your body seems to be troubling you?, please select a body part from this list") print(baseDf['name'].unique()) while chcker == False: while checker == True: bp = input() checker = bp in listOfBP if checker == False: print("please enter a valid body part") chcker = checker checker = True break chcker = True break symBaseDf = baseDf.drop_duplicates('name.1') ListOfSym = baseDf['name.1'].unique() checker1 = True chcker1 = False print("Please select a symptom from this list?") print(baseDf['name.1'].unique()) while chcker1 == False: while checker1 == True: sy = input() checker1 = sy in ListOfSym if checker1 == False: print("please enter a valid symptom") chcker1 = checker1 checker1 = True break print("is there any other symptom, please enter it or say 'no'") msy = input('') if msy == 'no': checker1 = False chcker1 = True break checker1 = msy in ListOfSym if checker1 == False: print("please enter a valid symptom") chcker1 = checker1 checker1 = True break chcker1 = True break print("Your diagnosis is most likely:") #To return the diagnosis according to the user input sym1Name = baseDf.loc[(baseDf['name'] == bp) & (baseDf['name.1'] == sy) & (baseDf['is_common'] == 1), ['name.2', 'description', 'symptoms', 'workup', 'treatment']] notCommon1 = baseDf.loc[(baseDf['name'] == bp) & (baseDf['name.1'] == sy) & (baseDf['is_common'] == 0), ['name.2', 'description', 'symptoms', 'workup', 'treatment']] if msy == 'no': sym2Name = '' notCommon2 = '' else: sym2Name = baseDf.loc[(baseDf['name'] == bp) & (baseDf['name.1'] == msy) & (baseDf['is_common'] == 1), ['name.2', 'description', 'symptoms', 'workup', 'treatment']] notCommon2 = baseDf.loc[(baseDf['name'] == bp) & (baseDf['name.1'] == msy) & (baseDf['is_common'] == 0), ['name.2', 'description', 'symptoms', 'workup', 'treatment']] print("common diagnosis: " + sym1Name, sym2Name) print() #print("less common diagnosis: " + notCommon1, notCommon2) choice=input('would you like to view the doctors list (Enter Y or N):') if choice.upper() == 'Y': with open('select_doctor_file1.csv', mode='r') as file: doctors_list =csv.reader(file) for lines in doctors_list: print(lines)
import os def rename_files(): file_list = os.listdir(r"C:\Trey\Teo\alphabet") #You will have to insert your own directory here. saved_path = os.getcwd() print("Current Directory is "+saved_path) os.chdir(r"C:\Trey\Teo\alphabet") #And insert it here. for file_name in file_list: os.rename(file_name, file_name.translate(None, "1234567890")) os.chdir(saved_path) rename_files()
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: def search(nums, left, right, target): if left < right: mid = (left+right)//2 if nums[mid] == target: return mid elif nums[mid] < target: return search(nums, mid+1, right, target) else: return search(nums, left, mid-1, target) else: if target > nums[left]: return left+1 else: return left if len(nums) == 0: return 0 left, right = 0, len(nums)-1 idx = search(nums, left, right, target) return idx
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: # 规则1 for i in range(9): flag = [0] * 9 for j in range(9): item = board[i][j] if not item == '.' : if flag[int(item)-1] == 0: flag[int(item)-1] = 1 else: return False # 规则2 for j in range(9): flag = [0] * 9 for i in range(9): item = board[i][j] if not item == '.' : if flag[int(item)-1] == 0: flag[int(item)-1] = 1 else: return False # 规则3 flatten = [j for i in board for j in i] start = [3*i + 27*j for j in range(3) for i in range(3)] add = [0, 1, 2, 9, 10, 11, 18, 19, 20] for i in start: flag = [0] * 9 for j in add: item = flatten[i+j] if not item == '.' : if flag[int(item)-1] == 0: flag[int(item)-1] = 1 else: return False return True
class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ def search(nums, left, right, target): while(left<=right): index = (left+right) // 2 if nums[index] == target: return index elif nums[index] > target: return search(nums, left, index-1, target) elif nums[index] < target: return search(nums, index+1, right, target) return -1 def enlargeRange(nums, index): left = index right = index while left > -1 and nums[left]==nums[index]: left -= 1 while right < len(nums) and nums[right]==nums[index]: right += 1 return [left+1, right-1] size = len(nums) if size == 0: return [-1,-1] left = 0 right = size-1 index = search(nums, left, right, target) if index == -1: return [-1, -1] return enlargeRange(nums, index)
from random import randint def mysort(arr): for i in range(len(arr)): for j in range(len(arr) - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] # A simple test if __name__ == '__main__': cnt = 0 for _ in range(100): arr = [randint(-100, 100) for i in range(100)] correct = sorted(arr) mysort(arr) if arr == correct: cnt += 1 print("acc: {:.2f}%".format(cnt / 100 * 100))