text
stringlengths
37
1.41M
from machine import Pin import time # initial state currentLED = "GREEN" # setup button and the LEDs btn = Pin(14, Pin.IN) leds = {"GREEN": Pin(15, Pin.OUT), "YELLOW": Pin(32, Pin.OUT), "RED": Pin(13, Pin.OUT)} # set the LED to the initial value leds[currentLED].value(1) while True: if btn.value() == 0: ...
import book_system_manage.book_list_manage import book_system_manage.inventory_manage print(""" =================== 图书库存管理系统V.1 1.显示书目信息 2.显示图书库存信息 3.添加书目信息 4.修改图书库存量 5.退出系统 =================== 请输入要执行的操作(填写数字):""", end="") infos = [] num = input() while num != '5': if num == '1': ...
# 魔法函数可以自己重构,便于实现自定义的一些功能 # 达到某些特定条件,魔法函数会自动触发,无需手动调用 class Student(): def __init__(self,name): self._name=name print(str(self._name)) # __gt__使用大于比较的时候触发的魔法函数 def __gt__(self,obj): # self和obj代表两个对象 # self代表自己,obj代表第二个对象 # 不加._name比较结果显示对象 print("哈哈哈,{0}会比{1...
""" birthday.py Author: Tess Snyder Credit: Mary Feyrer, Adam Glueck Assignment: Your program will ask the user the following questions, in this order: 1. Their name. 2. The name of the month they were born in (e.g. "September"). 3. The year they were born in (e.g. "1962"). 4. The day they were born on (e.g. "11"). ...
import os def is_valid_input_file(args): """ Validates that the input file exists and is a .json file. @param args: the command line arguments to the program. """ if len(args) < 2: return False filename_length = len(args[1]) return os.path.isfile(args[1]) and args[1][filename_length - 5::] == ".json"
#oop first classes example class cat: def __init__(self, name, owner, color): self.name = name self.owner = owner self.color = color cat_1=cat('Clocharde','Hannah','multicolored') cat_2=cat('Leia','Paula','orange') print(cat_1.color)
score = 0 while True: try: section= str(input("Pick a Section: Math, Science or History ")) except ValueError: print("Sorry, I didn't understand that.") continue else: break if section == "Math": mathVal= int(input("Pick a Question Amount: 100, 200, 300, 400, 500 ")) ...
from tkinter import * import tkinter.messagebox #create the window. root = Tk() root.configure(background='black') root.title("My calculator") #create the output line. e = Entry(root, width=35, borderwidth=5) e.grid(row=0,column=0, columnspan=3, padx=10,pady=20) def click(number): current=e.get() ...
spaces = 3 while(spaces >= 0): if(spaces != 3): print(" " * spaces + "*" ,end = "") else: print(" " * spaces + "*") i = 3 - spaces spaces = spaces - 1 innerspace = i * 2 - 1 if i == 0: continue print(" " * innerspace + "*") #added a line
class UnionFind: def __init__(self, n): self._ids = [i for i in range(n)] self._count = n def get_count(self): return self._count def connected(self, p, q): return self.find(p) == self.find(q) def find(self, p): return self._ids[p] def union(self, p, q): ...
def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr if __name__ == '__main__': from script_benchmark_tools import Script from script_benchmark_tools.bench...
def loggestCommonSubString(str1, str2): if len(str1) < len(str2): str1, str2 = str2, str1 if len(str2) == 1: return str2 if str2 in str1 else None for l in reversed(range(1, len(str2) + 1)): start = 0 end = l - 1 for i in range(len(str2) - l + 1): if str...
def printMatrix(matrix): for row in matrix: print(" {0} {1} {2} {3} {4}".format(*[col for col in row])) def scanMatrix(matrix): for row in range(1,len(matrix[0])): for col in range(1,len(matrix[0])): if matrix[row][col] == 0: matrix[row][0] = 0 ...
def relativelySort(a1, a2): a1.sort() a3 = [] for x in a2: i = a1.index(x) while(i >= 0 and a1[i] == x): a3.append(x) a1[a1.index(x)] = -1 i += 1 for i in a1: if i != -1: a3.append(i) return a3 a1 = [2, 1, 2, 5, 7, 1, 9, 3, 6...
import json import re def address_converter(address): """This function gets an string as address and returns string of street and string of street-number as JSON object Args: address (str): concatenated address Returns: JSON: string of street and string of street-number as JSON objec...
#逆にしないと別の組み合わせができてしまう.(動的計画法はかしこい) S = input() word = ["dream","dreamer","erase","eraser"] S = S[::-1] #入力文字を反転 for i in range(len(word)): word[i] = word[i][::-1] #4つのワードを反転 while True: for i in range(len(word)): flag2 = False if word[i] == S[:len(word[i])]: flag2 = True ...
m = int(input()) if 100>m: print(format(0,'02')) elif 5000>=m and m>=100: print(format((m*10)//1000,'02')) #二桁ゼロ埋め elif 30000>=m and m>=6000: print((m//1000)+50) elif 70000>=m and m>= 35000: print(((m//1000)-30)//5+80) else: print(89)
N = int(input()) flag = True for i in range(1,10): for j in range(1,10): #print(i, j) if i * j == N: print("Yes") flag = False if not(flag): break if flag: print("No")
N = input() nine = 0 for i in range(len(N)): nine += int(N[i]) print("Yes" if nine%9==0 else "No")
celsius = float(input('Digite a temperatura em Celsius: ')); fahrenheit = (celsius * (9/5)) + 32; print('{}°c é igual a {}°f'.format(celsius, fahrenheit));
n1 = float(input('Digite uma distancia em metro: ')); print('Esta distancia possue: '); km = n1 / 1000; hm = n1 / 100; dam = n1 / 10; dm = n1 * 10; cm = n1 * 100; mm = n1 * 1000; print(km); print(hm); print(dam); print(dm); print(cm); print(mm);
n1 = int(input('Digite a nota um: ')); n2 = int(input('Digite a nota dois: ')); media = (n1 + n2) / 2; print('A média entre {}, e {}, é igual a {}!'.format(n1, n2, media));
class Calculator: def addition(self,num1,num2): self.a=num1 self.b=num2 return (self.a+self.b) def sub(self,num1,num2): self.a=num1 self.b=num2 return (self.a-self.b) def mul(self,num1,num2): self.a=num1 self.b=num2 return (self.a*sel...
#constructors used for the initialization of instant variables class Person: def __init__(self,name,age,gender): #init (initialization) constructor self.name=name self.age=age self.gender=gender def printVal(self): print("Name:",self.name,"\nAge:",self.age,"\nGender:",self.gend...
#inheritance #python supports 3 types of inheritance #1.Single-level inheritance : When the child class inherits from only one parent class #2.Multiple-level inheritance : When the child class inherits from multiple parent classes #3.Hierarchical inheritance : When more than one class is derived from the single base cl...
# a=int(input(":")) # b=int(input(":")) # try: # print(a,b) # print(a,"/",b,"=",a/b) # # except: # print("Exception occured") #the 'try' block always work in every cases #but the 'except' block work only when an error occures in the try block #.................................................................
class Student: def __init__(self, name, age): self.name = name self.age = age def printVal(self): print(self.name, "\t", self.age) f = open("student", "r") for i in f: data = i.rstrip("\n").split(",") st=Student(data[0], data[1]) st.printVal()
num = int(input('Enter a positive integer to know its factorial: ')) fact = 1 if num >= 0: for x in range(1, num+1): fact *= x print(f"{num}! is", fact) elif num < 0: print('Factorial is only defined for positive integers.')
# Take in the sudoku output and print it in a pretty way with open("output.txt", "r") as f: line = f.readline() # Read until completion while not line.startswith("Completed"): line = f.readline() line = f.readline() a = [] # Generate an empty board for i in range(10): a.a...
from argparse import ArgumentParser, Namespace def get_args() -> Namespace: """ Initialize the argument parser. """ parser = ArgumentParser(description='Example max-finding script.') parser.add_argument('numbers', metavar='N', type=int, nargs='+', help='Possible maximum int...
def answer(x, y): if x <= 0 or y <=0: return -1 ans = 1 + ((y+y+x)*(x-1)/2) + (y * (y-1)/2) return str(int(ans)) print answer(1,1) print answer(3,2) print answer(2,3) print answer(-1,1)
import random class Markov: chain_dict={} def generate_chain(self): f=open("test.txt","r") words=[""]*2 for line in f: for word in line.split(): curr_key=words[0]+' '+words[1] if curr_key in self.chain_dict: self.chain_dict[curr_key].append(word) else: self.chain_dict[curr_key]=[w...
class Solution(object): def shortestToChar(self, S, C): """ :type S: str :type C: str :rtype: List[int] """ length = len(S) index = [] items = [] for i in xrange(length): if S[i] == C: index.append(i) for i ...
class Solution(object): def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ items = [s[k * i: k * i + k] for i in range(len(s) / k + 1)] reverse_items = [] for i in xrange(len(items)): if i % 2 == 0: re...
# encoding: utf-8 class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ height = len(board) length = len(board[0]) x = y = 0 while True: if board[y][x] == word[0]:...
class Solution: def exist(self, board: [[str]], word: str) -> bool: res = [] def back_track(count, selected: [[]]): coordinate = selected[-1] x, y = coordinate[0], coordinate[1] if x >= len(board) or x < 0: return if y >= len(board[0...
class Solution: def wordBreak(self, s: str, wordDict: [str]) -> bool: tmp = s length = len(s) max_l = 0 for i in wordDict: max_l = max(max_l, len(i)) for i, j in enumerate(s): tmp = tmp[:length-i] if len(tmp) > max_l: contin...
# encoding: utf-8 class Solution(object): def firstMissingPositive_before(self, nums): """ :type nums: List[int] :rtype: int """ # 去重 nums = list(set(nums)) # 排序 nums = sorted(nums) for i in range(len(nums)): if nums[i] > 0: ...
class Solution(object): def dominantIndex(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return 0 nums_t = sorted(nums) if nums_t[-1] >= nums_t[-2] * 2: return nums.index(nums_t[-1]) else: ...
import re res = re.match(r'^\d+\.\d+$', '2.2') if res: print( True ) else: print( False )
#Solution1 DFS find the depth of minimum, check whether it is the leaf node #O(n) in time, O(1) in space #AC in 69ms class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ return self.dfs(root) def dfs(self,root): ...
#Idea: binary search for the citation times in citations that is less than n-mid #O(logn) in Time, O(1) in space class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ n = len(citations) i, j = 0, n - 1 wh...
#Idea: create hashtable to find the count of each individual element in the nums, check which one is larger than len(nums)/2 #O(n) in time, O(n) in space #AC in 52ms class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ temp = dict().fro...
#Solution1 DFS with recursive #O(??????) in time, O(n) in space # class Solution: def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ return self.dfs(root, k, []) def dfs(self, root, k, d): if root is None: ...
#Bubble sort #O(n ** 2) in time, O(1) in space def bubbleSort(nums): for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] > nums[j]: nums[i],nums[j] = nums[j], nums[i] return nums nums = [4,3,5,1,2,4,2,7] print(bubbleSort(nums))
# #O(n) in time, O(n) in space #AC in 32ms class Solution(object): def isStrobogrammatic(self, num): """ :type num: str :rtype: bool """ num = str(num) reverse = ['0']*len(num) for i in range(len(num)): reverse[len(num)-1-i] = self.convertDigit(n...
#Make the array descending according to its height, move the people according to the k number #O(nlogn) in time, O(1) in space #AC in 156ms class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ if len(peopl...
class Rectangle: def __init__(self, a, b): self.a = a self.b = b def p(self): return 2*(self.a + self.b) def s(self): return self.a * self.b class Square(Rectangle): def sq(self): if self.a == self.b: self.sq = True return self....
#!/usr/bin/env python #-*- cording: utf-8 -*- from datetime import datetime from time import sleep def now_time(): d = datetime.now() year = d.year month = d.month day = d.day hour = d.hour minute = d.minute second = d.second datetime_str = d.strftime('%Y/%m/%d %H:%M:%S') print(datetime_str) return...
# Author: JJ # Date: 3 April 2020 # Version: 1.0 # # Math Quest # Ask student to enter name and enter the timestable they want to practice print ("Welcome to Math Quest") print ("What is your name?") name = input() print ("Hello {} which timestable would you like to practice, from (1-12)?". format (name)) number = inp...
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ min_int = ints[0] max_int = ints[0] for i in ints: if i <min_int: min_int = i elif i >max_int: max_int = i...
thePassword = str(1234) yourPassword = input('Enter Password:') def crack_password(password): passwd = list(thePassword) for i in range(0, 10): for j in range(0,10): for k in range(0,10): for l in range(0,10): if str(i) == passwd[0] and str(j) == passwd[1...
""" 栈的顺序存储结构 重点代码 """ import os # Tom import threading # Jame # 自定义栈异常 class StackError(Exception): pass # 基于列表实现顺序栈 class SStack: def __init__(self): # 约定列表的最后一个元素为栈顶 self._elems = [] def top(self): if not self._elems: raise StackError("stack is empty") r...
#Nos ayuda en la interfaz que hay entre el usuario y el programa from tkinter import * import tkinter as tk #Esta biblioteca importa todas las operaciones aritmeticas y funciones matematicas import math #nos ayuda con el calculo de operaciones a nivel matricial import numpy as np #Esta biblioteca ayuda con la grafic...
def divide(arg1,arg2): if isinstance(arg1,list) or isinstance(arg2,list): raise ValueError("Cannot divide if either of the operand is a list") return arg1/arg2
''' 1、 Python3字符 ''' ''' 2、Python字符串运算符 表实例变量a值为字符串 "Hello",b变量值为 "Python": 操作符 描述 实例 + 字符串连接 a + b 输出结果: HelloPy...
# using Tkinter to display a hand of 13 random card images # each time you click the canvas from deck import * from Tkinter import * #import random from random import shuffle #TODO-pl let user set up his cards to compare with program def create_images(): """create all card images as a card_name:image_object dict...
class Pixel: def __init__(self,r: int,g: int,b: int,a: int): self.r,self.g,self.b,self.a = r,g,b,a def get_rgba(self): return self.r, self.g, self.b, self.a def set_rgba(self,r: int,g: int,b: int,a: int): self.r,self.g,self.b,self.a = r,g,b,a def set_pixel(self,pixel): ...
# 4. Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. # Строки необходимо пронумеровать. Если слово длинное, выводить только первые 10 букв в слове. txt = list(input('Введите несколько слов: ').split()) for i in range(len(txt)): print(i + 1, txt[i][:10])...
# 4. Программа принимает действительное положительное число x и целое отрицательное число y. # Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). # При решении задания необходимо обойтись без встроенной функции возведения числа в степень. # Вариан...
# 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. # При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, # разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. # Но если вместо числа ...
# 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10% относительно предыдущего. Требуется определить номер дня, # на который общий результат спортсмена составит не менее b километров. Программа должна принимать знач...
#!/usr/bin/python3 # 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. # В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия. # Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. from...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ An example to show how the backprogation is computed in pytorch reference: https://stackoverflow.com/questions/43451125/pytorch-what-are-the-gradient-arguments Zhenhao Ge, 2018-12-11 """ from torch.autograd import Variable import torch x = Variable(torch.FloatTensor...
# removing duplicate element from a list n = int(input()) l = [] for i in range(n): l.append( int(input()))
#selection sort l = [ 9 , 6 , 2 , 4 , 3 , 6 ] for i in range( len( l ) - 1 ): for j in range( i + 1 , len( l ) ): if l[i] > l[j]: l[i] , l[j] = l[j] , l[i] #swap print( l )
# Exercise 3 ## Objective: prompt a user to enter their age; script should output "Your age is [age here]" age = input("How old are you? :") print("your age is " +age)
"""http://dojopuzzles.com/problemas/exibe/troco/ Funcionários de empresas comerciais que trabalham como caixa tem uma grande responsabilidade em suas mãos. A maior parte do tempo de seu expediente de trabalho é gasto recebendo valores de clientes e, em alguns casos, fornecendo troco. Seu desafio é fazer um programa qu...
class Robot: def __init__(self, name, build_year, lk=0.5, lp=0.5): self.name = name self.build_year = build_year self.__potential_physical = lk self.__potential_psychic = lp @property def condition(self): s = self.__potential_physical + self.__potential_psychic ...
for i in range(6): print("Shivam",end="") for j in range(6): print("Shivam Shivam") for k in range(6): print("Shivam",end="")
def song_playlist(songs, max_size): """ songs: list of tuples, ('song_name', song_len, song_size) max_size: float, maximum size of total songs that you can fit Start with the song first in the 'songs' list, then pick the next song to be the one with the lowest file size not already picked, repeat ...
#크롤링이후 데이터를 별도의 디렉토리에 저장하고 진행하려면? #파일의 크기 확인 from os.path import getsize getsize('c:/r/emp.csv') #디렉토리에 있는 파일 확인 import os import glob folder = 'c:/python' file_list = os.listdir(folder) file_list #특정한 파일들의 목록 확인 file = 'c:/python/*.csv' file_list = glob.glob(file) file_list #현재 디렉토리 확인 i...
#[문제7] 아래와 같은 문자데이터가 있습니다. url = 'http://www.python.org' #1. http:// 제거한 후 url 변수에 넣어 주세요. url = url.lstrip("http://") #2. url변수에 있는 문자 데이터에 '.'을 기준으로 분리하세요. url = url.split(".",) #3. url변수에 있는 문자데이터를 www.python.org 모양으로 만드세요. url = ".".join(url) #4. url변수에 있는 문자데이터를 대문자로 변환하세요. url = url.upper() #...
### by using dictionary for format_map() type = input("enter type:") brand = input("enter brand:") selection = "i like wear {} with the {} brand " print(selection.format(type,brand)) dict= {"type": "Shoes" , "brand": "nike" } print(selection.format(dict["type"],dict["brand"])) print('{type} {brand}'.format_map(dict)) ...
# Constructor functions a = int(2) b = int(3.5) c= int("7") #print("The type is " + str(a) + str(b) + str(c)) print( a,b,c) print("int type",a,b,c) # float() a = float(2) b = float (2.8) c = float("5") print( a,b,c) print("float type ", a,b,c) # # #string() a = str("e1") b = str(2) c = str(2.5) print( a,b,c) print(...
print("Padmajas Python world!") # above is prnint() function. # indentation if 2<6: print("2 is less than 6") # Assigning Values to variables x = "Padmaja will learn python" y = " in 2 months" print(x,y) x="iam going to do todays homework" print(x) #declaring Variables name = "Raju" _name = "explains Python" name...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' COMP 1012 SECTION A01/A02 INSTRUCTOR Domaratzki, Boyer ASSIGNMENT: A3 Q2 AUTHOR The Instructors VERSION 2016-Oct-22 PURPOSE: to determine the score of a 10-pin bowling game NOTE: This solution is slightly different than specified in...
a=10 print(id(a)) #global variable print(a) def something(): global a #to mention that we are changing value of global varibale a # a=15 local variable print(a...
dic = { "shammi": "red", "trijal": "blue", "mumma": "purple", "vasu": "brown", "peda": "orange" } original_length = len(dic) print(original_length) key_to_del = "" for index in dic: print(index) if (dic[index]) == "blue": key_to_del = index dic.pop(key_to_del) print(dic)
import random as ran import matplotlib.pylab as plt def roll_dice(): dice = ran.randint(1,100) if dice in range(1,50): #print(str(dice)+" house wins") return False elif dice in range(51,99): #print(str(dice)+" you win!") return True else: #print(str(dice)+"you lo...
# 다음 두 함수에 대해 ‘Hi, python!’과 ‘Bye, python!’이 출력되도록 데코레이터 함수를 정의하여 실행하라. # >>>def hi_python(): return ‘Hi, ‘ # >>>def bye_python(): return ‘Bye, ‘ def hi_python(): return 'Hi,' def bye_python(): return 'Bye,' def python(func): def newString(*args, **kwargs): print(func(), 'python!') return ...
# range() 함수를 이용하여 리스트 [30,29,28, . . .,3,2,1,0]를 생성하고 # 이 리스트의 멤버 3의 인덱스 값은 얼마인지 출력하는 while 문을 작성하라 list = list(range(0, 31)) index = 0 refList = [] while index < len(list): if list[index] == 3: print("리스트의{}째 값은 {}입니다.".format(index, index)) break else: index += 1
# 리스트 변수 names에 있는 각 요소들의 마지막 문자를 기준으로 오름차순 정렬을 하여 출력하고자 한다. # sorted() 함수의 key 파라미터에 익명 함수를 사용하여 작성하라. # names = [‘Kim’, ‘Jeong’, ‘Park’, ’Lee’, ’Choi’] names = ['kim', 'choi', 'park', 'lee', 'jeong'] print(sorted(names, key=lambda name: name[-1]))
import tkinter as tk from tkinter import PhotoImage janela = tk.Tk() class Estilo(): global janela def define_dimensoes(self, largura, altura, redimencionavel=False): # Extraindo a resolução do sistema largura_screen = janela.winfo_screenwidth() altura_screen = janela.winfo_screenhe...
print('program to sort list and find greatest no.in the list') '''l=eval(input('enter a list')) length=len(l) i=0 j=0 while j!=length-1: if l[i]<l[j+1]: t=l[j+1] l[j+1]=l[i] l[i]=t j+=1 print('greatest no.is',l[0]) input()''' l=eval(input('enter a list')) l.sort() print('sorted ...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: ...
class Solution: # @param {int[][]} matrix a matrix of m x n elements # @return {int[]} an integer array def spiralOrder(self, matrix): if not matrix or len(matrix[0]) == 0: return [] m = len(matrix) n = len(matrix[0]) r = [] s = 0 while 2 * s <...
#coding: utf-8 import math def main(): in_str = "abcd" combined_output(in_str) combined_output_k(n=4, k=2) def combined_output(in_str): len_str = int(len(in_str)) nc = int(math.pow(2, len_str)) for i in range(nc): output = '' for index, flag in enumerate([1 & (i >> m) for m...
# 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 countNodes(self, root): """ :type root: TreeNode :rtype: int """ cnt = 0 ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head curr =...
# coding: utf-8 def quicksort(nums, start=None, end=None): start = 0 if start is None else start end = len(nums) - 1 if end is None else end if start >= end: return pivot = partition(nums, start, end) quicksort(nums, start, pivot - 1) quicksort(nums, pivot + 1, end) def quicksort_i...
class Solution: ''' @param root: An object of TreeNode, denote the root of the binary tree. This method will be invoked first, you should design your own algorithm to serialize a binary tree which denote by a root node to a string which can be easily deserialized by your own "deserialize" method ...
class Deque: class Node: def __init__(self, key=0, val=0, prev=None, next=None): self.key = key self.val = val self.prev = prev self.next = next def __init__(self): self.head = Deque.Node() self.tail = Deque.Node() self.he...
# 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 preorderTraversal(self, root: TreeNode) -> List[int]: self.tlist = [] self._do_preorder_...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def partition_val(self, head: ListNode, x: int) -> ListNode: smaller = ListNode() larger = ListNode() saved_larger = larger ...
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if not intervals:...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not ...
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ if n <= 0: return [] self.r = [] self.n = n self.dfs(1, "(", 1, 0) return self.r def dfs(self, pos, path, left, right): ...
class Solution(object): def updateMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ if not matrix: return matrix xcnt = len(matrix) ycnt = len(matrix[0]) for i in range(xcnt): for j in range...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: an = 0 la = headA while headA is not None: headA = h...