text
stringlengths
37
1.41M
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'} newId = input('请输入新的学号') info['id'] = int(newId) print('修改之后的id为:%d'%info['id'])
# 定义类 class Demo: # 定义构造方法 def __init__(self, obj): self.data = obj[:] # 定义索引、分片运算符重载方法 def __getitem__(self, index): return self.data[index] # 创建实例对象,用列表初始化 x = Demo([1, 2, 3, 4]) print(x[1]) # 索引返回单个值 print(x[:]) # 分片返回全部的值 print(x[:2]) # 分片返回部分值 for num in x: # for循环迭代 p...
a=10 b=20 #判断a and b if ( a and b ): print("1——变量 a 和 b 都为 true") else: print("1——变量 a 和 b 有一个不为 true") # 判断a or b if ( a or b ): print("2——变量 a 和 b 都为 true,或其中一个变量为 true") else: print("2——变量 a 和 b 都不为 true") # 修改变量 a 的值 a = 0 if ( a and b ): print("3——变量 a 和 b 都为 true") else: print("3——变量 a 和 b 有一个不为...
from collections import Counter def all_uniqs(input_str: str): ctr = Counter(input_str) # print(ctr) # print(type(ctr)) for k,v in ctr.items(): # print(k,v) if v >1: return False return True def all_uniqs_no_datastruct(x:str): sorted_x = sorted(x) # print(type...
#!/usr/bin/python3 """ Task 12 module """ class Student: """ a class that students don't attend GET IT?!?! """ def __init__(self, first_name, last_name, age): ''' in it ''' self.first_name = first_name self.last_name = last_name self.age = age def ...
#!/usr/bin/python3 """ Task 7 Module """ import json def save_to_json_file(my_obj, filename): """ Writes object to text file using json representation """ with open(filename, 'w', encoding='utf-8') as f: json.dump(my_obj, f)
#!/usr/bin/python3 '''2-matrix_divided docstring''' def matrix_divided(matrix, div): '''Divides a matrix''' if not all(isinstance(li, list) for li in matrix): raise TypeError("matrix must be a matrix (li" "st of lists) of integers/floats") for li in matrix: for x in...
#!/usr/bin/python3 def uniq_add(my_list=[]): sum = 0 if (len(my_list) == 0): return sum new1 = my_list.copy() new1.sort() sum = new1[0] if (len(my_list) == 1): return sum for i in range(1, len(new1)): if new1[i] == new1[i - 1]: continue else: ...
# Note - this will work for Python 2.7, for Python 3 you seem to need to make the list indices integers rather than floats. def median(l): l.sort() if len(l) % 2 == 1: return l[len(l)/2] else: return (l[len(l)/2]+l[len(l)/2 -1])/2.0 #Python 3 version: #def median(l): #l.sort() #if len(l) % 2 == 1: #return l...
''' Base class for all tree types, to ensure operations have reasonable guarantees about what's available to use. ''' class Tree: def insert(self, pos, value): ''' Insert a child to the tree with string "value" at position "pos" ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree must de...
# By Matthew Thorburn # for EEE4120F Yoda project # User can guess the password in this program, also used for generating target hashes import hashlib import time import os #TargetHash = "1a1dc91c907325c69271ddf0c944bc72" # pass TargetHash = "76a2173be6393254e72ffa4d6df1030a" # passwd #TargetHash = "d7909618...
#!/usr/bin/env python # coding: utf-8 # In[1]: x=input('Enter a word: ') x=x[::-1] print(x) # In[ ]:
__author__ = 'pratibh' dict={1:{1:'something',2:'nothing'}} for key,value in dict.items(): print(key) print(value) print("******") for k,v in value.items(): print(k) print(v)
print("enter the following operator") print("1. +") print("2. -") print("3. *") print("4. /") a = input() print("enter the first digit") b = int(input()) print("enter the second digit") c = int(input()) if a == "+" : if b== 56 and c==9: print(77) else: print("sum =",b+c) elif a == "-": print...
a = raw_input("Enter a String : ") count = 0 for i in range(0,len(a)): if (a[i]=="a" or a[i]=="e" or a[i]=="o" or a[i]=="u" or a[i]=="i"): count = count+1 print count
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This is a base class for manipulating all sqlite databases. """ #pragma pylint=off # Credits __author__ = 'George Flanagin' __copyright__ = 'Copyright 2017 George Flanagin' __credits__ = 'None. This idea has been around forever.' __version__...
# name = input('Tell me your name:') # age = input('...and your age:') # print(name, 'you are', age) # Calculations - need to convert input to a number # inputs automatically gets stored as a string # Calculate the area of a circle (piR^2) radius = input('Enter the radius of your circle (m):') area = 3.142*int(radius...
grid = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "] ] locationGrid = [ ["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"], ["2,0", "2,1", "2,2"] ] player = 1 line = " ------------- " def printLine(): print(line) def printGrid(grid): printLine() textGrid = " |...
""" This code simulates the Monty Hall gameshow, in which contestants try to guess which of 3 closed doors contains a cash prize. The odds of choosing the correct door are 1 in 3. As a twist, the host of the show occasionally opens a door after a contestant makes a choice. This door is always one of the two the contest...
class Solution(object): def helper(self, sets, index,nums): if index == len(nums): return sets num = nums[index] new_sets = [] for old_set in sets: new_set = [n for n in old_set] new_set.append(num) new_sets.append(new_set) ...
# 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 isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root is...
from graphviz import Graph class Stack: def __init__(self): self.items = [] def empty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def top(self): return self.items[-1] def size(self): return len(self.items) class Queue: def __init__(self): self.items...
""" Use example code if you want to use the Zora robot 1 - You will need to install Python 2.7 - 32 bits (be sure that it is the 32 bits version) You can find the installer here: https://www.python.org/downloads/release/python-2714/ 2 - After installing Python, install the naoqi executable also in Library: pynaoqi...
#!/usr/bin/python3 import platform Windows = platform.system() == 'Windows' def cc_intersection(P0, P1, r0, r1): """ Circle-Circle Intersection P0, P1 are coordinates of circle centers r0, r1 are the radii of said circles Returns ([x1,y1],[x2,y2]) """ from math import sqrt, fabs P2 = [None,None] P3_1 = [No...
import json from datetime import datetime DEGREE_SYBMOL = u"\N{DEGREE SIGN}C" def format_temperature(temp): """Takes a temperature and returns it in string format with the degrees and celcius symbols. Args: temp: A string representing a temperature. Returns: A string contain the tempe...
import json input ='''[ {"ID":"001", "x":"2", "name":"Chuck"}, {"ID":"002", "x":"3", "name":"Break"} ]''' input type(input) info=json.loads(input) type(info) info0=info[0] info0['ID'] for item in info: print item['ID'], item['name']
list=[2,3,4,6] count=1 out=[] for num in list: data=num**count out.append(data) count+=1 print(out)
a=int(input("enter the first value=")) b=int(input("enter the second value=")) res=a+b print("result =",res)
# # i=2 # for i in range(10,50): # if(10%i==0): # i+=1 # break # else: # print (i) # for i in range(1,13): # if(i%4==0): # print(i) # else: # print(i,end="\t") # print(i,end=" ") #* #** #*** #**** #n=int(input("enter value for n")) # for row in range(0,n+1): ...
pattern="ababa" lst=list(pattern) #find the recursive character for i in lst: if i in lst[lst.index(i)+1:]: print(i) break
from tkinter import * import tkinter.messagebox from io import StringIO class Ide: #====================================Attribute=========================================================================== def __init__(self): self.root = Tk() self.root.title("Run Python Code") # set up ...
fname = input("Enter file name: ") fh = open(fname) inp = fh.read() lst = list() for line in inp: line = inp.rstrip() words = line.split() res = [] [res.append(x) for x in words if x not in res] print(sorted(res))
import math class Operacion: def __init__(self,numero): self.__numero=numero def floor(self): a=math.floor(self.__numero) return f"{a}" def ceil(self): b=math.ceil(self.__numero) return f"{b}" def raiz(self): c=math.sqrt(self.__numero) ...
from bitarray import bitarray def trim(a): "return a bitarray, with zero bits removed from beginning" try: first = a.index(1) except ValueError: return bitarray() last = len(a) - 1 while not a[last]: last -= 1 return a[first:last+1] def find_last(a, value=True): "f...
a=int(input("")) b=int(input("")) c=int(a-b) if(c<0): c=-c if(c<a): print(c+b)
import pygame, sys from random import randrange import time class Robot: def __init__(self, row, col, name): self.row = row self.col = col self.name = name self.score = 0 def increaseScore(self): self.score += 1 def printScore(self): # print(f"{self.name}...
# -*- coding: utf-8 -*- """ Created on Tue Jul 20 20:05:09 2021 @author: hoang 2 """ import random def genChars(): while True: saltAmount=int(input("Nhap kich co Salt toi thieu tu 10-32 ky tu(nhap so^'):")) if saltAmount<10: print("Yeu cau nhap gia tri lon hon 10 va nho...
primes = [] isPrime = [True]*200 isPrime[0]=False isPrime[1]=False for i in range(2,200): if isPrime[i]: for x in range(2,200/i): isPrime[x*i]=False for i in range(200): if isPrime[i]: primes.append(i) def ProductOfPrimes(n): div = {} for i in primes: if (n%i==0): div[i]=0 while (n%i==0): div[i...
# 进程和线程的区别: # 1.进程:每个程序都会有一个进程,负责管理每个程序的各个功能的执行, # 进程只会有一个,而且至少有一个(相当于包工头) # 2.线程:每个进程里面至少有一个线程,称之为 主线程,除此之外还会有其他线程,称之为分线程 # 线程是控制执行任务的最小单位(相当于农民工) # 3.进程 负责控制各个线程 的执行,当程序运行,进程启动;程序关闭,进程结束 # # 主线程和分线程: # 1.代码运行默认在主线程里面 如果需要执行新的任务,可以开辟新线程 # 2.分线程没有个数限制,分线程里面的任务结束后,分线程结束 # # 分线程的使用场景: # 1.当有大量的任务需要执行的时候,可以将任务放入到分线程里面...
#条件判断表达式 # 条件判断之if score=81 if score>=60: print('带你去海洋馆') # 条件判断之 if else salary=10000 if salary>=10000: print('哎呦,不错呦') else : print('努力吧') # 条件判断之if elif salary = 40000 # salary 薪水 if salary<=2000: print('Hello,小屌丝') elif salary<=4000: print('Hellow,小青年') elif salary<8000: print('Hellow,小帅哥') ...
# def binary_search(alist,item): # first = 0 # last = len(alist) - 1 # # while first <= last: # midpoint = (first + last)//2 # # if alist[midpoint] == item: # return True # elif item < alist[midpoint]: # last = midpoint - 1 # else: # first ...
# 异常处理: 提前将可能会引起错误的代码 # 放入到捕获异常代码块中,一旦 # 发生次错误 不会影响后续代码的执行 # try 尝试 try: list = [1, 2, 3, 4, 5, 6] print(list[100]) dic = {'name': '张三'} print(dic['age']) except KeyError as e : print('捕获了一个key值错误,请仔细检查key值') except IndexError as e : print('捕获了一个索引值错误,索引值超出范围') try: ...
class People(object): # 类属性 name ='' age ='' def __init__(self, fond=''): # 对象属性 self.fond =fond # 对象方法 self def say(self): print('Hello') print(People.name) p1 = People() p1.fond ='学习' print(p1.People) print(p1.name) print(p1.fond) # 对象属性不能通过类名+属性的方式来调用,只能通过对象来调用 ...
# def quict_sort(alist,start,end): # '''快速排序''' # # #递归的退出条件 # if start >= end: # return # # #设定一个基准元素 # mid = alist[start] # # low = start # high = end # # while low < high: # #如果low跟 high 没有重合,high指向的元素不比基准元素小,则high向左移动 # while low < high and alist[high] >=mid: ...
from random import randint user_num = input('请输入一个数字') # 0 石头 1 剪子 2 布 or或者 and 并且 # 0 1 -1 # 1 2 -1 # 2 0 2 computer_num = randint(0 , 2) print(computer_num) if user_num.isdigit(): user_num = int(user_num) if 0 <= user_num <= 2 : if user_num - computer_num == -1 or user_num - c...
# JSON # [] , () , {} list = [[],[],[]] list = [('a','A'),('b','B'),('c','C')] for x in list: print(x) for x , y in list: print(x , y) # 枚举 enumerate 可以让被遍历元素 添加一个编号(索引值) # for 后面的第一个参数 即为索引值 第二个参数 为被遍历的元素 for x , y in enumerate(list): print(x , y) for x ,( y ,z ) in enumerate(list): print(x , y ,z ) l...
class People(object): def __init__(self,name='',age='',sex='',height='',yaowei=''): self.name = name self.age = age self.sex = sex self.height = height self.yaowei = yaowei def sexIsFit(self,other): if self.sex == True and self.sex == other.sex print('...
import tkinter as tk class App: def __init__(self,root): # 创建一个框架,然后在里面添加Button按钮组件 # 框架一般使用再复杂的布局中起到将组件分组的作用 frame = tk.Frame(root) frame.pack() # 创建一个按钮组件,fg是foreground的缩写,就是设置前景色的意思 self.hi_there = tk.Button(frame,text = '打招呼',fg = 'blue',command = self.say_hi) ...
import json, requests import oauth2 as oauth import os # Customer keys & secret CONSUMER_KEY = "INSERT HERE"; CONSUMER_SECRET = "INSERT HERE"; ACCESS_KEY = "INSERT HERE"; ACCESS_SECRET = "INSERT HERE"; def main(): # prompt user for input query = input("What would you like to search for: "); lang = input("...
#Cristina Logg PSET #PART 1 ##################################################### #An API is a set of instructions for interfacing with software (getting it to talk with each other). This API is a set of instructions for getting into Twitter databases. Reading the documentation - we only have a week of tweets and rand...
class Usuario: def __init__(self, usuario, senha, id, email): self.usuario = usuario self.senha = senha self.id = id self.email = email ##Método que cria um dicionário com as informações do usuário def __dict__(self): d = dict() d['id'] = self.id ...
import numpy import cv2 def draw_box(img, box): tl = (box[0], box[1]) br = (box[0] + box[2], box[1] + box[3]) cv2.rectangle(img, tl, br, (0, 0, 255)) # cv.rectangle(img, box.tl(), box.br(), # cv::Scalar(0x00, 0x00, 0xff)) def help(): print('Call: python3 example_09-02....
# MATH BASIS FOR DETRENDING: # To detrend / flatten a 2d array, we need to understand the problem. We need to find a plane of best fit by regression. # Regression is done between the angle of rotation for each point to fit the height data the best. Thus: # X * Theta = Y must be solved. # X:= coordinate matrix (fir...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('/tmp/data',one_hot=True) #number of nodes in the layer n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 #number of outputs n_classes = 10 batch_size = 100 #input and output placeholders x = t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 10 18:36:11 2019 @author: reality """ def encode_keyword(string, cipher): #creating the cipher text key key = cipher #Notes any characters in plain text newInsertor = {} fcounter = -1; for i in string: fcounter = fco...
f = open("имя файла") #открываю файл с тройками n = sum(1 for x in open('имя файла')) #смотрю количество строк в файле. строки файла - количество наших троек def comb(): #функция, которая на выводе дает всевозможные комбинации троек a = list(map(int,f.readline().split())) #читаем строку, создаем из этого список ц...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' dict ''' d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a']) del d1['a'] print(d1) d1.clear() print(d1) print(d1.get('a'))
#Function without a param def greetings(): print('Hello World') greetings() #Function with a param def greetings(name): print('Hello {0}'.format(name)) greetings('Amit') #Function which returns a value def add(a, b): return a + b a = 2 b = 3 c = add(a, b) print('{0} + {1} = {2}'.format(a,b,c))
def convertKmToMiles(km): conversionFactor = 0.621371 miles = conversionFactor * km return miles if __name__ == "__main__": print("Welcome to km-to-mile converter program") km = float(input("Enter km? ")) miles = convertKmToMiles(km) print("{} km = {} miles".format(km, miles))
# Relative Figure Encryption cracking method # # NEED TO APPLY A FORM TO GET ALL COMBINATIONS AND # PERMUTATIONS OF ALPHABETS # Libraries import pyperclip as PC import tools.criptoTools as CT import detectarEspanol as DE import relatedFigure as RF # Get all the characters availeable SYMBOLS = """ º\ª1234567890...
# Ataque de diccionario a la cifra de sustitución simple import pyperclip, sustitucionSimple, detectarEspanol MODO = False def main(): criptograma = input('Criptograma > ') textoLlano = ataque(criptograma) if textoLlano == None: # ataque() devuelve None si no ha encontrado la clave ...
㖼̐ Ŋ֌W𐄒łH Ȃ lXgwK\[XɂƂ P̒oɎgƂcc 3n^2 - n + 3 (n - d)^2 - n + d = 6n ^2 - 2n - 6nd + 3d^2 + d =3(sqrt(2)n - d)^2 + 6sqrt(2)nd - 6 nd - 2n +d #pentagonal = [] #for i in xrange(1, 10000): # n = i * (3 * i - 1) / 2 # pentagonal.append(n) # #for i in xrange(len(pentagonal)): # for j in xrange(i + 1, len(penta...
#n is even: # 2 #n is odd: # 2 * n * a % a**2 s = 0 for a in xrange(3, 1001): n = 1 r = [] while True: div = a**2 rem = 2 * n * a % div if rem in r: s += max(r) break else: r.append(rem) n += 2 else: print s
import fractions def num(n): if n % 3 == 0: return 2 * n / 3 else: return 1 N = 100 t = fractions.Fraction(1, num(N)) for i in xrange(N, 2, -1): t = num(i - 1) + t t = 1 / t print 2 + t q = 2 + t sum([int(i) for i in str(q.numerator)])
digit = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] teens = ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] other = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] def print_below_100(number): ...
from datetime import datetime from time import mktime class Date(object): """Some time/date manipulation utilities. """ def __init__(self, datetime): self.datetime = datetime self._diff_date = None @property def diff_date(self): if not self._diff_date: the_dat...
class operation(): def __init__(self,num1,num2): self.number1= num1 self.number2=num2 def display_result(self,result): print('The result is {}'.format(result)) def add_numbers(self): sum = self.number1 + self.number2 self.display_result(sum) def sub_n...
__author__ = 'adam' size=20 def numWays(x,y): if(x==size+1 and y==size+1): return 1 if(x>size): return numWays(x,y+1) if(y>size): return numWays(x+1,y) else: return numWays(x,y+1) + numWays(x+1,y) print numWays(1,1)
__author__ = 'adam' import pandigit import primes import itertools primelist = primes.numpyPrimes(20) def isPrimeDivisible(n): for i in xrange(7): if int(n[1+i:4+i]) % primelist[i]!=0: return False return True count=0 list=[] for i in itertools.permutations('0123456789'): i=''.join...
__author__ = 'adam' import math n=0 ninefac=math.factorial(9) while (n+1)*ninefac>10**n: n+=1 print(n) factorials=[] for i in range(10): factorials.append(math.factorial(i)) def isFactorial(n): num=str(n) sum=0 for i in num: sum+=factorials[int(i)] return n==sum list=[] for i in ran...
#!/usr/bin/env python3 import os import settings import ast def read_sidebar(filename): """ Reads a text file and evaluates it as a python dict. Takes a file, reads it line by line and evaluates it so that the dictionary it holds can be initialised. """ with open(file...
from typing import List, Optional # 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 def treeNodeToString(root): if not root: return "[]" output = "" queue = [root] ...
class Solution: def spiralOrder(self, matrix: list[list[int]]) -> list[int]: ''' Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7] ''' s.show_result(matrix) bottom = len(matrix) up = 0 right = len(matrix[0]) ...
""" Declares a point in a metric space """ class Point: """ Defines a point in a metric space Parameters: ---------- coords : Iterable The point coordinates. metric : Metric The metric used to measure points proximity. """ def __init__(self, coords, met...
#Input/Output Files in Python # When you read a file, you have to close it as well # Open a file myfile = open('myfile.txt') # Read the contents of a file in one huge string contents = myfile.read() print(f"Contents of file {contents}") myfile.seek(0) # to move the cursor back to the starting position contents_again = ...
a=0 while a<100: a+=1 if a%7==0 or (a-7)%10==0 or a-70<10 and a-70>0: continue print(a)
# ============= Binary search ================ # Time: O(log(n)) # Space: O(1) # Idea: """ [__larger__|_____smaller_____] If target in the larger zone, go left. otherwise, go right. """ class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int ...
""" Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. For example, Given [[0, 30],[5, 10],[15, 20]], return 2. """ # ============= merge intervals =============== # Time: O(nlog(n)) # Space: O(n) # Idea: me...
""" Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. """ # ============== Bit =============== # Time: O(result) # Space: O(1) """ In this problem, we are asked to divide two integers. However, we are not allowed to use division, multiplication and mod ope...
""" Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. Credits: Special thanks to @ts for adding this problem ...
""" Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent. Find the number of islands. Have you met this question in a real interview? Yes Example Given graph: [ [1, 1, 0, 0, 0]...
""" There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for yo...
""" 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? Have you met this question in a real interview? Yes Example Given an example n=3 , 1+1+1=2+1=1+2=3 return 3 """ # ============= DP variables ======...
# ============ Recursive ============ # Time: O(log(n)) # Space: O(log(n)) class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 if n == 1: return x if n < 0: ...
""" Numbers keep coming, return the median of numbers at every time a new number added. Have you met this question in a real interview? Yes Clarification What's the definition of Median? - Median is the number that in the middle of a sorted array. If there are n numbers in a sorted array A, the median is A[(n - 1) / 2...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ######## Resursion with min and max ############## # Running time: 72ms # Time complexity: O(n) # Space complexity: O(n) class Solution(object): ...
""" There are two properties in the node student id and scores, to ensure that each student will have at least 5 points, find the average of 5 highest scores for each person. Have you met this question in a real interview? Yes Example Given results = [[1,91],[1,92],[2,93],[2,99],[2,98],[2,97],[1,60],[1,58],[2,100],[1,...
""" Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not alread...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # ================== Recursion ================= # Time: O(n) # Space: O(n) # Running time: ~80ms class Solution(object): def pathSum(self, root,...
""" Given a binary tree, find the subtree with minimum sum. Return the root of the subtree. Notice LintCode will print the subtree which root is your return node. It's guaranteed that there is only one subtree with minimum sum and the given binary tree is not an empty tree. Have you met this question in a real inte...
# Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None #=============== Stack ==================== # Time: hasNext: O(1) next: # Space: O(h) # Explaination: The average time complexity of next() function ...
#=========== Dict ============ # Time: O(n) # Space: O(n) class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ d = {} for n in nums: if d.has_key(n): return True else: ...
""" Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] 0 3 | | 1 --- 2 4 Output: 2 E...
""" Given a set of strings which just has lower case letters and a target string, output all the strings for each the edit distance with the target no greater than k. You have the following 3 operations permitted on a word: Insert a character Delete a character Replace a character Have you met this question in a real...
""" Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] E...
""" Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1; Besides, leading zeros in the IP...
""" Given a string, find the length of the longest substring T that contains at most k distinct characters. For example, Given s = “eceba” and k = 2, T is "ece" which its length is 3. """ # =============== Sliding window ============= # Time: O(n) # Space: O(n) class Solution(object): def lengthOfLongestSubstrin...
""" Given a nested list of integers, return the sum of all integers in the list weighted by their depth. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Have you met this question in a real interview? Yes Example Given the list [[1,1],2,[1,1]], return 10. (four 1's a...
""" Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 Show Company Tags Show Tags Show Sim...
""" Given an integer array, find a subarray where the sum of numbers is in a given interval. Your code should return the number of possible answers. (The element in the array should be positive) Have you met this question in a real interview? Yes Example Given [1,2,3,4] and interval = [1,3], return 4. The possible ans...