text
stringlengths
37
1.41M
from header import * #the flow of this algorithm is designed as follow: #1.prepare the Bell state #2.implement the algorithm according to Nielsen and L.Chuang def teleportation(): c = Circuit(True) #store the unknow quantum state, the aim of this algorithm is teleporting the state of AliceQ to BobQ AliceQ = Qubit()...
from tkinter import * root = Tk() root.title("Tic Tac Toe - Two Player Game") player=True status=None count=0 class TicTacToe: def __init__(self,master): frame=Frame(master) menu1 = Menu(root) root.config(menu=menu1) subMenu = Menu(menu1) menu1.add_cascade...
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None self.height = 1 class AVL: def getHeight(self, root): if not root: return 0 return root.height def insert(self, root, key): # Step 1 - Perform no...
#These are the enemy classes (includes boss) from random import randrange class enemy: #creates enemy character def __init__(self): self.hpp = 35 self.aep = 15 self.mapp = 3.0 self.rapp = 1.0 self.lp = 1 #allows access to and setting of...
from random import randint, shuffle from munkres import Munkres, print_matrix # mentors: [a,b,c,d] # mentees: [z,q,w,y] # votes: [mentorId,mentorId,mentorId,mentorId,mentorId] <<< per mentee nMentee = i = 20 nMentor = nMentee maxSelectedMentors = 3 matrix = [] while i > -1: i -= 1 entry = [1, 2, 3] if...
import math from fractions import Fraction import itertools def next(top,root,plus): newbottom = root-plus**2 if newbottom%top==0: newbottom,top = newbottom/top,1 else: print "wtf!" plusser = int(float(top)*(math.sqrt(root) -plus)/newbottom) return (plusser,(newbottom,root,-plus-plu...
def split_into_2(array): length = len(array) result = [] flag = False if length % 2 != 0: last_array = [array.pop()] flag = True i = 0 while i < length - 1: if array[i] < array[i + 1]: result.append([array[i], array[i + 1]]) else: result.ap...
def is_string_int(s): """ This function takes in the parameter s as a string and returns True if s can be safely converted to an int. It returns False otherwise. """ pass def is_string_float(s): """ This function takes in the parameter s as a string and returns True if s can be safely...
import copy #Get an array initialized, 15x15 def make_board(): """ A board is a list of lists of dictionaries. board[r][c] is the dictionary representing the square at row r and column c A dictionary representing a square can have: * A key 'letter' that contains a single letter that is played at ...
# chapter 8 exercise # create a function that will return a string of the type of data passed def checkType(var): var = str(var) if(var.isalpha()): return 'alpha' elif(var.isdigit()): return 'number' elif(var.isalnum()): return 'aphanum' else: return 'unknown' var = input('input something:\n') print...
#chapter 4 exercise #create fibonacci sequence and stop at the first number greater than 100 #Fn = Fn-2+Fn-1, inital values F0=0 and F1=1 Fn = 0 F0 = 0 F1 = 1 check = False while True: Fn = F0 + F1 F1 = F0 F0 = Fn if(Fn > 100): check = True #print('check true') else: check = False print(Fn) if(check == T...
# Store input # create var name number_map number_map = [] height, width = map(int, input().split()) # first line for line in height: # map lines number_map.append(list(map(int, input().split()))) T = int(input()) # number of test cases nodes = {} # For each test case for i in range(T): ...
``` Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character ...
``` Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 1...
``` You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make. Example 1: Input: "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: "AAABBC" Outp...
``` A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to determine if a number is strobogrammatic. The number is represented as a string. Example 1: Input: "69" Output: true Example 2: Input: "88" Output: true Example 3: Input: "962" Outp...
``` A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that nums[-1] = nums[n] = -∞. Exam...
``` Given an input string , reverse the string word by word. Example: Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] Note: A word is defined as a sequence of non-space characters. The input string does not contain leading ...
age=int(input("Enter your age")) print("sex? (M or F)") sex=input("Enter your sex") print("Married? (Y or N)") married=input("Enter your status") if sex=="F" and age>=20 and age<=60: print("Work in Urban area only") elif sex=="M" and age>=20 and age<=40: print("Work anywhere") elif sex=="M" and age>40 and age<=...
alienColor=input("Enter color") if alienColor=="green": print("earn 5 points ") elif alienColor!="green": print("earn 10 points")
name=input("Enter you name: ") password=input("Enter your password: ") if name=="tejuchoudhary": if password=="TEJU12": print("Successful Login") else: print(name,password,"You have entered incorrect password or name") name1=input("Enter you name: ") if name=="tejuchoudhary": ...
"""Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).""" class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() max_product = (nums[-1] -1) * (nums[-2] -1) ...
# while True: # try: # miles = input('请输入英里数:') # km = int(miles) * 1.609344 # print(f'等于{km}公里') # except ValueError: # print('你输入了非数字字符') # try: # choice = input('输入你的选择:') # if choice == '1': # 100/0 # else: # [][2] # except ZeroDivisionError: # ...
def methode_rectanglesdr(a, b, n): integrale = 0.0 hauteur = float(b-a)/n for k in range(n+1): integrale += (hauteur * k + a)**2 integrale = integrale * hauteur return integrale print "Rectangle droit pour x**2 avec n = 10 : " print methode_rectanglesdr(0, 1, 10)
from pandas import read_csv from matplotlib import pyplot # Display the time series plots/graphs def display(file, type): series = read_csv(file, encoding="ISO-8859-1", header=0, index_col=0, parse_dates=True, squeeze=True) # Loads the dataset and print the first 5 rows if type == "table": print(s...
''' Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right subtree is the maximum tree constructed from right pa...
#coding=utf-8 ''' Given a singly 1-linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true Follow up: Could you do it in O(n) time and O(1) space? ''' #如果让头部节点在"归"的过程中,配合递归时逆向行驶的节点,做相向的移动,有两种方式: #1. "递"结束之后,返回头部,每次"归"时,返回节点next #2. 在递归函数之外,定义一个头部节...
#coding=utf-8 ''' Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters. Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longe...
#coding=utf-8 ''' You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is n...
''' Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. ''' def lengthOfLIS_dp(nums): if not nums: return 0 N = len(nums) dp = [1] ...
#coding=utf-8 ''' Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1,4] Output: 2 Explanat...
''' Given an 2-array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. ''' #1.use python api #2.one pass , by recording dict[target-curN] = curIdx, # judge if curN in di...
#coding=utf-8 ''' Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0. ''' import collections def calcEquation(equations, values, queries): ...
#coding=utf-8 ''' Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] ''' #用part == part[::-1]判断回文,没必要单独写函数 #注意审题,不是返回每个回文子串的集合,而是回文子串列表构成的集合 #对当前输入列表(字符串)进行切片,作为下一层的递归输入 de...
def longestCommonPrefix(strs): if not strs: return "" if len(strs) == 1: return strs[0] prefix = "" strs.sort() for i,j in zip(strs[0], strs[-1]): if i == j: prefix += i else: break return prefix strs = ["alower","flow","flight"] print longestCommonPrefix(strs)
def searchInsert(nums, target): cnt = len(nums) lo,hi = 0, cnt-1 while lo < hi: mid = (lo+hi)/2 if nums[mid] == target: return mid elif nums[mid] < target: lo = mid+1 else: hi = mid return lo+1 if cnt>0 and nums[lo] < target else lo n...
''' 1. Hashmap provides Insert and Delete in average constant time, although has problems with GetRandom. The idea of GetRandom is to choose a random index and then to retrieve an element with that index. There is no indexes in hashmap, and hence to get true random value, one has first to convert hashmap keys ...
def maxSubArray(nums): """ :type nums: List[int] :rtype: int """ maxsum = cursum = nums[0] for num in nums[1:]: cursum = max(cursum + num, num) maxsum = max(maxsum, cursum) return maxsum
#coding=utf-8 ''' Reverse a singly 1-linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A 1-linked list can be reversed either iteratively or recursively. Could you implement both? ''' class ListNode(object): def __init__(self, x): self.val = x self.next = No...
''' Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. ''' # Let's use three pointers i2,i3,i5 ,to mark the last ugly numbe...
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ hist = {} for i, num in enumerate(nums): j = hist.get(target - num, -1) if j >= 0: return [j, i] hist[num] = i
''' Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. ''' def integerBreak(n): dp = [i-1 for i in range(n+1)] for i in range(2,n+1): for j in range(1,i): dp[i] = max(dp[i...
''' A sequence X_1, X_2, ..., X_n is fibonacci-like if: n >= 3 X_i + X_{i+1} = X_{i+2} for all i + 2 <= n Given a strictly increasing 2-array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0. ''' import collections def lenLong...
#coding=utf-8 ''' Implement a basic calculator to evaluate a simple expression 5-string. The expression 5-string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . The expression 5-string contains only non-negative integers, +, -, *, / operators , open ...
#coding=utf-8 ''' Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: nums = [2,3,1,1,4] Output: true Explanation: Jum...
#coding=utf-8 #Binary tree could be constructed from preorder/postorder and inorder traversal. #Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder). class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None cl...
''' Given an array A of 0s and 1s, we may change up to K values from 0 to 1. Return the length of the longest (contiguous) subarray that contains only 1s. Example 1: Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray i...
#coding=utf-8 ''' Given an 2-array A of non-negative integers, the 2-array is squareful if for every pair of adjacent elements, their sum is a perfect square. Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i]. Ex...
#coding=utf-8 ''' You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.) Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number o...
#coding=utf-8 ''' A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. For exampl...
def findMin(nums): cnt = len(nums) left, right = 0, cnt-1 if cnt == 1: return nums[0] if nums[0] < nums[-1]: return nums[0] if (cnt ==2 and nums[0]>nums[1]) or (cnt > 2 and nums[0] > nums[1] and nums[1]>nums[2]): return nums[-1] while left < right: mid = (left+...
#coding=utf-8 ''' There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language. Examp...
''' Find the kth largest element in an unsorted 2-array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 <= k <= 2-array's...
''' Given an 2-array nums, there is a sliding window of size k which is moving from the very left of the 2-array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 Output:...
''' 1081. Smallest Subsequence of Distinct Characters Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once. Example 1: Input: "cdadabcc" Output: "adbc" ''' def smallestSubsequence(text): stack = [] for i, c in enumerate(text): if c i...
#coding=utf-8 ''' We have a sequence of books: the i-th book has thickness books[i][0] and height books[i][1]. We want to place these books in order onto bookcase shelves that have total width shelf_width. We choose some of the books to place on this shelf (such that the sum of their thickness is <= shelf_width), th...
''' There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house i, we can either build a well inside it directly with cost wells[i], or pipe in water from another well to it. The costs to lay pipes between houses are given by the 2-array pipes, where ...
#enconding: utf-8 def fact(n): if n < 0: return None mul = 1 for i in range(1,n+1): mul *= i return mul print(fact(-1)) print(fact(0)) print(fact(5))
# 构建基本的二叉树 class Node: def __init__(self, elem): self.elem = elem self.lchild = None self.rchild = None # list_1 = [1,2,3] # list_2 = [1,2,3] # A, B, C = [ Node(i) for i in list_1 ] # A.lchild, A.rchild = B, C # D, E, F = [ Node(i) for i in list_2 ] # D.lchild, D.rchild = E, F class Tree...
# encoding: utf-8 # 选择排序 时间复杂度O(n^2) 空间复杂度 O(1) 不稳定 def selection_sort(arr): """选择排序 :param arr:需要排序的列表 :return: 排序完成的列表 """ length = len(arr) for i in range(length - 1): minIndex = i for j in range(i + 1, length): if arr[j] < arr[minIndex]: minInde...
# 实现 strStr() 函数。 # 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。 # 示例 1: # 输入: haystack = "hello", needle = "ll" # 输出: 2 # 示例 2: # 输入: haystack = "aaaaa", needle = "bba" # 输出: -1 # 说明: # 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 # 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 s...
# 核心思路 # 建立两个指针,一个从开始指一个,另一个指下一个,一样就弹出第二个,不一样就递增 # 反思一下 这么简单的想法,为什么我就没想到??? def test(nums): pre = 1 while pre < len(nums): if nums[pre-1] == nums[pre]: nums.pop(pre) else: pre = pre + 1 return len(nums) nums = [0,0,1,1,1,2,2,3,3,4] print(test(nums))
import csv with open('data.csv', encoding='utf-8') as f: reader = csv.reader(f) header = next(reader) print(header) for i in reader: print(i)
# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 # 示例 1: # 输入: 123 # 输出: 321 # 示例 2: # 输入: -123 # 输出: -321 # 示例 3: # 输入: 120 # 输出: 21 # 注意: # 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31,  2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。 def test(x): if x > 0: a = int(str(x)[::-1]) return a if a < 2**31 - 1 else 0 eli...
# 编写一个函数来查找字符串数组中的最长公共前缀。 # 如果不存在公共前缀,返回空字符串 ""。 # 示例 1: # 输入: ["flower","flow","flight"] # 输出: "fl" # 示例 2: # 输入: ["dog","racecar","car"] # 输出: "" # 解释: 输入不存在公共前缀。 # 说明: # 所有输入只包含小写字母 a-z 。 # 注意看题 前缀!!!,随便比两个就行 # 利用python的max()和min(),在Python里字符串是可以比较的,按照ascII值排,举例abb, aba,abac,最大为abb,最小为aba。所以只需要比较最大最小的公共前缀就是整个数...
# enconding: utf-8 def test(n): if 1 <= n <= 10**5: Product = 1 Sum = 0 while(n): Product *= n % 10 Sum += n % 10 n //= 10 return Product - Sum n = 234 print(test(n))
#enconding: utf-8 def key(n): return n def key2(n): return n[1] def key3(n): return n['age'] def bubble(l,key): length = len(l) for j in range(length - 1): for i in range(length - 1): if key(l[i]) > key(l[i+1]): l[i+1],l[i] = l[i],l[i+1] l1 = [5,4,3] bubble(...
# encoding: utf-8 import queue def quick_queue_sort(array): work_queue = queue.Queue() quick_data = QuickData(0, len(arr) - 1, arr) work_queue.put(quick_data) while work_queue.qsize() > 0: data = work_queue.get_nowait() i = data.head j = data.tail compare = array[data.he...
#enconding;utf-8 num1 = [1,2,3,4,5,6,7,8,9] num2 = [1,2,7,8,11,1230] result = [] for num in num1: if num in num2 and num not in result: result.append(num) # result.append(num) print(result)
#Written By Collin Lakeland #Program to solve a quadratic in standard form #Completed on December 20th, 2013 from __future__ import division #division module makes it so the division operator doesn't round the quotient import cmath #cmath module allows for complex solutions import sys c...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return str(self.val) def inorderTraversal(root: TreeNode): if not root: return [] visited = set() stack = [root] ans = [] while len(stack) > ...
def check_n(ch): return ord(ch) >= ord('1') and ord(ch) <= ord('9') class Solution: def isValidSudoku(self, board) -> bool: for i in range(9): row_set = set() for j in range(9): ch = board[i][j] if ch == ".": continue if not chec...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def buildTree_helper(start_inor, end_inor, preorder_dict, inorder_dict, preorder, inorder): if start_inor >= end_inor: return None root = TreeNode(pr...
from typing import List from collections import deque class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: m = len(board) n = len(board[0]) if board[click[0]][click[1]] == "M": board[click[0]][click[1]] = "X" return b...
import turtle turtle.shape('classic') def drawRect(side): turtle.pendown() turtle.color('red', 'yellow') turtle.begin_fill() for i in range(4): turtle.forward(10 + int(side)) turtle.left(90) turtle.penup() turtle.goto(-side*0.5, -side*0.5) for i in range(10,50,10): ...
a = int(input("Primeiro valor: ")) b = int(input("Segundo valor: ")) if a > b : print ("O primeiro numero é maior!") if b > a : print ("O segundo numero é maior!") if a == b : print ("Os numeros são iguais") idade = int(input("Digite a ideia de seu carro: ")) if idade <= 3: print ("Seu carro é novo!") if idade > ...
#!/usr/bin/python num1 = 1 num2 = 2 print num1 + num2 print num1 - num2 print num1 * num2 print num1 / num2 print num1 % num2 num1 = num1 + 2 print num1 print "Hello Wold" # feita validacao prog = raw_input("Qual a melhor linguagem de programacao: ") if prog == "python": print "Voce acertou" else: print "...
#!/usr/bin/python def func1(): print "Entrou na funcao 1" def func2(): print "Entrou na funcao 2" def func3(): print "Entrou na funcao 3" def switch(x): dict_func = {1:func1,2:func2,3:func3} dict_func[x]() # podemos fazer assim: # switch(1) # ou assim: x = input("Digite um valor de 1 a 3: ") switch(x) # ou...
#!/usr/bin/python ## uso o import sys para o sys.exit() no sair do programa import sys ## mais sobre funcoes nome = "" senha = "" def cadastrar_usuario(): # buscar uma variavel global global nome global senha nome = raw_input("Digite o login do novo usuario: ") senha = raw_input("Digite a senha do novo usuario...
custos = [] custo = str(input("Digite o nome do custo: ")) valor = str(input("Digite o valor: ")) custos['custo'] = 'valor' print(custos)
# Considere a empresa de telefonia Tchau. # Abaixo de 200 minutos, a empresa cobra R$ 0,20 por minuto. # Entre 200 a 400 minutos, o preço é R$ 0,18. Acima de 400 minutos o preço por # minutos o preço por minuto é R$ 0,15. # Calcule sua conta de telefone. a = 0.20 b = 0.18 c = 0.15 valor = int(input("Quantos minutos ...
# 汉诺塔 """ Hanoi(A,C,n): if n = 1 then move(A,C) //将最大的盘子移动到C上 else Hanoi(A,B,n-1) //以C为中间柱,将n-1 个盘子移动到B上 move(A,C) //将当前最大的盘子移动到C上 Hanoi(B,C,n-1) //以A为中间柱,将n-1 个 盘子移动到C上 """ # ----------------实现----------------- def Hanoi(A,C,B,n): #开始 结束 中间柱 if n == 1: print(A,"-->",C) else: ...
with open("Day10Input.txt") as file: read_data = file.read() input_list = read_data.split('\n') input_numbers_list = [int(i) for i in input_list] input_numbers_list.append(0) input_numbers_list.append((max(input_numbers_list) + 3)) input_numbers_set = set(input_numbers_list) set_sorted = sorted(input_numbers_set) ...
def make_prime_generator(): n= 2 def primes(): nonlocal n found_prime = False while not found_prime: n += 1 found_prime = True for i in range(2,n): if n % i == 0: found_prime = False return n return primes
# CS 61A Fall 2014 # Name: Kevin L. Chen # Login: cs61a-sj def interval(a, b): """Construct an interval from a to b.""" "*** YOUR CODE HERE ***" if type(a) != int or type(b) != int: return [a,b] return range(a,b+1) def lower_bound(x): """Return the lower bound of interval x.""" "*** YO...
# # @lc app=leetcode id=67 lang=python3 # # [67] Add Binary # # https://leetcode.com/problems/add-binary/description/ # # algorithms # Easy (38.13%) # Total Accepted: 281K # Total Submissions: 736.8K # Testcase Example: '"11"\n"1"' # # Given two binary strings, return their sum (also a binary string). # # The input...
from typing import * class Solution: def combine(self, n: int, k: int) -> List[List[int]]: nums = list(range(1, k+1)) + [n + 1] output, j = [], 0 while j < k: output.append(nums[:k]) j = 0 while j < k and nums[j + 1] == nums[j] + 1: nums[j...
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ # t = sorted(nums1[:m]+nums2) # for i in range(len(t)): # nums1[i] = t[i] j = 0 for i in ran...
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ # This is basically a binary search # Transfer to 2D array arr = [] for i in matrix: for j in i: ...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None # Do in order traversal. The in order traversal is monotonically increase # O(1) Space, can not use iterative method or recursive solution, both use space # c...
string = 'aabbcddcef' def delete_char(string): try: print(string[0] == string[0+1]) for i in range(len(string)): if(string[i] == string[i+1]): print(string) string = string[:i] + string[i+2:] return True, string except IndexError: ...
class Solution: # Solution 1, similar to find the pivot solution def find_pivot(self, nums): if len(nums) <= 2: return nums.index(min(nums)) left, right = 0, len(nums) - 1 while right > left: if right - left == 1: return nums.index(min(nums...
import os import csv from operator import itemgetter months = 0 revenue = 0 changeinmonth = [] monthChanges = [] csvpath = os.path.join('..', 'Resources', 'budget_data.csv') #budget_data with open(csvpath, newline='') as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = c...
import turtle as t scale = 100 def move_to(x, y): t.penup() t.goto(x, y) t.pendown() def draw_kiyeok(xs = 1): x,y = t.pos() t.pendown() t.setheading(0) t.forward(scale * xs) t.right(100) t.forward(scale / 2) move_to(x, y) def draw_nieun(xs = 1): x, y = t.pos() t.pendown() t.setheading(270) t.forward(s...
import ctypes def make_array(size): return (size * ctypes.py_object)() arr = make_array(5) # for i in range(5): # arr[i] = i*i arr = [None]*5 print(arr[2]) # for i in range(5): # print(arr[i]) # class Node: # def __init__(self, val): # self.value = val # self.rightChild = None # ...
class Node: def __init__(self,val): self.value = val self.next = None def __str__(self): return "value : %d" % self.value node = Node(1) node.next = Node(5) node.next.next = Node(3) node.next.next.next = Node(2) node.next.next.next.next = Node(4) node.next.next.next.next.next = Node(7...
def partition(slist, low , high): if low < high: i = (low - 1) pivot = slist[high] for j in range(low,high): if slist[j] <= pivot: i+= 1 slist[i],slist[j] = slist[j],slist[i] slist[i+1],slist[high] = slist[high],slist[i+1] return ...
# Assignment 4 # Hangman Plus # Anthony Swift import random WORDS = ( "PYTHON", "ESTIMATE", "DIFFICULT", "ANSWER", "XYLOPHONE", \ "UNNECESSARY", "ADEQUATE", "FEASIBLE", "CHARACTER", \ "CONGRATULATIONS", "SEQUENCE", "POSITION", "PROGRAM" ) MAX_WRONG = 6; word = random.choice(WORDS) so_far = "-" * len(...
# -*- coning:utf-8 -*- # 迭代器 class Fib(): def __init__(self): self.a, self.b = 0, 1 # 实现了__iter__方法的对象是可迭代的 def __iter__(self): return self # 实现了__next__()方法的对象是迭代器 def __next__(self): self.a, self.b = self.b, self.a + self.b if self.a > 100: raise Sto...
# -*- coding:utf-8 -*- """ 可迭代对象(Iterable):只要定义了__iter__()方法,我们就说该对象是可迭代对象,并且可迭代对象能提供迭代器。 a. 集合数据类型,如list、tuple、dict、set、str等; b. 是generator,包括生成器和带yield的generator function。 迭代器、迭代对象 :实现了__next__()或者next()(python2)方法的称为迭代器,迭代器仅仅在迭代到某个元素时才计算该元素, ...