text
stringlengths
37
1.41M
# for + break fruits = ['apple', 'banana', 'orange', 'pear'] for fruit in fruits: if fruit.startswith('o'): print(f'Found: {fruit}') break print('end') print() # for + continue for fruit in fruits: if fruit.startswith('o'): continue print(f'Fruit: {fruit}') print('end') print() #...
class Person: def __init__(self, name, age): self.name = name self.__age = age print(f'Creating {self.name} with age of {self.__age}') def greet(self): print(f'Hello {self.name} at age of {self.__age}') @property def age(self): return self.__age @age.setter...
x = {'a': 1, 'b': 2} y = {'c': 3, 'd': 4} print(f"{x = }, {y = }") m = x.copy() m.update(y) print(f"{m = }") m = {**x, **y} # Py 3.5 print(f"{m = }") m = x | y # Py 3.9 print(f"{m = }")
names = ['Alice', 'Bob', 'Charlie'] ages = [20, 25, 30] pairs = zip(names, ages) pairs = list(pairs) print(pairs) print(list(zip(*pairs)))
# read line by line fh = open('file.txt') for line in fh: print(line.strip('\n')) fh.close()
class UnionFind(object): '''Implementation of Union Find (a.k.a. Disjoint Set) data structure, with 'union by rank' optimization.''' def __init__(self, n): self.leader = list(range(n)) self.rank = [0 for i in range(n)] def find(self, elem): if elem != self.leader[elem]: ...
import forca import adivinhacao def escolhe_jogo(): print("*********************************") print("*******Escolha o seu jogo!*******") print("*********************************") print("(1) Forca (2) Adivinhação") jogo = int(input("Qual jogo? ")) if (jogo == 1): print("...
# coding: utf-8 # Estrutura de dados: List valores = [] print("Tipo da variavel valor {}".format(type(valores))) valores = [0,1,2,3,4] print("*******************************") print("**LISTA = > ", valores, "**"); print("*******************************") print("Tamanho da Lista {}" .format(len(valores))) print("...
rank = int(input('What rank would you like to calculate Thue-Morse\'s sequence to? ')) + 1 print('nth Sequence') print('===========================================================================') def thue_morse(previous): for bit in previous: if bit=='0': yield '01' elif bit=='1': yield '10' for i in...
import math def new(x, y): return x, y def translate(a, b): return x+a, y+b def rotate(a, b, c): return (round(a + math.cos(-c)*(x-a) - math.sin(-c)*(y-b), 3), round(b + math.sin(-c)*(x-a) + math.cos(-c)*(y-b), 3)) def scale(a, b, c): return a+(x-a)*c, b+(y-b)*c def reflect(axis): if axis in 'Xx': return...
#!/usr/bin/env python3 import math # https://projecteuler.net/problem=20 # Use divmode in a loop. num = math.factorial(100) total = 0 while (num != 0): num, dig = divmod(num, 10) total += dig print(total)
#!/usr/bin/env python3 import math def reverseDigitsOf(n: int): """ Returns the digits of the given number in reverse order. :param n: an integer number """ while n != 0: n, d = divmod(n, 10) yield d def isPrime(i: int): """ Returns True if the given number is a prime, False if no...
#!/usr/bin/env python3 import math # https://projecteuler.net/problem=27 # Brute force algorithm. def isPrime(num): if num < 2: return False for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True best = (0, 0, 0) # number of primes, a, b for a i...
#!/usr/bin/env python # coding: utf-8 # In[ ]: #python program for simple calculator #now here is function to add two numbers try: def add(number1,number2): return number1+number2 #now here is function to substract two numbers def sub(number1,number2): return number1-number2 #now her...
country = input('请问你是哪国人: ') age = input('输入你的年龄: ') age = int(age) if country == '中国': if age >= 18: print('你可以考驾照') else: print('你还不能考驾照') elif country == '美国': if age >= 16: print('你可以考驾照') else: print('你还不能考驾照') else: print('只能输入 中国/美国')
''' Sequence motifs are short, recurring patterns in DNA that are presumed to have a biological function. Often they indicate sequence-specific binding sites for proteins such as nucleases and transcription factors (TF). Given two strings s and t, t is a substring of s if t is contained as a contiguous collection of s...
#!/usr/bin/env python ''' Title: Independent Alleles Rosalind ID: LIA URL: http://rosalind.info/problems/lia/ Two Events A and B are Independent if Pr(A and B) = Pr(A) x Pr(B). Given: two (+) integers k (k <= 7) and N (N <= 2^k) Begin with Tom who is the 0th generation and is Aa Bb. He has two childre...
import xlrd import re import datetime from internal import * def check(x,y,z): regex = '^\w+([\.-]?\w+)@\w+([\.-]?\w+)(\.\w{2,3})+$' error=" " if (y==0)or(y==3)or(y==4)or(y==5)or(y==13) : flag=0 if all(k.isalpha() or k.isspace() for k in x): flag=1 if (flag=...
def RPN(alge): rpn_string = "" operators = [] for token in alge: if token in ['+','-','*','/','^']: operators.append(token) elif token == ')': rpn_string += operators.pop() elif token != '(': rpn_string += token return rpn_string for i in range(int(input())): # alge = input() print(RPN(input()))...
#!/usr/bin/env python3 ############################################################################ # time2words.py - A program to display the current time as words (e.g. # 09:31:00 = "Nine thirty one AM" # # HISTORICAL INFORMATION - # # 2017-07-02 msipin Inspired by the great Physics Denier, Eric P....
def add(): x=input('Enter the value of x:') y=input('Enter the value of y:') z=int(x)+int(y) print("The result of addition = ",z) def sub(): x=input('Enter the value of x:') y=input('Enter the value of y:') z=int(x)-int(y) print("The result of subtraction = ",z) def mul(): x=input('Enter the v...
largest = None for itervar in [3, 41, 12, 9, 74, 15]: if largest is None or itervar > largest : largest = itervar print('Largest:',largest)
def chop(arr): j=0 while(j<5): if(j==0): arr[j]=" " j=j+1 elif(j==4): arr[j]=" " j=j+1 else: j=j+1 return arr arr=["0","0","0","0","0"] i=0 while(i<5): arr[i] = input("Enter element in list\n") i=i+1 arr=chop(arr) print(arr)
# string_name = "navgurukul" # if "s" in string_name: # print ("s hai") # else: # print ("s nahi hai") user=input("enter the password:-") if(user>='A' and user<='Z'): if (user=="2" or user=="8"): if "@" or "#" in user: print("password is rigth") else: print("password is wrong") ...
# -*- coding: utf-8 -*- """ Created on Tue Aug 11 17:47:09 2020 @author: laramos """ import numpy as np def compute_bmi(weight,height): bmi = weight/(height**2) return bmi weight = 65 height = 1.76 print(compute_bmi(weight,height))
import json def clear_string(color_string): #we have two cases red is returnstring='' split_string = color_string.split("-") #['', 'r123', 'g456', 'b789'] #if the colors dont contain 3 digits then we have to do fillings with the zero. for substring in split_string: if substring.startswi...
import resource import random import time names = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas'] majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business'] print('Memory (before): {}Mb'.format(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)) def people_list(num_people): results = [] for i in r...
#!/usr/bin/python3 def new_in_list(my_list, idx, element): other_list = my_list.copy() if (idx < 0 or idx > len(my_list) - 1): return other_list for i in range(0, len(my_list)): if i == idx: other_list[i] = element return other_list
import form as f import pandas as pd print(f) all_data = [f.date,f.first_name,f.last_name,f.age,f.phone_number,f.mail,f.lic,f.cert,f.refer,f.lang,f.prog,f.add] requested = ["english","python","javascript"] employee = [] exist = [] grade = 0 employee.append(f.languages) employee.append(f.programming) for i in employ...
from .board import Board, Player, BoardState from . import const import time from typing import Tuple class Game: """Описывает игровой процесс.""" def __init__(self): self.board = Board() self.moves_durations = list() self.players_times = [const.GAME_TIME_LIMIT for i in range(2)] ...
#!/usr/bin/python f = open('input.txt', 'r') total_valid = 0 for line in f.readlines(): listofwords = {} valid = True for i in line.split() : # convert string to a list and sort it string_list = list(i) string_list.sort() # convert list back to string sorted_str = '...
# -*- coding: utf-8 -*- """ Created on Mon Oct 26 13:16:21 2020 @author: Aspect """ board_list = ["1","2","3","4","5","6","7","8","9"] lst = ["","","","","","","","",""] def display_board(board_list): #displays a 3 by 3 tic-tac-toe board to the users, with numbers 1-9 in playable spots p...
# -*- coding: utf-8 -*- """ Created on Thu Nov 19 13:50:22 2020 @author: Aspect Unit Converter (temp, currency, volume, mass and more) - Converts various units between one another. The user enters the type of unit being entered, the type of unit they want to convert to and then the value. The program will t...
def calculate_euclid_algorithm(number1,number2): #Function for Algorithm if number1 == 0: return number2 elif number2 == 0 : return number1; reminder = number1%number2; #Check the Reminder return calculate_euclid_algorithm(number2,reminder) # Return Function value def euler_function(n): counter ...
''' 一次性读取指定分割符的超大文件 ''' ''' f : 文件 newline : 分隔符 size : 一次性读取多少字符 ''' def myreadlines(f,newline,size=4096): buf="" while True: while newline in buf: pos=buf.index(newline) yield buf[:pos] buf=buf[pos+len(newline):] chunk=f.read(size) if not ...
# _*_ coding: utf-8 _*_ __author__ = 'Air Zhuang' __date__ = '2018/4/26 18:25' ''' 如何进行线程之间的通讯 使用标准库中的Queue.Queue,他是一个线程安全的队列 ''' from threading import Thread from collections import deque from queue import Queue #这是一个线程安全的队列 import os path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"\\test\\8_2.txt"...
""" 迭代器模式 Python内置对迭代器模式的支持 比如我们可以用for遍历各种Iterable的数据类型 Python里可以实现__next__和__iter__实现迭代器 """ from collections import deque class Stack: def __init__(self): self.deque=deque() #或者用list def push(self,value): self.deque.append(value) def pop(self): return self.deque.pop() de...
from random import randint def randGen(aList): while len(aList)>0: yield aList.pop(randint(0,len(aList))-1) for i in randGen([1,2,3,4,5]): print(i) print() '''--------------------------''' def gen_123(): #一个生成器函数 yield 1 yield 2 yield 3 print(gen_123) print(gen_123()) for i in gen_12...
import operator from functools import reduce,partial '''https://blog.csdn.net/felaim/article/details/71082031''' '''operator.mul''' def f(n): print(reduce(lambda a,b:a*b,range(1,n+1))) #等同 print(reduce(operator.mul,range(1,n+1))) f(4) print() triple=partial(operator.mul,3) #使用partial把一个两参数函数改编成需要单参数的可调用对象...
''' 尽量用ThreadPoolExecutor进行多线程编程 线程模块: Python3 通过两个标准库 _thread 和 threading 提供对线程的支持。 _thread 提供了低级别的、原始的线程以及一个简单的锁,它相比于 threading 模块的功能还是比较有限的。 threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法: threading.currentThread(): 返回当前的线程变量。 threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 thre...
import heapq """ 获取大量元素 topk 大个元素,固定内存 思路: 1、先放入元素前k个建立一个最小堆 2、迭代剩余元素: 如果当前元素小于堆顶元素,跳过该元素(肯定不是前k大) 否则替换堆顶元素为当前元素,并重新调整堆 """ class TopK: def __init__(self,iterable,k): self.minheap=[] self.capacity=k self.iterable=iterable def push(self,val): if len(self.minheap)>=self.c...
# _*_ coding: utf-8 _*_ __author__ = 'Air Zhuang' __date__ = '2018/4/24 23:23' from High_Level_Coding_python3.area.lib1 import Circle from High_Level_Coding_python3.area.lib2 import Triangle from High_Level_Coding_python3.area.lib3 import Rectangle from operator import methodcaller def getArea(shape): #第一种方式:get...
''' 如何将多个小字符串拼接成一个大字符串 ''' pl=["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"] #使用字符串的 + 缺点:开销巨大 s='' for i in pl: s+=i print(s) print() #使用reduce方法 from functools import reduce from operator import add print(reduce(str.__add__,pl)) print(reduce(lambda a,b:a+b,pl)) print(reduce(add,pl)) print() ...
import array ''' array比list性能高很多 array和list的一个重要区别:array只能存放指定的数据类型 Type code C Type Python Type Minimum size in bytes Notes 'b' signed char int 1 'B' unsigned char int 1 'u' Py_UNICODE Unicode character 2 (1) 'h' signed shor...
from collections import defaultdict from random import randint #旧方法 user_dict={} users=["bobby1","bobby2","bobby3","bobby1","bobby2","bobby2"] for user in users: if user not in user_dict: user_dict[user]=1 else: user_dict[user]+=1 print(user_dict) print() '''fromkeys()''' '''创建并返回一个新字典,以序列seq中...
''' 如何读取文本文件 ''' import os path=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #python3 写入读取 ff=open(path+"\\5_1.txt",'w',encoding='utf8') ff.write('你好python3') ff.close() ff=open(path+"\\5_1.txt",'r',encoding='utf8') ss=ff.read() print(ss) #python2 写入读取 # f=open(path+"\\file\\5_1.txt",'w') # s=u'你好py...
from random import randint ''' 如何在列表,字典,集合中根据条件筛选数据 ''' #传统办法 data=[randint(-10,10) for _ in range(10)] print(data) res=[] for i in data: if i>0: res.append(i) print("传统方法:",res) #列表:filter函数 data2=[randint(-10,10) for i in range(10)] print(data2) lf=list(filter(lambda x:x>=0,data2)) #在python3中,filter返回...
'''不可散列,意味着值可变在set([11,22,33])是ok的,在set([11,22,[33,44]])不ok 因为列表里的元素包含列表是可变的,无法进行hash操作 可散列:意味着值不可变并可进行hash操作''' class Vector2d(object): typecode='d' def __init__(self,x,y): self._x=float(x) self._y=float(y) @property #property函数用作装饰器可以创建只读属性 def x(self): return self._...
''' 在一个for语句中迭代多个可迭代对象 ''' from random import randint from itertools import chain #并行 chinese=[randint(60,100) for _ in range(10)] math=[randint(60,100) for _ in range(10)] english=[randint(60,100) for _ in range(10)] print(chinese);print(math);print(english) total=[] for c,m,e in zip(chinese,math,english): total...
# Program Name: Technical Support Assistant # # Author: Chinenye Okpalanze # # Date: 21-June-2020 # # Description: Demonstration program for SAIT CPRG 100 (Manpower) # # As the user if their computer beeps when powered on, and whether # the hard-drive s...
''' Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list. That is, if your list contains 10 items, only include a digit in your sum if the digit 10/2 = 5 steps forward matches it. Fortunately, your list has an even number of elements. For example: 1212 produc...
print('Enter the revenue value: ') revenue = int(input()) print('Enter cost value: ') cost = int(input()) if revenue > cost: print('profit') profitability = revenue / cost print(profitability) elif revenue < cost: print('loss') else: print('0') print('Enter the number of employees: ') numberOfEmpl...
input_world = [ [1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0] ] def count_islands_1(world_list): island = [] island_line = [] line_flag = False is_add = False for line_num in range(len(world_list)): world_line = world_list[line_num] for element_...
cars = ["audi", "bmw", "toyota", "honda"] for car in cars: if car == "bmw": print(car.upper()) else: print(car.title()) if "bmw" in cars: print("I have BMW!") age = 12 if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5") else: prin...
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): arr.sort() index = 0 if arr[-1] == 0: return arr while arr[index] <= 0: index += 1 arr1 = arr[:index] arr2 = arr[index:] return arr2 + arr1 if __name__ == '__mai...
graph = {1:[2,4], 2:[1,3,5], 3:[2,5], 4:[1], 5:[2,3]} #======================= #Depth first search def dfs(s): visited = [0]*(len(graph)+1) if (visited[s]): return visited[s] = True print(s) for u in graph[s]: dfs(u) dfs(1) #================== #breadth first search def bfs(): visited = [0]*(len(graph)+1) ...
import functools @functools.total_ordering class Node: def __init__(self, key, data): self.key = key self.data = data def __lt__(self, other): return self.key <= other.key def __eq__(self, other): return self.key == other.key def __str__(self): return "{(%d, %s)}" % (self.key, self.data)...
def add_time(start, duration, day = ""): parse_arr = start.split() start_m = parse_arr[1] parse_arr = parse_arr[0].split(":") start_hour = int(parse_arr[0]) start_minute = int(parse_arr[1]) if start_m == "PM" : start_hour += 12 if start_hour == 12 : start_hour = 0 elif...
import forecastio import datetime import urllib import re import json # Using checkip.dyndns.org to external IP address. externalipurl = "http://checkip.dyndns.org" findip = urllib.urlopen(externalipurl).read() myIP = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", findip) # Using IP address to determine geolocation...
import random NOMBRE_MIN = 1 NOMBRE_MAX = 10 NB_QUESTION = 10 def poser_question(): nombre_aleatoire_a = random.randint(NOMBRE_MIN, NOMBRE_MAX) nombre_aleatoire_b = random.randint(NOMBRE_MIN, NOMBRE_MAX) o = random.randint(0, 1) operateur = "+" if o == 1: calcul = nombre_aleatoire_a * nom...
import cv2 import pytesseract ## Python-tesseract is an optical character recognition (OCR) tool for python ## pytesseract.pytesseract.tesseract_cmd = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe" ## Fetch the image from respective Directory ## image = cv2.imread("calc.png") image = cv2.resize(image, (500...
# Zach Cowell # CS 210 # Project 1 Part 2 # Submitted May 29, 2009 # addm.py class proj12(): m1=[] m2=[] m3=[] def __init__(self, m, n): self.m1=m self.m2=n def add_matrices(self): colsX = len(self.m1) colsY = len(self.m2) rowsX = len(self.m1[0]) rowsY = len(self.m2[0]) self.m3...
A = 'AB' def find_column_number(A): number = 0 for i, char in enumerate(reversed(A.lower())): rank_char = ord(char) - 96 number += rank_char * (26**i) return number print(find_column_number(A))
def helper_1(A, B, start, end): len_A = len(A) mid = (start + end)//2 right = (mid + 1)%len_A left = (mid - 1 + len_A)%len_A # print(len_A, A[0],A[-1], left, mid, right) # print(A) # print if A[mid] == B: return mid if A[start] <= A[end]: if B > A[mid]: ...
def print_ll(A): to_print = True while to_print: if A: print(A.val) A = A.next if A == None: break else: break class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param ...
def braces(A): stack = [] redundant = False for c in A: if c != ' ': if c in ['(', '+', '-', '*', '/']: stack.append(c) elif c == ')': redundant = True while stack[-1] != '(': redundant = False ...
class MinStack: def __init__(self): self.a = [] self.min_stack = [] # @param x, an integer def push(self, x): if len(self.min_stack) == 0: self.min_stack.append(x) elif x <= self.min_stack[-1]: self.min_stack.append(x) self.a.append(x) # ...
#strings in python name="Tomisin Adebiyi" print(name[0]) ''' #python strings are immutable name[3]="c" ''' #we can convert python strings num1 = "55" print(type(num1)) num2 = int(num1) print(type(num2)) ''' num="55" print(type(int(num))) #object references x='blue' y='green' z=x #print(x,y,z) #we can rebind the...
#!/usr/bin/python # -*- coding: UTF-8 -*- import numpy as np def normalization(datalist, place=2): """data normalizaton datalist:data list palce:decimal places, default is 2 return:normalized data generator """ mindata = min(datalist) maxdata = max(datalist) generator = (round((x - m...
import numpy as np import pandas as pd from utils.constant import Constant def check_category(data_col, threshold_category): """ The function checks category of the data column :param data_col: one data column from file csv. :param threshold_category: threshold of the length function. :...
"""Show a window with a button to open a dialog. Installation: pip install bui[demo] To run this example: python download.py """ from bui import Dialog, Window, start class Hello(Window): layout = """ <window title="Greetings"> <button x=2 y=2 id=rename>What's your name?</button> ...
from abc import abstractmethod from bui.specific.base import * class SpecificList(SpecificWidget): """Parent class for a specific list widget.""" widget_name = "list" @abstractmethod def refresh(self): """Refresh the list choices, using the generic widget.""" pass def select(se...
class Dungeon(object): def __init__(self): self.dLevels = [] # bidirectional linked list def add_level(self, dLevel): self.dLevels.append(dLevel) class DungeonLevel(object): def __init__(self): self.tileGrid = [] maxX = -1 maxY = -1 def tile_at(sel...
import numpy as np methods = ('holm', 'bonferroni', 'hochberg', 'hommel', 'BH', 'BY', 'none') def p_adjust(p, method:str='holm', n=None): """Given a set of p values, returns p values adjusted using one of the methods. **Arguments:** p {array} -- Array of p values to adjust. method {string} -- Meth...
""" @@ CS 261 Assignment 1 - Divisibility Tester @@ Solution Test Script """ import unittest from gradescope_utils.autograder_utils.decorators import weight from a1_p1_divisibility import is_divisible import dis checkfor=['len', 'lower','upper', 'isalpha','isnum','isalnum', 'capitalize',' min', ' max', 'sor...
# USAGE # to run code # python ocr.py --image images/example_01.png # import the necessary packages from PIL import Image import pytesseract import argparse import cv2 import os # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, he...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def flipMatchVoyage(self, root, voyage): """ :type root: TreeNode :type voyage: List[int] :rtype: List[in...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isEvenOddTree(self, root: TreeNode) -> bool: cur_level = [root] level = 0 while ...
class Solution: def largestTriangleArea(self, points): """ :type points: List[List[int]] :rtype: float """ def area(p1,p2,p3): x1=p2[0]-p1[0] y1=p2[1]-p1[1] x2=p3[0]-p1[0] y2=p3[1]-p1[1] return abs(x1*y2-x2*y1) ...
# coding=utf-8 ''' Created on 2017?7?28? @author: Administrator ''' from data_structure.Link import list_to_list_node, output # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def insertionSortList(sel...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def pruneTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ def hasone(node): if n...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode: def deconstruct(root): if root: return deco...
# coding=utf-8 ''' Created on 2017?11?26? @author: Administrator ''' class Solution(object): def floodFill(self, image, sr, sc, newColor): """ :type image: List[List[int]] :type sr: int :type sc: int :type newColor: int :rtype: List[List[int]] """ ...
# coding=utf-8 ''' Created on 2017?8?24? @author: Administrator ''' from random import shuffle arr = range(10) + [6, 6, 6, 6] shuffle(arr) i = j = 0 n = len(arr) - 1 mid = 6 print arr while j <= n: if arr[j] < mid: arr[i], arr[j] = arr[j], arr[i] i += 1 j += 1 elif arr[j] > mid: ...
# coding=utf-8 ''' Created on 2017?8?6? @author: Administrator ''' from data_structure.Tree import list_to_tree # 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 findTarge...
# coding=utf-8 ''' Created on 2017�?6�?14�? @author: Administrator ''' from data_structure.Tree import tree_to_list # 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 str2...
# coding=utf-8 ''' Created on 2017?11?12? @author: Administrator ''' class Solution(object): def countOfAtoms(self, formula): """ :type formula: str :rtype: str """ from collections import defaultdict def getName(i): name = [formula[i]] i ...
# coding=utf-8 ''' Created on 2017?7?30? @author: Administrator ''' from Tkconstants import SOLID from data_structure.Tree import list_to_tree, tree_to_list # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None...
# coding=utf-8 ''' Created on 8 Jan 2018 @author: Administrator ''' class Solution: def pourWater(self, heights, V, K): """ :type heights: List[int] :type V: int :type K: int :rtype: List[int] """ for _ in range(V): left = ind = K #...
class Solution: def camelMatch(self, queries: list, pattern: str) -> list: ans = [] def foo(q, pattern): p1 = p2 = 0 while p1 < len(q) and p2 < len(pattern): while p1 < len(q) and q[p1] != pattern[p2]: if q[p1].isupper(): ...
from typing import List import collections class ThroneInheritance: def __init__(self, kingName: str): self.king=kingName self.children=collections.defaultdict(list) self.dead=set() def birth(self, parentName: str, childName: str) -> None: self.children[parentName].append(childN...
class Solution(object): def isLongPressedName(self, name, typed): """ :type name: str :type typed: str :rtype: bool """ def solve(s): arr = [] p1 = 0 cur_char = None cur_len = 1 while p1 < len(s): ...
# 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 twoSumBSTs(self, root1, root2, target): """ :type root1: TreeNode :type root2: TreeNode ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minCameraCover(self, root): """ :type root: TreeNode :rtype: int """ # 0 root is not covered...
import collections class Solution(object): def sortItems(self, n, m, group, beforeItems): """ :type n: int :type m: int :type group: List[int] :type beforeItems: List[List[int]] :rtype: List[int] """ def top_sort(nodes,rnp): in_degree=colle...
class Solution: def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ p1=0 while p1<len(A) and A[p1] % 2 == 0: p1+=1 p2=p1 while p2<len(A): while p2<len(A) and A[p2]%2==1: p2+=1 ...
class Solution(object): def shortestSuperstring(self, A): """ :type A: List[str] :rtype: str """ def overlap(s1, s2): length = min(len(s1), len(s2)) for i in range(length - 1, -1, -1): if s1[len(s1) - i:] == s2[:i]: ...
class Solution: def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: def foo(s): number = [] for ch in s: number.append(str(ord(ch) - ord("a"))) return int("".join(number)) return foo(firstWord) + foo(secondWord) == foo(...
class Solution(object): def validateStackSequences(self, pushed, popped): """ :type pushed: List[int] :type popped: List[int] :rtype: bool """ p = 0 stack = [] for num in pushed: stack.append(num) while stack and stack[-1] == po...
# coding=utf-8 ''' Created on 2017?7?13? @author: Administrator ''' from data_structure.Tree import list_to_tree # 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 ...