text
stringlengths
37
1.41M
#!/usr/bin/env python3 # Created by: Haokai Li # Created on: Sept 2021 # This Program calculate weight and volume of package def main(): # This function calculate weight and volume of package # input string_weight = input("Please enter weight of the package(kg): ") string_length = input("Please ente...
# # CSE 3521 - Programming Assignment 01 (Part1) # # Input - one text file containing a single integer in each line and several # such lines; this text files is expected to contain the ranks of the ojects # coming down the Conveyer Belt in this environment. The assumption is that the # file is well formatted. Occur...
import sqlite3 conn = sqlite3.connect('UsuariosApp.db') cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS Usuarios ( Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Nome TEXT NOT NULL, Email TEXT NOT NULL, Senha TEXT NOT NULL ); """) print('Conectando ao Banco de Dad...
# --- Day 14: Docking Data --- # As your ferry approaches the sea port, the captain asks for your help again. The computer system that runs this port isn't compatible with the docking program on the ferry, so the docking parameters aren't being correctly initialized in the docking program's memory. # After a brief ins...
def nextPrime(primes, cur): for p in primes: if (cur % p == 0): return nextPrime(primes, cur+1) return cur def getNthPrime(n): p = 2 primes = [2] for i in xrange(n): p = nextPrime(primes, p) primes.append(p) print(p) print(len(primes)) getNthPrime(10000)
from tkinter import * #Zona de clases #Zona de funciones #Ejemplo def Hello(): det=Tk() frame = Frame(det) lan = ["Python", "C++", "iOS", "Swift"] d = 1; list = Listbox(frame) for i in lan: list.insert(d, i) d += 1 frame.pack() list.pack() det.mainloop() #Venta...
#!/usr/bin/env python3 class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state class YourBorg(Borg): def __init__(self, state=None): # Share __dict__ between all instances super().__init__() if state: self.state = state el...
#!/usr/bin/python3 import time import numpy as np import tkinter as tk UNIT = 80 H, W = 5, 5 class Maze(tk.Tk, object): def __init__(self): super(Maze, self).__init__() self.action_space = ['E', 'W', 'S', 'N'] self.n_state = 2 self.n_action = len(self.action_space) self.ti...
import random def place_marker(board, marker, position): board[position] = marker def display_board(board: list): print('\n' * 5) print(board[7] + '|' + board[8] + '|' + board[9]) print('-' * 6) print(board[4] + '|' + board[5] + '|' + board[6]) print('-' * 6) print(board[1] + '|' + board...
# creating a caesar cipher def encrypt(string, shift_by): """ Encrypt the string into a new string """ numList = [(ord(s) - shift_by) for s in string] encrypted_string = '' for i in numList: encrypted_string += chr(i) return encrypted_string encryptedSentence = encrypt('This is a s...
''' Password Management ''' import string from random import choice, shuffle def generate(length = 15, caps = 2, nums = 2, chars = 2, restricted = "", isExactly = False): ###BELOW ARE CONSTANTS LOWERCASE = removeRestricted(string.ascii_lowercase, restricted) UPPERCASE = removeRestricted(string.asc...
bonacci(signature, n): if(n==0): return [] if(n==1): return signature[:1] if(n==2): return signature[:2] if(n==3): return signature[:3] tribonacciSequence = signature.copy() while len(tribonacciSequence) < n: tribonacciSequence.append(tribonacciSequen...
import sys import data import index import utils def main() -> None: """ Driver method """ # Read arguments filename = sys.argv[1] products = sys.argv[2:] # Load data and create index items = data.read_data(filename) item_index, shop_index = index.build_index(items) # Find r...
def calculate_bisiesto(año): if(año%400==0)or(año%100!=0)and(año%4==0): return ('True') else: return ('False') def main(): #escribe tu código abajo de esta línea año = int(input()) print(calculate_bisiesto(año)) pass if __name__=='__main__': main()
from collections import namedtuple import datetime Book = namedtuple('Book', ['title', 'author', 'year_published', 'subject', 'section']) #title(str), author(str), year_published(int), subject(str), section(str) Checkout = namedtuple('Checkout', ['book', 'student', 'due_date']) #book(Book), student(Student), due_date...
# File: nums.py # Started: by Dr. Gibson # Author: Sanaa Mironov # Date: Oct 24, 2016 # Section: 04 # Description: # This file contains python code that uses functions to # allow a user to get basic information about a number # they've entered. MIN_VAL = -1000000 MAX_VAL = 1000000 def evenOrOdd(number):...
def topological_sort(graph): def dfs(graph, used, order, u): used[u] = True for v in graph[u]: if not used[v]: dfs(graph, used, order, v) order.append(u) n = len(graph) used = [False] * n order = [] for i in range(n): if not used[i]: ...
string = input() character_count = {} for i in string: if i not in character_count: character_count[i] = string.count(i) odd_counts = 0 for i in character_count: if character_count[i] % 2 == 1: odd_counts += 1 if odd_counts > 1: print("NO") else: print("YES")
from Tkinter import Tk, Canvas, BOTH from math import sin, cos, radians from random import choice, randint WIDTH=1000 HEIGHT=600 global text1 def quit_to_exit(): w=Tk() w.after(3000, lambda:w.destroy()) w.mainloop() def call(): # f = open("score_data.txt", "r+") class Breakout(Tk): def __init__(self): ...
from matplotlib import pyplot as plt plt.ion() plt.plot([1,2,3]) # h = plt.ylabel('y') # h.set_rotation(0) plt.ylabel(-0.1, 0.5, 'Y label', rotation=90, verticalalignment='center', horizontalalignment='right', transform=plt.ylabel.transAxes) plt.draw()
nombre = input("Por favor ingrese su nombre: ") print(nombre) prueba = str(20) print(type(prueba)) print(prueba) numero = int(input("Por favor ingrse un número: ")) flotante = float(input("Por favor ingruese un número decimal: ")) titulo = input("Proporciona el titulo: ") autor = input("Proporciona el autor") pr...
class Caja: def __init__(self, alto, ancho, largo): self.__alto = alto self.__ancho = ancho self.__largo = largo def calcularVolumnen(self): return self.__alto * self.__ancho * self.__largo alto = int(input("Por favor inrese el alto de la caja: ")) ancho = int...
a = int(input("Ingrese un valor: ")) min = 0 max = 5 dentroRango = a >= min and a <= max print(dentroRango) if dentroRango: print("Dentro del rango") else: print("Fuera de rango") descanso = False vacaciones = True if descanso or vacaciones: print("Puedo ir a donde quiera") else: print("Te...
import turtle import time import sys from collections import deque from tkinter import * window = Tk() window.title("BFS Maze Solving Program") wn = '' # window declared # this is the class for the Maze class Maze(turtle.Turtle): def __init__(self): turtle.Turtle.__ini...
from random import choice def open_and_read_file(file_path): """Takes file path as string; returns text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ file_obj = open(file_path) file_text = file_obj.read() file_ob...
############################################################################ ## Python sample code to create a new pdf file with different formats ## ## Author: Gunther Bacellar ## ## Email: gcbacel@hotmail.com ## ############...
from typing import Any,Sequence def bin_search(a:Sequence, key:Any)-> int: pl=0 pr=len(a)-1 while True: pc=(pl+pr)//2 if a[pc]== key: return pc elif a[pc]<key: pl=pc+1 else: pr=pc-1 if pl>pr: break re...
# a부터 b까지 정수의 합을 구하자 (for문 이용) import time import os print("a부터 b까지 정수의 합을 구하는 프로그램을 시동합니다....") print("로딩중...") time.sleep(1) print("30% 완료") time.sleep(4) print("72% 완료") time.sleep(2) print("97% 완료") time.sleep(2) print("잠시만 기다려 주세요...") time.sleep(5) print("정수 a와 b의 값을 입력해 주세요") a=int(input("정수 a를 입력해주세요:")) b=...
""" " draw the scatter with log plot of both " X and Y axis " accept two lists as input " range, x/y labels, title and Ticks """ import matplotlib.pyplot as plt import math class plotLog(): def __init__(self, xData, yData,): self.xData = [math.log10(x) for x in xData] self.yData = [math.log10(y) ...
# Created by Viktoria # (▰˘◡˘▰) # 21/10/2020 # Student number: R00180598 import math def powerV1(): num1=int(input("please enter the base number: ")) num2=int(input("please enter the power number: ")) print("The value {} raised to the power of {} is :{} ".format(num1,num2,pow(num1,num2))) def ...
# Created by Viktoria # (▰˘◡˘▰) # 21/10/2020 # Student number: R00180598 options=["Addition","Subtraction","Multiplication","Division"] symbols=['+','-','*','/'] def menu(): print("What would you like to perform?") print("1: Addition") print("2: Subtraction") print("3: Multiplication") ...
# Created by Viktoria # (▰˘◡˘▰) # 21/10/2020 # Student number: R00180598 fibonacci=[0,1] def sequence(): for i in range(40+1): fibonacci.append(fibonacci[i]+fibonacci[i+1]) print(fibonacci) def getNum(index): return fibonacci[index-1] sequence() print(getNum(13))
print(bool("Hello")) print(bool(15)) x = "Hello" y = 15 print(bool(x)) print(bool(y)) class myclass(): def __len__(self): return 0 myobj = myclass() print(bool(myobj))
#!/usr/bin/python # # Sums all the values from a certain predicate from the database. import sys from lib_db import read_db if len(sys.argv) < 3: print "usage: count_db_total.py <predicate> <argument position (1..N)>" sys.exit(1) predicate = sys.argv[1] position = int(sys.argv[2]) db = read_db(sys.stdin.readlines...
""" Class Block : - block_ids: a list of blocks (We give each block an id) eg. [Block A, Block B] - id_quantity: a dictionary consist of id and its corresponding quantity eg. {id: quantity, id:quantity} - size: block size, a list of [L,W,H] eg. [100, 40, 100] - orientation: - fitness: """ class Block: de...
"""Utility functions for storing and loading json data. Attributes: basepath (str): Basepath for object files. basepath_json (str): Basepath for json files. basepath_pick (str): Basepath for pickle files. """ import json # import pickle from os import makedirs, path import shutil # import traceback # ...
""" and ---- ve or ---- veya not ----- değil """ sayi = int(input("Sayi Gir: ")) sayi2 = int(input("Sayi2 Gir: ")) if sayi > 5: if sayi % 2 == 0: print("Doğru") //kolay yolu if sayi > 5 and sayi % 2 == 0: //and (ve demek) print("doğru") if sayi > 5 or sayi2 == 5: // veya demek ...
# list that saves the names of the subjects and the grades of those subjects last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)] # lists that saves other subjects and grades subjects = ["physics", "calculus", "poetry", "history"] grades = [98, 97, 85, 88] # this adds compu...
import utils import sorts bookshelf = utils.load_books('books_small.csv') bookshelf_v1 = bookshelf.copy() bookshelf_v2 = bookshelf.copy() long_bookshelf = bookshelf.copy() def by_title_ascending(book_a,book_b): if book_a['title_lower'] > book_b['title_lower']: return True return False def by_autho...
### # Code by Olzhas Kurenov # Implementation of Quick Sort # Average running time: O(nlog) ### from random import randint print '\n~~~~~~~~~Quick Sort Algorithm~~~~~~~~~\n' print 'Reading input file\n' with open('quickSort.txt') as f: lines = f.readlines() numbers = []; for line in l...
#Importin tweepy to access twitter import tweepy #importing json to write to ajson file import json #importing pandas to create graph import pandas as pd #importing matplotlib to plot graph import matplotlib.pyplot as plt #impotrting tweepy to access twitter from tweepy import OAuthHandler #storing keys in public varia...
def verify_password(line: str, version: int = 1) -> bool: policy, password = [item.strip() for item in line.split(':')] bounds = policy[:-2] letter = policy[-1] low, high = [int(item) for item in bounds.split('-')] if version == 1: letter_count = password.count(letter) if low <= let...
import sys def collatz_terms(A, limit): num_terms = 0 while A != 1 and A <= limit: if A % 2 == 0: A /= 2 else: A = 3 * A + 1 num_terms += 1 if A == 1: num_terms += 1 return num_terms case = 1 for line in sys.stdin: A, limit = [int(n) for n in...
import pygame from pygame import gfxdraw from .color import Color class Draw: game_display = None screen_width = 0 screen_height = 0 @classmethod def set_game_display(cls, screen, screen_width, screen_height): """ set the screen reference :param screen: the pygame's screen...
# -*- coding: utf-8 -*- """ Fig. 3.4. beta prior y posterior @author: COTP """ #librerias a usar import numpy as np import matplotlib.pyplot as plt import scipy.stats as ss #fijando la semilla np.random.seed(0) #función de probabilidad (beta) def fun1(n,a,b): X=ss.beta(a,b) X1=X.pdf(n) ...
import pygame BLUE = (0,0,255) BLACK = (0,0,0) RED = (255,0,0) YELLOW = (255,255,0) WHITE = (255,255,255) class Button: def __init__(self,screen,x,y,w,h,wm,hm,name): self.screen = screen self.color = [YELLOW,RED] self.toggle = 0 self.name = name self.x,self.y,self.w,self.h,...
#!/bin/python3.6 import re f = open('./madlibs.txt').read() for word in f.split(): if "ADJECTIVE" in word: print("Enter a new adjective: ") newAdj = input() f = f.replace("ADJECTIVE", newAdj) if "NOUN" in word: print("Enter a new noun: ") newNoun = input() f = f.replace("NOUN", newNoun, 1...
''' This python program solves the given non linear equation by various methods ''' import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt from scipy.optimize import * def f(x):# the function return np.sin(np.cos(np.exp(x))) ''' Root finding by bisection method in the range (-1....
INF = int(1e9) # graph = [[] for i in range(n + 1)] graph = [ [], [(2, 2), (3, 5), (4, 1)], [(3, 3), (4, 2)], [(2, 3), (6, 5)], [(3, 3), (5, 1)], [(3, 1), (6, 2)], [] ] visited = [False] * (len(graph)) dist...
from collections import deque queue = deque() queue.append(8) queue.append(1) queue.append(4) queue.append(2) print("팝 :", queue.popleft()) queue.append(0) queue.append(3) print("팝 :", queue.popleft()) print(queue) queue.reverse() print(queue)
s = list(input()) s.sort() sum = 0 for c in s: if '0'<= c <= '9': sum += int(c) else: print(c, end='') print(sum)
n = int(input()) array = [] for _ in range(n): data = input().split() array.append((data[0], int(data[1]))) array = sorted(array, key = lambda student: student[1]) for i in array: print(i[0], end = ' ') # print([x[0] for x in d])
def bubblesort(myList): for item in range(len(myList)): for i in range(len(myList)-1): if myList[i] > myList[i+1]: myList[i], myList[i+1] = myList[i+1], myList[i] numList = [1, 5, 6, 7, 8, 2, 3, 4, 5, 6, 1, 8, 9, 4, 243, 23, 12, 19, 54, 43] bubblesort(numList) print...
import matplotlib.pyplot as plt import pandas as pd # setting to display max 85 columns because default is 10 pd.set_option('display.max_columns', 85) # loading data df_data_schema = pd.read_csv('survey_results_schema.csv', header=0) # loading next column but this time respondent number is row id too df_data_public =...
sentence = input("Write a sentence: ") print() long = len(sentence) reverse="" for i in range(long): reverse = reverse + sentence[long-1] long = long-1 print("Your sentence in reverse order is: " + str(reverse))
frase=str(input("Write a sentence and I'll give you back the letters that are in even positions.")) i=0 frase=frase.replace(' ','') leng=len(frase) while (i<=leng): if (i%2!=0): print(frase[i]) i+=1
def Bsearch(LIST, ITEM, n): # n is the number of elements in list ''' Main Function for the Binary Search ''' beg = 0 # starting element last = n - 1 # end element while (beg<=last): mid = (beg + last)//2 if (ITEM == LIST[mid]): return mid elif (ITEM > LIST[m...
iteration = 0 state = 'A' position = 0 data = ['0','1','1','1','1','1',''] #output of first data print(f"Input data: ", data) #algorithm print(f"⋙State: ",state, f"⋙Position: ", position, f"⋙Data state: ", data) def stateA(): global position global state if data[position] == '1' or data[position] == '0': # same ...
fruits = ["Bananas", "Oranges", "Mangoes", "passion fruits"] for x in fruits: print(x) if x == "Mangoes": break # BREAKING BEFORE THE LOOP fruits = ["Bananas", "Oranges", "Mangoes", "passion fruits"] for x in fruits: if x == "Mangoes": break print(x) #CONTINUE USE, STOPS THE MENTION ELEMENT IN THE LI...
class person: def __init__(self, age, name): self.age = age self.name = name def myfunction(self): print("Hello my name is " + self.name + " and am", self.age) p1 = person(30, "John") p1.myfunction()
def ordinal( x ): suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'] if x < 0: x *= -1 x = int(x) if x % 100 in (11,12,13): p = 'th' else: p = suffix[x % 10] return str(x) + p print[ordinal(n) for n in range(1,10)]
##Screen asking you to input yourname print("Enter your name:") x = input() print("Hello", x)
class Myfirstclass: def __init__(self, name, age): self.age = age self.name = name p1 = Myfirstclass("James", 30) #print("My name is", p1.name, "and am " , p1.age,".") print(p1.age) print(p1.name)
#Data Belanja1 = input("Masukkan daftar belanja 1:") Belanja2 = input("Masukkan daftar belanja 2:") Belanjatambah1 = input("Tambahkan data ke daftar belanja 1:") Belanjatambah2 = input("Tambahkan data ke daftar belanja 2:") #Progres print("Daftar belanja 1 adalah", Belanja1 +","+Belanjatambah1) print("Daftar belanja 2...
print('-' * 75) import json # Dictionary emp = { 1: { 'name': 'justin', 'loc': 'kochin' }, 2: { 'name': 'tris', 'loc': 'hyderabad' }, 3: { 'name': 'davies', 'loc': 'noida' } } print(emp, '-', type(emp)) print('-' * 75) # Convert dictionary to J...
proceed = 1 try : dictFile = open(input("Enter the file path to create Keys : "), encoding="utf8") except Exception : print (" FILE OPEN ERROR FROM CODE") proceed = 0 if proceed==1 : # trigger an empty dictionary wordDict = dict() count = 0 for line in dictFile : wordKeys = line.split() ...
''' itertools.islice() perfrom lazy slicing of any iterator ''' from itertools import islice, count one_million_numbers = (x for x in range(1, 1000000)) first_ten = islice(one_million_numbers, 10) for x in first_ten: print(x) def is_even(num): """ Predicate Function :param num: :return: ""...
import threading from time import sleep def do_work(item): print("Processing !! --> {} by --> {} ".format(item, threading.current_thread().name)) sleep(1) def worker(): while True: # get processing item from queue when available item = q.get() if item is None: break ...
''' Syntax: Generators are type of comprehension that generates generator object. Syntax is similar to list comprehension, instead of square brackets [], parenthesis are used () (expr(item) for item in iterable) where needed : where you need, - lazy evaluation of generators and - declarative way of writing comprehensi...
import turtle from random import randint from turtle import Turtle, Screen class DrawShapes() : def __init__(self, turtleShape = "Arrow", turtleColor = "red"): self.xLoc = 0 self.yLoc = 0 self.my_turtle = turtle.Turtle() self.color = "red" self.screen = Screen() se...
print('-' * 75) # Functions # Re-usable piece of code def validate_mobile_number(mobile): status = 'invalid' ''' Should be 10 Digits First digit should be between 6 and 9 ''' if len(mobile) == 10 and mobile.isdigit() and int(mobile[0]) in range(6, 10): status = 'valid' return stat...
""" Model to aircraft flights """ from pprint import pprint as pp class Flight: ''' instance method for initializing new objects it is an initializer not a constructor self ~ this in java _number ? why - to avoid name clash with number() - by convention, implementation details start wi...
import random import turtle from random import randint from turtle import Turtle, Screen class RandomWalk(): def __init__(self, screen_size=500, step_size=20, steps_to_take=500, use_heading = False ): self.xLoc = 0 self.yLoc = 0 self.my_turtle = turtle.Turtle() self.color = "red" ...
''' Exercise 4.6 - Successor: Write an algorithm to find the "next" node of a given node in a binary seach tree. ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None self.parent = None def minNode(node): while root.left: ...
''' Exercise 10.4 - Sorted Search, No Size: You are given an array-like data structure Listy which lacks a size method. It does, however, have an elementAt(i) method that returns the element at index i in O(1) time. If i is beyond the bounds of the data structure, it returns -1. (For this reason, the data structur...
''' Exercise 1.2 - Check Permutation: Given two strings, write a method to decide if one is a permutation of the other. O(n) solution ''' def stringToDict(s): character_dict = dict() for character in s: if character not in character_dict: character_dict[character] = 1 else: character_dict[character] += ...
""" Bellman-Ford algorithm Time Complexity: O(EV) """ def shortestPath(graph, start): # Initialize distances. distance = {} for k in graph: distance[k] = float('inf') distance[start] = 0 # Rellax all edges V -1 Times. for _ in range(len(graph)): for node in graph: ...
''' Exercise 8.5 - Recursive Multiply: Write a recursive function to multiply two positive integers without using the * operator or / operator. You can use addition, substraction, and bit shifting, but you should minimize the number of those operations. ''' def recursiveMultiply(a,b): def multiply(a,b): if a =...
''' Exercise 2.6 – Palindrome: Implement a function to check if a linked list is a palindrome. ''' from LinkedList import LinkedList from collections import deque def isPalindrome(myList): current = runner = myList.head stack = deque() while runner != None: stack.append(current.value) current = current.nex...
def partition(myList, start, end): pivot = myList[(start + end)//2] while start <= end: while myList[start] < pivot: start += 1 while myList[end] > pivot: end -= 1 if start <= end: myList[start], myList[end] = myList[end], myList[start] start += 1 end -= 1 return start def quickSort(myList...
''' Exercise 2.2 – Return Kth to Last: Implement an algorithm to find the Kth to last element of a singly linked list. ''' from LinkedList import LinkedList # Revursive def recursiveKth(node,k): if node == None: return 1, None position, kvalue = recursiveKth(node.next,k) if position == k: return position+...
''' Priority Queue for Dijkstra Algorithm Time Complexity: * add = O(1) // We do not heapify * pop = O(log(n)) * decrease = O(log(n)) ''' class PriorityQueue: def __init__(self): self.nodes = [] self.total_nodes = 0 self.indexs = {} def add(self, ...
# -*- coding: utf-8 -*- """ Created on Sun Sep 6 11:42:27 2020 @author: Parvish """ # Finds sum with equal partition of the list def equalPartitionSums(l): listLength=len(l) l1=[] l2=[] for i in range(listLength,0,-1): for j in range(0,listLength-1): l1.append(l[j]) ...
pw = "Kaddan" intentos = 3 clave = input("BIENVENIDO AL SISTEMA. POR FAVOR, INSERTAR LA CLAVE DE ACCESO:") while intentos>0: if pw.lower() == clave.lower(): print("\nLA CONTRASEÑA ES CORRECTA. BIENVENIDO AL SISTEMA.") intentos = 0 else: intentos -=1 if intentos==0: p...
# 1. Realiza una función que imprima 'Hola Mundo' def holamundo(): print('Hola Mundo!') # 2. Realiza una función que sume dos números pasados por parámetros def sumador(a,b): return a+b # 3. Realiza una función que indique si un número pasado por parámetro es par o impar. def espar(a): return (a%2 == 0) # 4...
### Scope ### ## Age ## # Find the average age, for all and gender ## Charges ## # Average charge, for all and gender ## Smoking ## # Find ratio of smokers in genders # Find ratio of smokers with low, normal and high BMI # Find ratio of smokers for people with and without kids # Average price increanse for smokers v...
r = float(input()) area = 3.1416 * r * r print(area)
''' 494. Target Sum [Medium] You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: ...
''' 面试题26. 树的子结构 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树 A:      3     / \    4   5   / \  1   2 给定的树 B:    4    /  1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true 限制: 0 <= 节点个数 <= 10000 [前序遍历+递归] 首先要...
''' 地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。 一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。 但是不能进入行坐标和列坐标的数位之和大于 k 的格子。 请问该机器人能够达到多少个格子? 样例1 输入:k=7, m=4, n=5 输出:20 样例2 输入:k=18, m=40, n=40 输出:1484 解释:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。 但是,它不能进入方格(35,38),因为3+5+3+8 = 19。 注意: 0<=m<=50 ...
''' 【剑指offer】 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 [Method 1]: 抽屉原理(桶排序) 因为原数组包含的是从0到n-1的数,为了处理0,先把原数组每个数+1, 然后遍历每个数,把每个数(其绝对值-1)看成是一个index,把该index的数取反, 表示该index的数是存在的, 因为只需要输出第一个重复的数字, 则当我们遇到该index的数为负时,就可以...
''' Passing Parameters In URLs ''' import requests # http get request payload = {'key1': 'value1 ', 'key2': 'value2 '} r1 = requests.get('https://httpbin.org/get', params=payload) print(r1.url) # https://httpbin.org/get?key1=value1+&key2=value2+ # http post request: payload = {'key1': 'value1 ', 'key2': ['...
''' 字节跳动面试题, 同样的条件,给出一个target,看在数组里面小于等于k的元素个数有多少个。 Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example: ...
''' 543. Diameter of Binary Tree [Easy] Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree 1 ...
''' Method 1: Bit operation #O(1) If n is the power of two: n = 2 ^ 0 = 1 = 0b0000...00000001, and (n - 1) = 0 = 0b0000...0000. n = 2 ^ 1 = 2 = 0b0000...00000010, and (n - 1) = 1 = 0b0000...0001. n = 2 ^ 2 = 4 = 0b0000...00000100, and (n - 1) = 3 = 0b0000...0011. n = 2 ^ 3 = 8 = 0b0000...00001000, and (n - 1) = 7...
''' 100. Same Tree > 类型:DFSF分制 > Time Complexity O(N) > Space Complexity O(h) Runtime: 32 ms, faster than 92.27% of Python3 online submissions for Same Tree. Memory Usage: 13.9 MB, less than 5.72% of Python3 online submissions for Same Tree. ''' class Solution: def isSameTree(self, p: TreeNode, q: Tree...
#0-1 背包问题 def knapsack1(weight, value, capacity): ''' >>> knapsack1([], [], 10) 0 >>> knapsack1([3], [10], 0) 0 >>> knapsack1([4], [15], 4) 15 >>> knapsack1([4], [15], 10) 15 >>> knapsack1([4], [15], 3) 0 >>> weight = [1, 2, 3, 8, 7, 4] >>> value = [20, 5, 10, 40, 15...
''' --------------------------------------------- 70.Climbing Stairs [Easy] --------------------------------------------- DP (Bottom Up) Time: O(n), Space: O(n) ''' class Solution: def climbStairs(self, n: int) -> int: if n < 2: return n dp = [0]*n dp[0], dp[1] = 1, 2 for...
''' 26. Remove Duplicates from Sorted Array [Easy] Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example ...
import unittest from circles import circle_area from math import pi ''' test command: winpty python -m unittest test_circles or: winpty python -m unittest # it will search for tests and run them ''' class TestCircleArea(unittest.TestCase): def setUp(self): self._f = circle_area def test_ar...