text
stringlengths
37
1.41M
import os import csv #Declare variables candidates = [] uniqueCandidates = [] #Open election_data.csv as long as election_data is in the same folder as this file path = os.path.join(".","election_data.csv") with open(path,'r') as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") next(csvreader) #I...
#!/usr/bin/env python import sys, re def isValidInput(string): # fix regex ... it allows (+)^number result = re.match(r'\([-]?([1-9]+[0-9]*)*([a-z](\^[1-9]+[0-9]*)?)*[+-]([1-9]+[0-9]*)*([a-z](\^[1-9]+[0-9]*)?)*\)\^[1-9]+[0-9]*', string) return result != None and result.group(0) == string def badInput(): ...
# of cars available cars = 100 # how many passengers fit in each car space_in_a_car = 4.0 #how many drivers are available drivers = 30 #how many passengers passengers = 90 # of cars that won't be used cars_not_driven = cars - drivers # of cars that will be used cars_driven = drivers # how many passengers can be driven ...
#print("How old are you?", end=' ') #age = input() #print("How tall are you?", end=' ') #height = input() #print("How much do you weigh?", end=' ') #weight = input() #print(f"So, you're {age} old, {height} tall, and {weight} heavy.") #print("Let's try something else.") #name = input('What do they call you? ') #print(f"...
def kitty(treats, catnip): print "Kitty is hungry for %s!" % treats print "Especially after having %r oz of catnip. ^^" % catnip kitty("babies", 100) tasty = "birds" oz = 50 kitty(tasty, oz) kitty(tasty + tasty, oz + 20) print "this one" kitty(kitty(tasty, oz), oz) treats = raw_input('What food do we have?') k...
import random from typing import List # simple model of reinforcement learning # an environment that will give the agent random rewards # for a limited number of steps, regardless of the agent's actions class Environment: """ providing observations and giving rewards. The environment changes its state ba...
#! /usr/bin/env python #-*- coding: utf-8 -*-import numpy import os import pandas as pd import time import numpy as np from collections import OrderedDict from datetime import datetime import string def ReverseWords(str): _len = len(str) if _len<2: return str else: i = 0 j = _len-1 ...
from person import Person, Consts class Teacher(Person): def __init__(self, name, age): super(Teacher, self).__init__(name, age) self.job = 'teacher' def get_price(self): return Consts.BASE_PRICE[self.job] - (self.age - Consts.MIN_AGE) * Consts.AGE_MUL def calc_life_cost(self): ...
from threading import Thread, Lock lock = Lock() def synchronized(f): def g(*args): lock.acquire() f(*args) lock.release() return g a = 0 @synchronized def f(): global a for i in range(3000000): a += 1 number_of_threads = 2 t = [Thread(name=i, target=f) for i in...
from film import Film from periodical import Periodical from book import Book from video import Video class SearchEngine(object): def __init__(self, books_path, periodic_path, video_path, film_path): '''Reads and parses all of the specified files and stores the objects in a list''' self.__media = l...
from string import ascii_lowercase import random def main(): with open('words.txt') as file: words = file.readline().split() print(f'Found {len(words)} words in input file') word_to_guess = random.choice(words) attempt_number = 0 max_attempts = 20 all_letters = set(ascii_lowerca...
# Python The process of python learning. import requests import os url = 'http://img0.dili360.com/rw5/ga/M00/45/C5/wKgBy1guyueAFg1vABWJTEejlTU417.tub.jpg' root = 'c:/pics/' path = root + url.split('/')[-1] def get_pic(): try: if not os.path.exists(root): os.mkdir(root) if not os.path.exi...
compras = ['tomate','queijo','suco'] print (compras [-1]) #desse modo o python vai retornar recursivamente #os valoes sortados da direita para a esquerda #o numero negativo deve estar sempre com o valor #total dos itens na lista. e o ultimo valor #sera apresentado de forma negativa
# the woodcutters house import time # define the global variables needed for this level inventory = [] no_of_cupboard_entries = 0 snake_dead = False def fig_puzzle(): # user the global inventory list global inventory # introduce the puzzle time.sleep(1) print("Before you can go in you must solve a little p...
pi=22/7 r=float(input("input the radius of the circle:")) area=pi*(r**2) print("the area of the circle with radius: "+str(r)+" is: "+str(area))
'''21 -Crie uma classe chamada Ingresso que possui um valor em reais e um método imprimeValor(). a. crie uma classe VIP, que herda Ingresso e possui um valor adicional. Crie um método que retorne o valor do ingresso VIP (com o adicional incluído). b. crie uma classe Normal, que herda Ingresso e possui um método que i...
#12 - Ler dois valores # (considere que não serão lidos valores iguais) e escrever o maior deles. num2=0 num1=0 repetido=True while repetido: num1=int(input("digite um numero a ser comparado: ")) num2=int(input("digite um numero a ser comparado e que não seja repetido: ")) if num1!=num2: repetido=F...
# 9 - faça um método que receba um número X e uma palavra no console e # repita x vezes a essa frase. num=input("digite uma palavra: ") quant=int(input("digite a quantidade de vezes que se deseja printar este numero: ")) for i in range(quant): print(num)
import torch import torch.nn as nn X = torch.tensor([[1], [2], [3], [4]], dtype=torch.float32) Y = torch.tensor([[2], [4], [6], [8]], dtype=torch.float32) X_test = torch.tensor([5], dtype=torch.float32) #Create an Xtest tensor for testing n_samples, n_features = X.shape print(n_samples, n_features) input_size ...
""" Hi, here's your problem today. This problem was recently asked by Microsoft: Given the root of a binary tree, print its level-order traversal. For example: 1 / \ 2 3 / \ 4 5 The following tree should output 1, 2, 3, 4, 5. class Node: def __init__(self, val, left=None, right=None): self.val = v...
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. Given a stack of N elements, interleave the first half of the stack with the second half reversed using only one other queue.This should be done in-place. Recall that you can only push or pop from a stack, and enqueue...
""" Hi, here's your problem today. This problem was recently asked by Facebook: Starting at index 0, for an element n at index i, you are allowed to jump at most n indexes ahead. Given a list of numbers, find the minimum number of jumps to reach the end of the list. Example: Input: [3, 2, 5, 1, 1, 9, 3, 4] Output: 2 ...
#Matthew Lee #GUI Math Quiz Test v2.2 - 07/03/2021 #IMPORTS import random from tkinter import * from tkinter import Tk #FUNCTIONS class Math(): def __init__(self, parent): self.name = "" self.age = 0 self.result = 0 """Welcome""" self.Welcome = Fr...
#################################### # Location Functions #################################### #################################### # adapted from # https://www.freecodecamp.org/forum/t/make-a-script-read-gps-geolocation/241607 #################################### import requests import math def getUserLocation(): ...
from matplotlib import colors import numpy as np from numpy.core.fromnumeric import argmax from tqdm import tqdm import pandas as pd import matplotlib.pyplot as plt class NeuralNetwork: """ Feedforward neural network / Multi-layer perceptron classifier. Uses back propagation to optimise the error function ...
from matplotlib import colors import numpy as np from numpy.core.fromnumeric import argmax from tqdm import tqdm import pandas as pd import matplotlib.pyplot as plt class NeuralNetwork: """ Feedforward neural network / Multi-layer perceptron classifier. Uses back propagation to optimise the error function ...
# 1. count() - call t his method to count specific char in string # 2. upper() - Call this method to return an upper case version of any string. # 3. lower() - Call this method to return a lower case version of any string. # 4. provide comparision example using a .lower() method # 5. islower() - call this method to c...
import time import calendar # 时间戳 print(time.time()) # 获取当前时间 localtime = time.localtime(time.time()) print("本地时间为 :", localtime) # 格式化时间 localtime = time.asctime(time.localtime(time.time())) print("本地时间为 :", localtime) # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成S...
# -*- coding: UTF-8 -*- import time import calendar ticks = time.time() print(ticks) print(time.localtime(time.time())) localtime = time.asctime(time.localtime(time.time())) print("本地时间为 :", localtime) # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24...
"""Unit tests for the TravelPoint class. A TravelPoint stores information about a given location that is part of a journey. The attributes include name, departure_time and arrival_time. """ import unittest # Standard unittest framework. import location # The module implementing the TravelPoint class. class Tes...
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def eat(self): pass class Mammal(Animal): def eat(self): print("nom nom") # @abstractmethod decorator is used so any subclass created must have its own implementation.
class Student(): class_="student" def __init__(self,name,age,mark1,mark2,mark3): self.name = name self.age = age self.mark1 = mark1 self.mark2 = mark2 self.mark3 = mark3 def calcAverage(self): return int(self.mark1 + self.mark2 + self.mark3)/3 Artas = Studen...
math = int(input("What is your Maths mark?: ")) phys = int(input("What is your physics mark?: ")) chem = int(input("What is your chemistry mark?: ")) avg = (math + phys + chem) // 3 if avg > 70: print("A") elif avg > 60: print("B") elif avg > 50: print("C") elif avg > 40: print("D") else: print("F...
# Глава 2. Сортировка выбором def find_smallest(arr): smallest = arr[0] smallest_index = 0 for i in range (1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selection_sort(arr): newArr = [] for i in range(len(arr)): smallest = find_smallest(arr) newArr...
#coding=utf8 import random import math #Функция ввода массива случайных натуральных чисел #(для удобства тестирования) def randArr(length): numbers = [] for i in range(length): numbers.append(random.randint(0,100)) return numbers #Функция ввода массива натуральных чисел пользователем def arrImput(): print("Вве...
import pandas as pd import numpy as np from scipy.io import loadmat import matplotlib.pyplot as plot import scipy.optimize as opt from sklearn.metrics import classification_report ''' Training a neural network 1.Randomly initialize weights 2.Implement forward propagation to get h(x(i)) for any x(i) 3.I...
from agents import * # DEFINCION DEL AGENTE class Aspiradora(Agent): location = random.randint(0,1) print("las aspiradora inicia en location {}".format(location)) def moveright(self): self.location += 1 def moveleft(self): self.location -= 1 def suck(self, thing): '''ret...
# 2. Написать программу сложения и умножения двух шестнадцатеричных чисел. # При этом каждое число представляется как массив, элементы которого — цифры # числа. Например, пользователь ввёл A2 и C4F. Нужно сохранить их как # [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно. # Сумма чисел из примера: [‘C’, ‘F’, ‘1’], # произв...
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. import random SIZE = 20 MIN_ITEM = 0 MAX_ITEM = 50 array = [random.randint(MIN_ITEM, MAX_ITEM) for i in range(SIZE)] min_el = MAX_ITEM max_el = MIN_ITEM min_index = 0 max_index = 0 for i in range(len(array)): if array[i] < ...
'''Demo Program - Use Dynamic programming for O(n) solution in Fibo Calculation''' ''' n -> number to calculate fibonacci for ''' def fibo(n): arr=[0]*(n+1) if n == 1 or n == 0: return 1 arr[1]=1 arr[2]=1 for i in range(3,n+1): arr[i]=arr[i-1]+arr[i-2] return arr[n] '''Drive...
class Stack: def __init__(self): self.__stackList = [] def getlist(self): return self.__stackList def push(self, val): self.__stackList.append(val) return self.__stackList def pop(self): val = self.__stackList[-1] del self.__stackList[-1] return va...
"""Finds the bounding box for D in x and y (The space in D with material)""" import numpy as np def boundingbox(D): D_box = np.nonzero(np.sum(D,axis=0)) D_ybox = np.nonzero(np.sum(D, axis=1)) """ Below example could make it more readable? """ # Creates a region of interest as a slice tuple - easy to...
""" X-ray simulator. Simulates the 2D image generated with x-rays emitted from a point source and penerating a material represented by an 3D array. Generally the coordinate system is right-handed with center in x-ray point source. hat{z} points toward the camera(CCD object) hat{x} (positive right) and hat{y}(inwards...
# PA1: FoxProblem # Jack Keane class FoxProblem: def __init__(self, start_state=(3, 3, 1)): self.start_state = start_state self.goal_state = (0, 0, 0) self.traverses = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] def is_safe(self, state): # determine animals on each bank we...
# 2.1.3 # # Tri de trois réels # # Ecrire un programme faisant saisir trois nombres réels x, y, z à l’utilisateur et qui les trie par ordre croissant # (à la fin du déroulement du programme x ≤ y ≤ z). x = eval(input("Entrez le premier nombre : ")) y = eval(input("Entrez le second nombre : ")) z = eval(input("Entrez l...
# 2.1.5 # # Somme des premiers carrés # # Ecrire un programme calculant la somme des n premiers carrés d’entiers, où n est un entier naturel # saisi par l’utilisateur. n = None while type(n) is not int: n = eval(input("Entrez un entier : ")) somme = 0 for i in range(n+1): somme += i**2 print("La somme des"...
# 2.5.1 # # Nombre d’occurrence d’un élément dans une liste # # Ecrire une fonction calculant le nombre d’occurrences d’un élément dans une liste. def compteOccurrence(l, x): compte = 0 for i in l: if l[i] == x: compte += 1 return compte maListe = [1, 2, 3, 4, 5, 3] print(compteOccu...
# 2.3.2 # # Suite de Syracuse # # Ecrire une procédure affichant les n premiers termes de la suite de Syracuse de base a. def syracuse(n, a): if type(a) is not int or a < 0: print("Erreur : a doit être un entier positif.") return -1 print(a, end=" ") precedent = a for i in range(1, ...
def what_i_want(thing1, thing2): print "I want %s" % thing1 print "I want %s" % thing2 print "That's just awesome!" print "Yay!\n" what_i_want("waffles", "beer") waffles = "waffles" beer = "beer" what_i_want(waffles, beer) what_i_want("waffles" + " beer", "waffles " + beer)
def arrayPrint(A): for i in xrange( len( A) ): print A[i] , print '' def less(a,b): return a < b def greater(a,b): return a > b def insertionSort(A, func = less): """ Insertion sort: - Simple implementation - Efficient for (quite) small data sets - Adaptive (...
def decorator(validate): def result(func): def check_validate(*args, **kwargs): if not validate(*args, **kwargs): return 'error' return func(*args, **kwargs) return check_validate return result def validator(*args, **kwargs): return True pass @dec...
text = input() stack = [] for i in range(0,len(text)): stack.append(text[i]) if text[i] == "=": stack.pop() if stack: stack.pop() pass print("".join(stack))
n = int(input()) for i in range(n): text = input() print(text.title()) pass """ for i in range(int(input())): print(" ".join([s.capitalize() for s in input().split()])) """
st = {2, 3, 1} print(st) a = set("salam") b = set("ali") print(a | b) print(a & b) print(a - b) print(a ^ b) # ( A - B) U ( A - B ) print({x for x in a if x not in b}) dict = {"ali": 12, "amir": 2.3} print(dict['ali']) print(list(dict)) print({2*x:x/4 for x in range(5)}) d = {'ali': 'A', 'amir': 'B'} for k, v in d.it...
"""from datetime import time t = time(17, 21, 20, 2021) print(t , "# ", type(t)) """ """ from datetime import date d = date(2019, 5, 23) print(d.year, d.month, d.day) """ from datetime import datetime dt = datetime(1, 2, 3, 4, 5, 6, 7) print(dt.year, dt.month, dt.day, dt.minute ) print() print(datetime.now())
import csv import globals as g import F03 as c def Exit(): if (not(g.Login_success)): print("Silahkan login terlebih dahulu untuk menggunakan fitur ini.") return; pilih = str(input("Apakah Anda mau melakukan penyimpanan file yang sudah dilakukan (Y/N)? ")) #apabila masukan bukan 'Y',...
from time import strftime from tkinter import Label, Tk # ======= Configuração da janela ========= window = Tk() # ======= Cria a janela grafica ========= window.title("Relógio") # ====== Titulo da janela ========= window.geometry("300x100") #======= Proporção da tela ========= window.configure(bg="Black") # =...
# print(1) # print(2) # print(3) # print(4) #print(5) # range(start, end, difference) #range(0, 5, 1) """ for i in range(0, 20, 2): print(i) """ """ #if first and difference value is not set then default irst value is 0 and difference is 1 for j in range(10): print(j) """ """ # print all ood and even...
# lambda arguments:code expression result = lambda x, y: x +y print(result(60, 50)) result2 = lambda x, y: (x +y)*2 print(result2(60, 50)) result3 = lambda x, y: x if x%2 == 0 else y print(result3(21, 30)) # Map : def square(n): return n**2 list1 = [5, 7, 3, 8, 9] output = list(map(square, list1)) print(ou...
""" When one operator perform multiple task then this is called operator overloading like + , * etc and behind the scene + operator is overloaded by "__add__" method. and * operator is overloaded by "__mul__" method. """ num1 = 50 num2 = 60 print(num1+num2) print(int.__add__(num1, num2)) print(str.__add__('Hello', ...
""" *** * * * * * * * * * * *** * ** *** **** *** ** * """ #1. write a print * at 2,3,4 and space at 1st and 5th position. #2. write code to print * at 1st and 5th position and space at 2,3,4 position # repeat same pattern 5 times """ for i in range(1, 6): if i ==2 or i == 3 or i == 4: ...
#1.take user salary and year of experience from user. #-> if exp > 1 year : 10% increament in salary #-> if emp < 1 year : 5% increment in salary # salary = float(input("Please enter emp salary :")) # exp = float(input("Please enter emp experiance :")) # # if exp > 2: # new_salary = salary + salary*10/100 # pr...
""" 1. Class : class is blue print of the object which contains all properties and attribute of the object. 2. Object : object is instance of the class through which we can access class properties. 3. Inheritance 4. Polymorphism 5. Data Hiding and Abstraction """ class Car: # object method/instance method def...
s = input() s = set(list(s)) ans = 'None' for alpha in list('abcdefghijklmnopqrstuvwxyz'): if alpha not in s: ans = alpha break print(ans)
# -*- coding: utf-8 -*- def solve(n): return sum(len(num2char(i)) for i in range(1, n+1)) def num2char(n): num_char_dic = { '0': '', '00': '', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': ...
# -*- coding: utf-8 -*- def is_palindrome(n): n_str = str(n) return n_str == n_str[::-1] def solve(): return max( i*j for i in range(999, 0, -1) for j in range(999, 0, -1) if is_palindrome(i*j) ) if __name__ == '__main__': print(solve())
# -*- coding: utf-8 -*- S, T, U = map(len, input().split()) if S == U and S == 5 and T == 7: print("valid") else: print("invalid")
s = list(input()) ss = sorted(s) sd = list('yahoo') ssd = sorted(sd) if ss == ssd: print('YES') else: print('NO')
# -*- coding: utf-8 -*- def solve(n): # list comprehension return sum(a_n for a_n in fibnacci(n) if a_n % 2 == 0) def fibnacci(n): a = [1, 2] while 1: a_n = a[-1] + a[-2] if a_n > n: return a a.append(a_n) if __name__ == '__main__': print(solve(4000000))
a, b = 1, 0 for k in range(int(input()) + 1): a, b = b, a + b print("%s %s" % (a, b))
# -*- coding: utf-8 -*- i = int(raw_input()) count = 0 for j in xrange(i): for k in str(j+1): if k == "1": count += 1 print count
# -*- coding: utf-8 -*- Y = int(raw_input()) if Y % 4 == 0: if Y % 100 == 0: if Y % 400 == 0: print "YES" else: print "NO" else: print "YES" else: print "NO"
nome = input("Qual seu nome?") idade = int(input("Qual sua idade?")) # cem_anos = 100 - idade # cem_anos = 2019 + cem_anos repetir_mensagem = int(input("Quantas vezes quer ver esta mensagem ?")) cem_anos = str((2019 - idade)+100) print(("Seu nome é {} e sua idade atual é {}. O ano em que vai fazer 100 anos é {}\n".form...
# import random # # aluno1 = input('Digite o nome do primeiro aluno:') # aluno2 = input('Digite o nome do segundo aluno:') # aluno3 = input('Digite o nome do terceiro aluno:') # aluno4 = input('Digite o nome do quarto aluno:') # # print('Os alunos são \n1- {} \n2- {} \n3- {} \n4- {}'.format(aluno1, aluno2, aluno3, alun...
salario = float(input('Digite o salário do funcionário: ')) aumento = (salario*15)/100 nsalario = salario + aumento print('O novo salário do Fulano é de {}'.format(nsalario))
import random def busqueda_binaria(lista, comienzo, final, objetivo): print(f' buscando {objetivo} entre {lista[comienzo]} y {lista[final -1]}') if comienzo > final: return False medio = (comienzo + final) // 2 if lista[medio]== objetivo: return True elif lista[medio] < objeti...
x = 3 if x>0: x = x-4 elif x<0: x = x+5 else: x = x+10 print(x)
# Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами # 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка # элементов необходимо использовать функцию input(). string = input("Введи элементы списка ...
# Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. # расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия. # Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. from sys import argv script, ...
print('Lottery nimbers') numbers = [] import random def main () : for x in range(9): numbers.append(random.randint(0, 9)) print(numbers) #Задания для написания кода. # 1. Общий объем продаж.Разработайте программу, которая просит пользователя ввести # продажи магазина за каждый день недели. Суммы должны бы...
# Константа NUМ_DAYS содержит количество дней, # за которые мы соберем данные продаж. NUМ_DAYS = 5 def main(): sales = [0] * NUМ_DAYS # Создать переменную, которая будет содержать индекс. index = 0 print("Введите продажи за каждый день: ") while index < NUМ_DAYS: print('День № ', index ...
#python program to map two list into a dictionary print("enter 2 list of equal length to map into dictionary") a=eval(input("enter a list1 : ")) b=eval(input("enter a list2 : ")) c={} for i in range(len(a)): c[a[i]]=b[i] print(c)
#!/usr/local/bin/python # -*- coding: UTF-8 -*- def name_to_class(key): """ Converts a note name to its pitch-class value. :type key: str """ name2class = {'B#': 0, 'C': 0, 'C#': 1, 'Db': 1, 'D': 2, 'D#': 3, 'Eb': 3, 'E': 4,...
import random import itertools from bisect import bisect def choices(population, weights=None, *, cum_weights=None, k=1): """Copy of source code for random.choices added to random module in 3.6 Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative wei...
""" Author: Mark Arakaki Date: November 24, 2017 Personal Practice Use Create a program that takes in a list from user input and prints out the first and last element from that list. """ def listEnds(list): print "The first element in the list is %s." % list[0] print "The last element in the list is %s." % li...
import sqlite3 conn = sqlite3.connect('test_data.db') c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS events (event_ID INTEGER PRIMARY KEY AUTOINCREMENT, event_name TEXT, event_start_date REAL, event_end_date REAL, event_venue TEXT)") c.execute("CREATE TABLE IF NOT EXISTS tickets (ticket_ID INTEGER PRIMARY KE...
# Counts the occurence of words in a sentence def words(sentence): count_dict = {} for word in sentence.split(): # if key is a integer if word.isdigit(): count_dict.setdefault(int(word),0) count_dict[int(word)] += 1 # otherwise treated as a string else: count_dict.setdefault(word,0) count_dict[wor...
# Window Sum # Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, # find the sum of the element inside the window at each moving. # # Example # For array [1,2,7,8,5], moving window size k = 3. # 1 + 2 + 7 = 10 # 2 + 7 + 8 = 17 # 7 + 8 + 5 = 20 # retu...
""" Given an integer array, find the top k largest numbers in it. Example Example1 Input: [3, 10, 1000, -99, 4, 100] and k = 3 Output: [1000, 100, 10] Example2 Input: [8, 7, 6, 5, 4, 3, 2, 1] and k = 5 Output: [8, 7, 6, 5, 4] """ class Solution: """ @param nums: an integer array @param k: An integer ...
""" Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top. Example Given nums = [1, 2, 4, 8, 6, 3] return 8 Given nums = [10, 9, 8, 7], return 10 """ """ 思路过程: increase first, then decrease =>问题是:既然是山并且基于example, 也就是有 可能这个山只有increase array or decrease array? =>觉得是 =>f...
""" Given a list of words and an integer k, return the top k frequent words in the list. Example Example 1: Input: [ "yes", "lint", "code", "yes", "code", "baby", "you", "baby", "chrome", "safari", "lint", "code", "body", "lint", "code" ] k = 3 Output: ["code", "lint", "baby"] Example 2: In...
"""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 from left to right. The first integer of each row is greater than the last integer of the previous row. Example Consider the following matrix: [ [1, 3, 5, 7], ...
# Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. # Example: # # Input: "babad" # # Output: "bab" # # Note: "aba" is also a valid answer. # # # # Example: # # Input: "cbbd" # # Output: "bb" #Solutions Summary: # Solution 1/1.1: 中心点枚举法 # Solution 2: Ma...
# Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). # # Example 1: # Input: [3, 2, 1] # # Output: 1 # # Explanation: The third maximum is 1. # Example 2: # Input: [1, 2] # # Output: 2 # # Explanation:...
# The Hamming distance between two integers is the number of positions at which the corresponding bits are different. # # Given two integers x and y, calculate the Hamming distance. # # Note: # 0 ≤ x, y < 231. # # Example: # # Input: x = 1, y = 4 # # Output: 2 # # Explanation: # 1 (0 0 0 1) # 4 (0 1 0 0) # ↑...
""" Find top k frequent words in realtime data stream. Implement three methods for Topk Class: TopK(k). The constructor. add(word). Add a new word. topk(). Get the current top k frequent words. Example TopK(2) add("lint") add("code") add("code") topk() >> ["code", "lint"] Notice If two words have the same frequency, ...
"""Corner Cases: better ask interviewer to confirm return value for corner cases""" if list is None or len(list) == 0 or k == 0: return [] """find closest element from target first in list: 利用helper function call binary search first to get closest index make that closet element a centered value and set two...
""" Remove adjacent, repeated characters in a given string, leaving only one character for each group of such characters. Assumptions Try to do it in place. Examples “aaaabbbc” is transferred to “abc” Corner Cases If the given string is null, returning null or an empty string are both valid. """ class Solution(obj...
""" Given inorder and postorder traversal of a tree, construct the binary tree. Example Example 1: Input: [1,2] [2,1] Output: {1,#,2} Explanation: 1 \ 2 Example 2: Input: [1,2,3] [1,3,2] Output: {2,1,3} Explanation: 2 / \ 1 3 Notice You may assume that duplicates do not exist in the tree. ""...
""" Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example Example 1: Input: tree = {1,2,3} Output: true Explanation: This is a balanced binary ...