text
stringlengths
37
1.41M
year = int( input("연수 입력: ") ) result = "평년" if year % 400 == 0: result = "윤년" else: if year % 100 != 0: if year % 4 == 0: result = "윤년" print(result)
print("반복 시작!") for i in range(3): print("반복") print(i) print("반복 끝!")
num = 1 while num > 0: num = int( input() ) print(num) ######################### a = ['I', 3, 0.1, 'choongam'] for i in a: print(i) ######################### for i in range(-6, 5): print(i)
#!/usr/bin/env python3 from random import shuffle from os import system from time import sleep moves = [(-1, 0), (1, 0), (0, -1), (0, 1)] WALL = 1 PATH = 2 UNSET = 0 speed = 50 solved = [] show_progress = True def main(): global solved height = 10 width = 20 maze = [[0 for x in range(width)] for ...
""" 0 = possible pathway 1 = wall 2 = rat's path """ board = [ [0, 0, 0, 0, 0], [1, 1, 0, 1, 0], [0, 0, 0, 1, 0], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0], ] moves = [(0, 1), (1, 0), (0, -1), (-1, 0)] def main(): if solve(board, 0, 0, 0): print("Solvable") [print(row) for row in board...
''' Data Preprocessing ''' import numpy as np import pandas as pd # Normalization & Scaling Functions using simple Numpy & Pandas methods # Outlier Scaling using .quantile() Pandas methods def scale_outlier(df, column): Q1 = df[column].quantile(0.25) Q3 = df[column].quantile(0.75) IQR = Q3 - Q1 min_bo...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool ...
class Radio(): CONNECTION = ["wifi", "bluetooh", "cable"] def __init__(self, brand, size, colour, item_of_speaker, music, connection): self.brand = brand self.size = size self.colour = colour self.item_of_speaker = item_of_speaker self.music = music if connection...
import time from randint_list import randint_list def timer(func): def wrapper(*args, **kwargs): t1 = time.time() func(*args, **kwargs) t2 = time.time() print(f"{func.__name__} 花费时间 {t2 - t1}") return wrapper @timer def bubble_sort(arr): """冒泡排序""" length = len(arr) ...
# Exercício Python 087: Aprimore o desafio anterior, mostrando no final: # A) A soma de todos os valores pares digitados. # B) A soma dos valores da terceira coluna. # C) O maior valor da segunda linha. matriz = list() somaPar = somaTerceiraColuna = maiorSegundaLinha = 0 for i in range(0, 3): for j in range(0, 3)...
#Exercício Python 057: Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'. # Caso esteja errado, peça a digitação novamente até ter um valor correto. sexo = str(input('Digite seu sexo: [F/M]')).strip().upper()[0] while sexo not in 'MmFf': print('Dados inválidos!') sexo = str(i...
# Exercício Python 035: Desenvolva um programa que leia o comprimento de três retas # e diga ao usuário se elas podem ou não formar um triângulo. r1 = float(input('Digite o comprimento da primeira reta: ')) r2 = float(input('Digite o comprimento da segunda reta: ')) r3 = float(input('Digite o comprimento da terceira r...
# Exercício Python 069: Crie um programa que leia a idade e o sexo de várias pessoas. # A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. # No final, mostre: # A) quantas pessoas tem mais de 18 anos. # B) quantos homens foram cadastrados. # C) quantas mulheres tem menos de 20 ano...
# Exercício Python 052: Faça um programa que leia um número inteiro e diga se ele é ou não um número primo. n = int(input('Digite um número inteiro: ')) total = 0 for i in range(1, n + 1): if n % i == 0: print('\033[32m', end='') total += 1 else: print('\033[31m', end='') print('{}...
# Exercício Python 059: Crie um programa que leia dois valores e mostre um menu na tela: # [ 1 ] somar # [ 2 ] multiplicar # [ 3 ] maior # [ 4 ] novos números # [ 5 ] sair do programa # Seu programa deverá realizar a operação solicitada em cada caso. from time import sleep cores = { 'limpa': '\033[m', ...
# Exercício Python 007: Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. nota1 = float(input('Nota 1: ')) nota2 = float(input('Nota 2: ')) #media = ((nota1 + nota2)/2) media = (nota1 + nota2) / 2 print('A média do aluno é {:.2f}.'.format(media))
# Exercício Python 087: Aprimore o desafio anterior, mostrando no final: # A) A soma de todos os valores pares digitados. # B) A soma dos valores da terceira coluna. # C) O maior valor da segunda linha. matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] somaPar = somaTerceiraColuna = 0 for l in range(0, 3): for c in rang...
# Exercício Python 084: Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista. # No final, mostre: # A) Quantas pessoas foram cadastradas. # B) Uma listagem com as pessoas mais pesadas. # C) Uma listagem com as pessoas mais leves. cadastro = list() pessoa = list() maisPesado = list() mai...
# Exercício Python 080: Crie um programa onde o usuário possa digitar cinco valores numéricos # e cadastre-os em uma lista, já na posição correta de inserção (sem usar o sort()). # No final, mostre a lista ordenada na tela. lista = list() for i in range(0, 5): valor = int(input('Digite um valor: ')) if i == 0...
# Exercício Python 064: Crie um programa que leia vários números inteiros pelo teclado. # O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. # No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag). numero = int(input('Digite um núm...
# Exercício Python 003: Crie um programa que leia dois números e mostre a soma entre eles. n1 = int(input('Digite um número: ')) n2 = int(input('Digite outro: ')) cores = {'limpa':'\033[m', 'peb':'\033[7m', 'brancoevermelho':'\033[0;30;42m', 'brancoeeverde':'\033[0;30;42m', 'branco...
# Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial. # Ex: 5! = 5 x 4 x 3 x 2 x 1 = 120 from math import factorial numero = int(input('Digite um número: ')) fatorial = factorial(numero) print('{}! = '.format(numero), end='') while numero >= 1: if numero != 1: print...
# let's start with sentences that don't include punctuation vowels = ['a', 'e', 'i', 'o', 'u'] consonantClusters2 = ['bl', 'br', 'ch', 'cl', 'cr', 'dr', 'fl', 'fr', 'gl', 'gr', 'pl', 'pr', 'sc', 'sh', 'sk', 'sl', 'sm', 'sn', 'sp', 'st', 'sw', 'th', 'tr', 'tw', 'wh', 'wr'] consonantClusters3 = ['sch', 'scr', 'shr', 'sp...
print("How old are you?", end=' ') age = input() print("How tall are you?", end=' ') height = input() print("How much do you weigh? (numeric only)", end=' ') weight = int(input()) print("What's your target weight (numeric only)?", end=' ') target_weight = int(input()) weight_goal = weight - target_weight # there woul...
# coding exercise from interview # this works but I feel it can be done in a much better way def char_count(sentence): activeChar = '' activeCount = 0 revised = '' for x in range(len(sentence)): if sentence[x] != activeChar: if activeChar: revised += activeChar + str...
## This is the text editor interface. ## Anything you type or change here will be seen by the other person in real time. # input: array of intergers # output: boolean, true if and only if 3 separate cells sum to 0 # [1, 1, 1] => false # [0, 0, 0] => true # [0, 1, 2, -5, 8, -1] # lower = [ i for i in myarray if i <= ...
# first factorial # based on CoderByte question def FirstFactorial(num): """Assuming between 1 - 20, all positive int""" if num <= 2: return num return num * FirstFactorial(num - 1) print(FirstFactorial(2)) print(FirstFactorial(8)) print(FirstFactorial(20))
# inspired by https://www.youtube.com/watch?v=O17TzRU0Pss # but with a function. # this can be improved a lot. import random def analyze_guess(guess, target): guess = int(guess) if not type(guess) == 'int': msg = "I don't understand that." if guess < target: msg = "Too low!" elif guess...
num=int(input("Enter a number to check the number is armstrong number or not: ")) n=num k=0 sum=0 while n!=0: n//=10 k+=1 n=num while n!=0: rem=n%10 sum+=pow(rem,k) n//=10 if sum==num: print("%d is a Armstrong Number"%num) else: print("%d is Not a armstrong number"%num)
# Uses python3 import sys ''' def get_fibonacci_huge_naive(n, m): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % m ''' def get_fibonacci_huge(n,m): if(n == 0): return 0 fib = {...
import random def merge_sort(list_a): if len(list_a) > 1: middle = len(list_a) // 2 left = list_a[:middle] right = list_a[middle:] print(left, '*' * 5, right) # llamada recursiva en cada mitad. Para dividir las listas en más pequeñas. Esto se ejecuta # Hasta tener l...
import math def checkPrime(n): if n == 0 or n == 1: return False elif n == 2: return True else: isPrime = True for divisor in range(2, math.ceil(math.sqrt(n)) + 1): if n % divisor == 0: isPrime = False break return isPrime ...
s = 'tata consultancy services limited' contador = len(s) - 1 count = 0 while contador >= 0: if s[contador]=='a' or s[contador]=='e' or s[contador]=='i' or s[contador]=='o' or s[contador]=='u': count = count + 1 contador = contador - 1 print(count)
############# Python Básico ################ ###Operadores Básicos # Soma e Subtração: + - # divisão: / # multiplicação: * # Exponencial a: ** # Modulo: % ###Tipos de dados # float: número com decimais # int: Número inteiro # str: Cadeias de texto # bool: Booleano (V/F) ###Operadores básicos podem fucionar com str...
data_string = "day_10_input_test.txt" text_file = open(data_string, "r") raw_input = text_file.read() adapters = raw_input.split('\n') adapters = [int(adapter) for adapter in adapters] adapters = sorted(adapters) from math import comb comb(10,3) # 10 over 3; n over k built_in_adapter = max(adapters) + 3 # 22 c...
import re # regular expressions # read data as txt file data_string = "day_02_input.txt" text_file = open(data_string, "r") lines = text_file.read().split('\n') text_file.close() #1-3 a: abcde lines = list((map(lambda password: re.split('\\-|: | ',password), lines))) # part 1: count occurences of given letter cou...
""" If you don't know how many keyword arguments will be passed into a function, then use single variable for all unknown arguments and place that variable as the last argument and add (**) before that variable. Such arguments are called arbitrary keyword argument. i.e arbitrary keyword argument is exactly same as arbi...
""" 1.) Errors :- Errors are the problems in the program or in the system, due to which execution of the program stops. Generally errors are irrecoverable and hence can't be handled.But it is not always true i.e some errors are recoverable and can be handled like RecursionError. 2.) Exceptions :- Exceptions in ...
""" Tuples are ordered immutable sequence of objects. Ordered means every item in Tuple has some fixed index and immutable means tuples are unchangeable i.e we can't add, remove, or change items from the tuple once they are created. Duplicate objects are allowed in Tuples and Tuples are written with round brackets(i.e ...
""" A variable declared in the main body of the Python file(or module) is called global variable and belongs to global scope. Global variables are available anywhere within the file i.e inside any function as well as outside any function, but we can't modify a global variable inside a function directly. For such requir...
""" In the previous part we have learned that any variable declared outside of any function is known as global variable. And scope of such variables is global. But we can declare a global variable directly inside a function also and scope of such variable will be global as well. We can achieve that with the help of 'gl...
""" As we know the concept of OOP revolves around 'objects' and to create an object we need class fo that object As the class works as the frame for any object. Using a class we can create any number of objects of that class which all have same properties(i.e attributes or variables) and behaviours(i.e operations or me...
""" Function :- A function is a block of code that can be run any number of time without defining it repeatedly just by calling it. Data can also be passed to a function as arguments for further processing and a function can also return a data as a result. Syntax of a function :- ---------------------------------------...
# Normal if-else statements :- a = 120 b = 30 if a > b: print("a is greater than b") elif a == b: print("a and b are equal") else: print("a is less than b") # short hand "if" statement :- if a > b: print("a is greater than b") # short hand "if-else" statement :- print("a is greater than b") if a > b ...
""" Comparison operators in Python :- Operator Name Example --------------------------------------------------------- == Equal x== y != Not equal x!=y > Greater than x>y < ...
# You are a professional robber planning to rob houses along a street. # Each house has a certain amount of money stashed. # All houses at this place are arranged in a [[[[[circle]]]]]. # That means the first house is the neighbor of the last one. # Meanwhile, adjacent houses have security system connected # and it wil...
# Given a binary tree, each node has value 0 or 1. # Each root-to-leaf path represents a binary number starting with the most significant bit. # For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. # For all leaves in the tree, consider the numbers represented by th...
from binary_tree import BinaryTree from node import Node ''' Methods that keep same as in base class BinaryTree: 1. is_tree_empty(self) -> bool 2. is_node_left_child(self, node: Node) -> bool 3. preorder_traversal(self, root_node: Node) 4. postorder_traversal(self, root_node: Node) ...
n=input('enter a number') m=math.sqrt(n) for i in range(2,m): r=n%i if r==0: break if r!=0: print('prime') else print('not prime')
'''Biggest number using three different method ''' l = [2, 5, 3, 4, 8, 10, 3] ''' using loop ''' m = l[0] for i in l: if m < i: m = i print(f'Biggest number: {m}') ''' using loop using index''' m1 = l[0] for i in l[1:]: if m1 < i: m1 = i print(f'Biggest number: {m1}') '''another process : u...
# -*- coding: cp1252 -*- print "Vlkommen till vr grymma kalkylator!" running = True while running: def plus (a, b): return a+b def minus (a, b): return a-b def multi (a, b): return a*b def div (a, b): if a==0 or b==0: print "Input invalid!" return ...
from fpdf import FPDF class Bill: """ Object that contains data about a bill such as total amount and period of the bill """ def __init__(self, amount, period): self.amount = amount self.period = period class Flatmate: """ Create a flatmate who lives in the flat and p...
import requests class Weather: """ Creates a Weather object getting an apikey as input and either a city name or lat and lon coordinates. Package use example: # given city weather = Weather(apikey=api_key, city="Boston") # given lat and lon weather = Weather(apikey=api_key, lat=4.1,...
class Matter: def __init__(self, temperature, freezing, boiling): self.boiling = boiling self.freezing = freezing self.temperature = temperature def state(self): if self.temperature < self.freezing: return "solid" elif self.temperature > self.boiling: ...
# coding: utf-8 import dis from threading import Lock, RLock # 在同一个线程里面,可以连续调用多次acquire,一定要注意acquire的次数要和release的次数相等 total = 0 lock = RLock() def add(): global total, lock for i in range(1000000): lock.acquire() lock.acquire() total += 1 lock.release() lock.release()...
# coding: utf-8 import threading from threading import Condition # 条件变量,用户复杂的线程间通信 class XiaoAi(threading.Thread): def __init__(self, cond): super().__init__(name="小爱") self.cond = cond def run(self): with self.cond: self.cond.wait() print("{} : 在 ".format(self....
# coding:utf-8 from collections.abc import Mapping, MutableMapping a = dict() # 不建议继承list和dict from collections import UserDict # class MyDict(UserDict): # def __setitem__(self, key, value): # super().__setitem__(key, value*2) # # # my_dict = MyDict(one=1) # print(my_dict) from collections import defaul...
class Solution: """ @param: n: The number of queens @return: All distinct solutions """ def solveNQueens(self, n): # write your code here self.ret = [] # board = ['.' * n] * n board = [['.' for i in range(n)] for j in range(n)] # print(board) self.zcs(...
# Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: the root of the tree @param target: the target @param K: the given K @return: All Nodes Distance K in Binary Tree """ de...
#! /usr/bin/python #filename typechk.py def displayNumType(num): print num , ' is ', if isinstance(num, (int, long ,float, complex)): print 'a number of type:', type(num).__name__ else: print 'not a number at all' while True: number = raw_input('Please input the number: '); if number == "quit": break; el...
#!/usr/bin/python #filename:if.py number = 23 guess = int(raw_input('Enter an integer:')) if guess == number: print 'Congratulations, you guessed it' elif guess < number: print 'No, it is a little highter than that' else: print 'No, it is a little lower than that' print 'Done'
#! /usr/bin/python #filename:using_dict.py ab = {'swaroop' :'swaroop@163.com', 'haha' :'haha@163.com', 'nihao' :'nihao@164.com', 'jingdong' :'jingdong@164.com'} print "Swaroop's address is %s" %ab['swaroop'] ab['junjun'] = 'junjun@163.com' del ab['nihao'] print '\nThere are %d contacts in the address-book\n' %l...
from tkinter import * import onetimepad root = Tk() root.title("Cryptosystem") root.geometry("450x200") def encryptMessage(): pt = e1.get() # inbuilt function to encrypt a message ct = onetimepad.encrypt(pt, 'random') e2.insert(0, ct) def decryptMessage(): ct1 = e3.get() # inbuilt function to dec...
#!/usr/bin/env python3 """Replace Placeholder Lines This module replaces placeholder lines in a file by contents of another file. Usage: ./replace_placeholder_lines.py [--keyword "#KEYWORD"] <FILE> This will go through every line in <FILE> and will try to replace all lines starting with '#KEYWORD' by the conten...
No_of_chars=256 def CanFormPalindrome(word): Count=[0]*No_of_chars for i in range(len(word)): Count[ord(word[i])]=Count[ord(word[i])]+1 odd=0 for j in range(0,No_of_chars): if(Count[j]&1): odd=odd+1 if(odd>1): return False return True word=input() if(C...
""" You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Fo...
# 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 rob(self, root): """ :type root: TreeNode :rtype: int """ rob_record = {} ...
def quick_sort(items): def _sort(items, l, r): if l < r: q = partition(items, l, r) _sort(items, l, q - 1) _sort(items, q + 1, r) def partition(items, start, end): pivot = items[end] i = start - 1 for j in range(start, end): if it...
# -*- coding:utf-8 -*- class Solution: def reOrderArray(self, array): odd, even = [], [] for i in array: if i & 1: odd.append(i) else: even.append(i) return odd + even
# 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]] """ ...
class Car(object): def __init__(self, name, price, speed, fuel, mileage): self.name = name self.price = price self.tax = 0 self.speed = speed self.fuel = fuel self.mileage = mileage def display_all(self): if self.price > 10000: self.tax = "15%"...
#Compare Lists def compareLists(list1, list2): '''Compare two lists when given two arguments. Arguments must be variables, not lists.''' if cmp(list1, list2) == 0: print "The lists are identical" else: print "The lists are not identical" compareLists([1,2,3,4,5], [1,2,3,4,5]) #premade arguments. Please chan...
my_dictionary = {"name": "Mendel", "age": 22, "language": "Ivrit", "nation": "Judaism"} def call_dictionary(dic): for keys, values in my_dictionary.iteritems(): print "My {} is {}".format(keys, values) call_dictionary(my_dictionary)
names = ["Adam", "Betty", "Charles", "David", "Edward", "Frank"] apples = ["Gala", "Yellow Delicious", "Granny Smith", "HoneyCrisp", "Red (not) Delicious", "Lady"] def make_dict_from_list(list1, list2): temp_dict = zip(names, apples) new_dict = dict(temp_dict) print new_dict make_dict_from_lis...
class Bike(object): def __init__(self, name, price, max_speed): self.name = name self.price = price self.max_speed = max_speed self.total_miles = 0 def displayinfo(self): print "The price for {} is ${}. Woah. That's a pretty penny.".format(self.name, self.price) p...
ipv6_addr1 = "2001:db8:1234::1" IPV6_ADDR2 = "2001:db8:1234::2" ipV6_addR3 = "2001:db8:1234::3" print("\n") print("Is variable 1 is equal to variable2: {}".format(ipv6_addr1==IPV6_ADDR2)) print("Is variable1 is equal to variable3: {}".format(ipv6_addr1!=ipV6_addR3))
def addNpointsLHS(self,inMatrix, m=1, method='random'): """ Add 'n' new points to the existing LHS matrix. NOTE: Assumes inMatrix to be a unit Hypercube i.e. all parameters are from 0-1 :param m: How many new points do you want. :param method: ...
# A entrada é descrita em uma única linha, que contém seis inteiros, separados por um # espaço em branco. Cv ,Ce, Cs, Fv, Fe, Fs, que são, respectivamente, o número de vitórias # do Cormengo, o número de empates do Cormengo, o saldo de gols do Cormengo, o # número de vitórias do Flaminthians, o número de empates do Fla...
def converter(hora): meianoite = 00 if hora > 12 and hora < 24: contador = 0 for x in range(hora): if x >= 12: contador += 1 return contador elif hora == 24: return meianoite else: return hora controle = "sim" while controle != "nao":...
palavra = input() letra = input() count = 0 for i in palavra: if letra == i: count = count + 1 print(count)
print('Digite o tempo gasto (em horas) e a velocidade media (em km/h):') entrada1 = float(input()) entrada2 = float(input()) distancia = entrada1 * entrada2 print('Quantidade de litros gastos na viagem: {:.6f}'.format(distancia/12.0))
# receba um valor do usuário (correspondente ao saldo da conta), outro valor do usuário # (correspondente ao valor da transação) e uma operação (débito ou crédito), e depois da # transação apresente o novo saldo da conta print('Bem vindo ao Banco do Nordeste defina qual a operação deseja realizar') saldoConta = float(...
digito1 = float(input()) digito2 = float(input()) operacao = input() while (operacao != '&'): if (operacao == '-'): digito1 -= digito2 print('{:.3f}'.format(digito1)) elif (operacao == '+'): digito1 += digito2 print('{:.3f}'.format(digito1)) elif (operacao == '*'): d...
a = input().split() v1 = float(a[0]) v2 = float(a[1]) v3 = float(a[2]) pi = 3.14159 TRIANGULO = (v1 * v3) / 2 CIRCULO = pi * (v3 ** 2) TRAPEZIO = ((v1 + v2) * v3) / 2 QUADRADO = v2 * v2 RETANGULO = v1 * v2 print('TRIANGULO: %.3f' %TRIANGULO) print('CIRCULO: %.3f' %CIRCULO) print('TRAPEZIO: %.3f' %TRAPEZIO) print('QUADR...
# coding: utf-8 a = int(input("Entre com o primeiro valor: \n")) b = int(input("Entre com o segundo valor: \n")) c = int(input("Entre com o terceiro valor: \n")) if(a > b and b > c): print('{} > {} > {}'.format(a,b,c)) elif(a > b and c > b): print('{} > {} > {}'.format(a,c,b)) elif(b > a and a > c): print...
# coding: utf-8 user = raw_input("Nome de usuario: ") senha = raw_input("Senha: ") while (senha == user): senha = raw_input("Digite uma senha diferente do nome de usuário: ") print ("Usuário: %s | Senha: %s" % (user, senha))
lista=[] contador=0 contador2=0 notas=int(input()) if (notas == 0): print("Numero de notas invalido.") else: while (contador < notas): lista.append(float(input())) contador +=1 media = (sum(lista) / notas) for i in range(notas): #print("Nota ", contador2 + 1, ": ", lista[contador2], sep="") prin...
import turtle import math screen = turtle.Screen() screen.bgcolor("blue") screen.title("Frosty the snowman!") frosty = turtle.Turtle() frosty.speed(0) frosty.color("black") frosty.fillcolor("white") frosty.pensize(3) frosty.hideturtle() def face (x, y): frosty.up() fro...
# 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 isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def depth(n...
# Definition for binary tree with next pointer. class TreeLinkNode(object): def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution(object): def connect(self, root): """ :type root: TreeLinkNode :rtype: nothi...
# 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 rob(self, root): """ :type root: TreeNode :rtype: int """ memoize = {} ...
from utils import * def manual_3_points(): """Trajectory Optimization of Box Moving Problem Using Lagrange Multiplier on 3 collocation points This code implements the Lagrangian multiplier method for the box moving problem using Lagrange Multipliers, where number of collocation points = 3. Coefficients ar...
# Given two strings s and t, write a function to determine if t is an anagram of s. # # For example, # s = "anagram", t = "nagaram", return true. # s = "rat", t = "car", return false. import collections class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype...
# There are 1000 buckets, one and only one of them contains poison, the rest are # filled with water. They all look the same. If a pig drinks that poison it will # die within 15 minutes. What is the minimum amount of pigs you need to figure # out which bucket contains the poison within one hour. # # Answer this questi...
# Given a sorted linked list, delete all duplicates such that each element appear only once. # # For example, # Given 1->1->2, return 1->2. # Given 1->1->2->3->3, return 1->2->3. # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solutio...
# You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # # Note: Given n will be a positive integer. class Solution: # this solution will not pass,even it is correct.due to it wastes a lot of time....
# # Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants # # represented by strings. # # # # You need to help them find out their common interest with the least list index sum. # # If there is a choice tie between answers, output all of them with no order req...
# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. # Now given an M x N matrix, return True if and only if the matrix is Toeplitz. # Example 1: # # Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] # Output: True # Explanation: # 1234 # 5123 # 9512 # # In the above grid, the diag...
# Given an integer array, you need to find one continuous subarray that if # you only sort this subarray in ascending order, then the whole array will be # sorted in ascending order, too. # # You need to find the shortest such subarray and output its length. # # Input: [2, 6, 4, 8, 10, 9, 15] # Output: 5 # Explanation:...
# Given an integer array, find three numbers whose product is maximum and output # the maximum product. # # Example 1: # Input: [1,2,3] # Output: 6 # Example 2: # Input: [1,2,3,4] # Output: 24 class Solution: def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """...