text stringlengths 5 121k |
|---|
class FootballTeamIterator:
def __init__(self, members):
self.members = members
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.members):
val = self.members[self.index]
... |
import pandas as pd
import numpy as np
import os.path, time
from urllib.request import urlretrieve
import datetime as dt
import matplotlib.pyplot as plt
def moving_Avg(stock_file):
try:
number = int(input("Please enter Moving Average days: "))
if number <= 200:
stock_file[... |
"""These are arrows for control flow of input"""
from reverseflow.arrows.primitivearrow import PrimitiveArrow
class DuplArrow(PrimitiveArrow):
"""
Duplicate input
f(x) = (x, x, ..., x)
"""
def __init__(self, n_duplications=2) -> None:
self.in_ports = [InPort(self, 0)]
self.out_po... |
from collections import defaultdict
import heapq
input_file=open("Input.txt","r")
slot_regid={}
reg_no={}
slot_age={}
ageList=defaultdict(list)
slot_cnt=0
available_slots=[]
def CreateParkingLot(size):
try:
n=int(size)
print("Created parking of",n,"slots")
except:
print("Invalid input,Size of parking ... |
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo = False)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship... |
import os
import webapp2
form_html = """
<form >
<body style='background-color:rgb(0,234,200)' >
<h2 style='color:rgb(234,13,156)'> Add a food </h2>
<input type = "text" name="food" ><br><br>
%s
<button> Add food </button>
</body>
</form>
"""
hidden_html = """
<input type ="hidden" name="food" value... |
import feedparser
from datetime import datetime
from time import mktime
from disease_list import disease_list_all, disease_list_small
days=2
def disease_monitor(days):
try:
if 0 < days <= 30:
for disease in disease_list_small:
feed_string = f'https... |
points = {
(0, 1): 2,
(0, 2): 3.8,
(0, 3): 2.7,
(1, 2): 2.5,
(1, 3): 4.1,
(2, 3): 3.9,
}
def calculate_distance(coordinates):
distance = 0
if len(coordinates) <=1:
return 0
else:
for i in range(len(coordinates)-1):
couple = (coordinates[i],coordinates[i+... |
import collections
person1 = ('Bob', 'Dou', 25)
Person = collections.namedtuple('Person', ['name', 'surname', 'age'])
person = Person('Jack', 'Watson', 55)
print(person1[0])
print(person.age)
print(person)
print(person1) |
squares = []
for i in range(11):
squares.append(i ** 2)
print(squares)
squares_new = [i **2 for i in range(11)]
print(squares_new)
def func(x):
return x * 2
dubbled = [func(i) for i in range(11)]
print(dubbled)
dubbled_set = {func(i) for i in range(11)}
print(dubbled_set)
dubbled_dict = {i: func(i) for... |
import random
from datetime import datetime, timedelta
def main():
starting_date = input('Enter starting date: ')
end_date = input('Enter ending date: ')
starting_date = datetime.strptime(starting_date, "%Y-%m-%d")
end_date = datetime.strptime(end_date, "%Y-%m-%d")
inerval_days = (end_date - star... |
def all_sub_lists (data):
sub_lists = [[]]
for i in range(len(data)+1):
for j in range(i+1,len(data)+1):
sub_lists.append(data[i:j])
return sorted(sub_lists, key=len)
print(all_sub_lists([4,6,1,3])) |
number = 0
while True:
if number % 2:
print(f"{number} is odd")
else:
print(f"{number} is even")
if number > 20:
break
number = number + 1
|
print("We are trying to solve linear equation 'ax + b = c'")
a = 3
b = 2
c = 1
print(f"a = {a}, b = {b}, c = {c}")
x = (c - b)/a
print(f"x = {x}")
print("We are trying to find hypotenuse")
a = int(input('Enter "a" value: '))
b = int(input('Enter "b" value: '))
print(f"a = {a}, b = {b}, c = {c}")
c = (a ** 2 + b ** 2... |
import os
import csv
from collections import namedtuple, Counter
from typing import List
data = []
Record = namedtuple('Record', ['Review', 'Brand', 'Variety_Style', 'Country', 'Stars', 'Top_Ten'])
def init():
base_file = os.path.dirname(__file__)
filename = os.path.join(base_file, 'data', 'ramen_ratings.csv... |
from bs4 import BeautifulSoup
import requests
def get_bus_times(stop_id):
url = "http://www.mybustracker.co.uk/?module=mobile&mode=1&busStopCode=" + stop_id + "&subBusStop=Display+Departures"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "html.parser")
stop_data = soup.find_all("tr", at... |
import numpy as np
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy ar... |
from ..fighter import Fighter
class Dragon(Fighter):
"""A Dragon occupies a place and does work for the colony."""
is_dragon = True
implemented = False
food_cost = 0
blocks_path=True
is_container=False
def __init__(self, armor=1):
"""Create a Dragon with a ARMOR quantity."... |
class Place(object):
"""A Place holds fighters and has an exit to another Place."""
def __init__(self, name, exit=None):
"""Create a Place with the given NAME and EXIT.
name -- A string; the name of this Place.
exit -- The Place reached by exiting this Place (may be None).
"""
... |
import json
import Product
jsonFile = open("./machine.json")
machine = json.load(jsonFile)
print("Let's Build a PC that fits your budget. What setup type would you like? We offer the Budget Gamer, the Mid Ranger, the Power Budget, and the All Out Power.")
products = []
for machineCounter in range(len(machine)):
... |
bill_thickness = 0.11 * 0.001
sears_height = 442
num_bills = 1
day = 1
while num_bills * bill_thickness < sears_height:
print(day, num_bills, num_bills * bill_thickness)
day = days + 1
num_bills = num_bills * 2
print('Number of days', day)
print('Number of bills', num... |
class Solution:
def Power(self, base, exponent):
result = base
if exponent == 0:
return 1
elif exponent > 0:
for i in range(exponent-1):
result *= base
return result
else:
for i in range(-exponent-1):
... |
class Solution:
def PrintMinNumber(self, numbers):
if not numbers:
return ""
lmb = lambda n1, n2:int(str(n1)+str(n2))-int(str(n2)+str(n1))
array = sorted(numbers, cmp=lmb)
return ''.join([str(i) for i in array])
print(Soluti... |
"""This script holds the definition of the Hand class"""
import deck
class Hand:
def __init__(self):
self.cards = []
self.hand_value = 0
self.num_aces = 0
def __len__(self):
return len(self.cards)
def add_card(self, new_card):
self.cards.append(new_card)
... |
import unittest
from bank import BankAccount
class AccountBalanceTestCases(unittest.TestCase):
def setUp(self):
self.account_yangu = BankAccount()
def test_balance(self):
self.assertEqual(self.account_yangu.balance, 3000, msg= 'Account balance Invalid')
def test_deposit(self):
sel... |
number_of_message = int(input("How many message do you want to send? "))
import pyautogui
import time
message = 0
while message < number_of_message:
time.sleep(2)
pyautogui.typewrite('hello we make song and programming projects. Now i made a project called automatic messenger')
pyautogui.press('enter')
... |
primes = []
for possiblePrime in range(2, 100):
isPrime = True
for num in range(2, possiblePrime):
if possiblePrime % num == 0:
isPrime = False
if isPrime:
primes.append(possiblePrime)
print(primes)
for num in range(1, 100):
if num in primes:
prin... |
inp1 = int(input())
inp2 = input()
out1 = inp1 * int(inp2[2])
out2 = inp1 * int(inp2[1])
out3 = inp1 * int(inp2[0])
result = inp1 * int(inp2)
print(out1, out2, out3, result, sep='\n')
|
nums = []
for i in range(10):
temp = int(input())
nums.append(temp%42)
num_list = set(nums)
print(len(num_list))
|
inp1 = int(input())
inp2 = int(input())
out1 = inp1*((inp2%100)%10)
out2 = inp1*((inp2%100)//10)
out3 = inp1*(inp2//100)
result = inp1*inp2
print(out1, out2, out3, result, sep='\n')
|
print('zad 1')
x = 1
fib = [1,1]
for i in range(2,40):
fib.append(fib[i-2] + fib[i-1])
print('F10',fib[9])
print('F20',fib[19])
print('F30',fib[29])
print('F40',fib[39])
print('zad 2')
def isPrime(x):
i = 2
if x >= 2:
while i < x:
if x%i == 0:
return False
... |
"""Infix to Postfix Converter
https://www.codewars.com/kata/infix-to-postfix-converter/train/python
https://www.codewars.com/kata/52e864d1ffb6ac25db00017f
Construct a function that, when given a string containing an expression in infix notation,
will return an identical expression in postfix notation.
The op... |
"""
This module contains all the models
required by the application.
"""
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, func
from sqlalchemy.orm import backref, relationship
from .database import Base
class Player(Base):
"""
Class to create a table for storing
a player's person... |
x=4545
print(x)
x_str=str(x)
print("my fav num is", x, ".", "x=", x)
print("my fav num is " + x_str +"."+"x="+x_str)
|
lista_de_compras = []
preguntar_de_vuelta = True
while preguntar_de_vuelta:
item = input("Ingrese producto: ")
lista_de_compras.append(item)
continuar = int(input("Desea agregar otro item?: (0: No/1: Si)"))
if continuar == 1:
continue
else:
preguntar_de_vuelta = False
break
print("Sele... |
f = reversed(list("stressed"))
a = ''.join(f)
print(a)
|
import pandas as pd
df = pd.read_csv('data/pokemon_data.csv')
print (df.count())
|
def check(num):
return True if (num<0) else False
print(check(-2))
lst = [4,-5,4, -3, 23, -254]
def neg(lst):
return [num for num in lst if num <0]
print(neg(lst)) |
def InorderTraveral(tree,i,N):
if i<=N:
InorderTraveral(tree,i*2,N)
print(tree[i],end="")
InorderTraveral(tree,i*2+1,N)
for t in range(1,11):
N = int(input())
tree = [0 for _ in range(N+1)]
for _ in range(N):
inputValue = input().split(" ")
node, item = inputValu... |
'''
https://jurogrammer.tistory.com/6
'''
memo = {1:1,2:1,3:1}
def Wave(n):
if n in memo:
return memo[n]
else:
memo[n] = Wave(n-2)+Wave(n-3)
return memo[n]
n = int(input())
for _ in range(n):
req = int(input())
print(Wave(req)) |
def BubbleSort(input_list):
for i in range(len(input_list)-1,-1,-1):
for j in range(0,i):
if input_list[j]>input_list[j+1]:
temp = input_list[j]
input_list[j] = input_list[j+1]
input_list[j+1] = temp
return input_list
n_test = int(input... |
'''
A "dunder" variable. Special properties represented by __name__ variable.
When run, every Python file/module has its own __name__ variable. If the file is
the main file being run, its value is "__main__". Otherwise, its value is the file name.
***check out say_hi.py and say_sup.py for example***
Basically, the _... |
from random import shuffle
class Card:
available_suits = ("Hearts", "Diamonds", "Clubs", "Spades")
available_values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
def __init__(self, suit, value):
if suit not in Card.available_suits:
raise ValueError
... |
def get_unlimited_multiples(number=1):
next_num = number
while True:
yield next_num
next_num += number
fours = get_unlimited_multiples(4)
print(next(fours))
print(next(fours))
print(next(fours))
print(next(fours)) |
"""
Typical syntax:
def my_decorator(fn):
def wrapper(*args, **kwargs):
# do stuff with fn(*args, **kwargs)
pass
return wrapper
Another tutorial example: https://www.youtube.com/watch?v=swU3c34d2NQ
from functools import wraps
import logging
logging.basicConfig(filename='example.log', level=lo... |
'''
Python Debugger (pdb) -- To set breakpoints in our code we can use pdb by inserting this line:
def function(params):
import pdb; pdb.set_trace() - Usually added/imported like this inside a function
*Rest of code*
Usually placed right before something starts breaking. Allows you to see a preview of what h... |
'''
Here's what happens you import something:
1. Tries to find the module (if it doesn't find it, it throws an error).
2. But if found, it runs the code inside of the module being imported
So, in the example with say_hi and say_sup, when you import say_sup into the say_hi file,
it will run the code in the say_sup modu... |
'''
sorted - Returns a new sorted LIST from the items in iterable (tuple, list, dict, str, etc.)
You can also pass it a reverse=True argument.
Key difference between sorted and .sort() is that .sort() is a list-only method and returns the
sorted list in-place. sorted() accepts any type of iterable. Good for sorted on ... |
'''
Write a function interleave() that accepts two strings. It should return a new string containing
the two strings interwoven or zipped together. For example:
interleave('hi', 'ha') # 'hhia'
interleave('aaa', 'zzz') # 'azazaz'
interleave('lzr', 'iad') # 'lizard'
'''
def interleave(str1, str2):
return ''.jo... |
'''
all - Return True if all elements of the iterable are truthy (or if the iterable is empty)
'''
all([0, 1, 2, 3,])
all([char for char in 'eio' if char in 'aeiou'])
all([num for num in [4, 2, -1, 10, 6, 8] if num % 2 == 0])
people = ['Charlie', 'Casey', 'Cody', 'Carly', 'Cristina']
print(all(name for name ... |
'''
POLYMORPHISM - A key principle in OOP is the idea of polymorphism - an object can take
on many (poly) forms (morph). Here are two important practical applications:
1. Polymorphism & Inheritance - The same class method works in a similar way for different classes
Cat.speak() # meow
Dog.speak() # woof
Human.speak(... |
from random import randint
start_game = True
while start_game:
player_wins = 0
computer_wins = 0
winning_score = 2
while player_wins < winning_score and computer_wins < winning_score:
print(f'Player: {player_wins} Computer: {computer_wins}')
p... |
'''
In Python, it is STRONGLY encouraged to use try/except blocks to catch exceptions
when we can do something about them. Let's see what that looks like.
Most basic form:
try:
foobar
except NameError as err:
print(err)
'''
'''
WHEN TO USE TRY/EXCEPT VS. RAISE:
You would want to use try-except when you wan... |
'''
ITERATOR - An object that can be iterated upon. An object which returns data,
ONE element at a time when next() is called on it. Think of it as anything we can
run a for loop on, but behind the scenes there's a method called next() working.
ITERABLE - An object which will return an ITERATOR when iter() is called... |
import time
gen_start_time = time.time()
print(sum(n for n in range(100000000)))
gen_time = time.time() - gen_start_time
list_start_time = time.time()
print(sum([n for n in range(100000000)]))
list_time = time.time() - list_start_time
print(f"Gen took: {gen_time}")
print(f"List took: {list_time... |
class Person:
def __init__(self):
self._secret = 'hi!'
self.name = 'Tony'
self.__msg = "I like turtles"
self.__lol = "hahahaha"
p = Person()
print(p.name)
print(p._secret)
print(dir(p))
print(p._Person__msg)
print(p._Person__lol) |
filename = input("Filename?")
txt = open(filename, 'w')
line4 = input("Line4: ")
print(f"Here's your file {filename}")
txt.write(line4)
txt.write("\n")
txt.close()
|
'''
Problem Statement: Christy is interning at HackerRank. One day she has to distribute some chocolates to her colleagues.
She is biased towards her friends and plans to give them more than the others. One of the program managers hears of this and tells her
to make sure everyone gets the same number. To ... |
numbers = [1, 6, 8, 1, 2, 1, 5, 6]
def TimeNumber(n):
count = 0
for i in range(len(numbers)):
if numbers[i] == n:
count += 1
return count
number = int(input("program to count number occurrences in a list \n enter a number? "))
print("{0} appears {1} times in my list".format(number, Time... |
def rabbit(month):
if month == 0:
return 1
if month == 1:
return 2
else:
return rabbit(month - 1) + rabbit(month - 2)
for i in range(5):
print("month {0}: {1} pairs of rabbit".format(i, rabbit(i)))
|
n = int(input("enter: "))
count = 1
while True:
if (n//10) != 0:
count +=1
n //=10
else:
break
print(count)
|
numbers = [1, 6, 8, 1, 2, 1, 5, 6]
number = int(input("program to count number occurrences in a list \n enter a number? "))
print("{0} appears {1} times in my list".format(number, numbers.count(number)))
|
def convert_cat2num(df):
num_encode = {'col_1' : {'YES':1, 'NO':0},
'col_2' : {'WON':1, 'LOSE':0, 'DRAW':0}}
df.replace(num_encode, inplace=True) |
import itertools
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 10, natuals)
for n in ns:
print(n)
np = itertools.repeat("A", 10)
for p in np:
print(p)
for c in itertools.chain('ABC', 'XYZ'):
print(c)
for key, group in itertools.groupby('AaaBBbccCAAaA', lambda c:c.upper()):
... |
"""
Do-from-scratch Exercises: Files section
The 4 different tasks are outlined in blocks of code.
"""
name = input("Please enter name: ")
out_file_name = open("name.txt", "w")
print(name, file=out_file_name)
out_file_name.close()
in_file_name = open("name.txt", "r")
print("Your name is {}".format(in_file_name.read... |
"""
Programs to display different kinds of lists (numerical and other).
"""
for i in range(1, 21, 2):
print(i, end=' ')
print()
for i in range(0, 101, 10):
print(i, end=' ')
print()
for i in range(1, 21):
j = 21 - i
print(j, end=' ')
print()
number_of_stars = int(input("Number of stars: "))
for ... |
"""
CP1404/CP5632 - Practical
Password checker code
"""
MIN_LENGTH = 2
MAX_LENGTH = 6
SPECIAL_CHARS_REQUIRED = False
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\"
def main():
"""Program to get and check a user's password."""
print("Please enter a valid password")
print("Your password must be betw... |
"""
Program to store information on all of the user's guitars.
"""
from prac_06.guitar import Guitar
def main():
"""
User continually prompted to input guitar make and model name, year of manufacturing, and cost until a blank name is
entered.
Information for each guitar is stored as an instance of th... |
list1=[10,11,12,13,14,17,18,19]
num=30
i=0
empty=[]
while i<len(list1):
j=i
empty1=[]
while j<len(list1):
if list1[i]+list1[j]==num:
empty1.append (list1[i])
empty1.append(list1[j])
empty.append(empty1)
j=j+1
i=i+1
print(empty)
|
import HashTable3
def main():
print("you as an administrator body can add and delete students for the start of the cycle of exam day starts")
type = input("if you need to add student from list please enter Add in opposite case please enter Delete")
if type == "Add":
HashTable3.creator()
elif t... |
def ordenada(lista):
for i in range(len(lista)):
if i == 0:
item = lista[i]
if item <= lista[i]:
item = lista[i]
else:
return False
return True
if __name__ == "__main__":
lista_ordenada=[1,2,2,3,4,5,6,7,8... |
def incomodam(n,item=1, palavra=""):
if(n>=item):
palavra +="incomodam "
return incomodam(n, item+1, palavra)
else:
return palavra
def elefantes(n, item=1, frase=""):
if(n>=item):
if(item==1):
frase= "Um elefante incomoda muita gente\n"
retur... |
EMPTY = 'EMPTY'
MISS = 'MISS'
SHIP = 'SHIP'
HIT = 'HIT'
class Board:
def __init__ (self, size = 10):
self.board = []
self.last_change = (EMPTY, 0, 0)
self.size = size
for i in range(size):
elem = []
for i in range(size):
elem.append(EMPTY)... |
token=0
name=True
while(name):
token=token+1
print("Token number ",token," please enter the doctor's cabin.")
print("Do you wish to continue ? (0/1)")
n=int(input())
if(n==0):
name=False
else:
continue
|
def bin_search(l,x,start,end):
if(start==end):
if(l[start]==x):
return start
else:
return -1
else:
mid=int((start+end)/2)
if(l[mid]==x):
return mid
elif(l[mid]>x):
return bin_search(l,x,start,mid-1)
else:
... |
import string
import random
symbols=[]
symbols=list(string.ascii_letters)
card1=[0]*5
card2=[0]*5
pos1=random.randint(0,4)
pos2=random.randint(0,4)
sames=random.choice(symbols)
symbols.remove(sames)
print(pos1,pos2)
if(pos1==pos2):
card2[pos1]=sames
card1[pos1]=sames
else:
card1[pos1]=sames
card2[pos2]=sames
... |
import sqlite3
conn =sqlite3.connect('sqlite3/example.db')
c = conn.cursor()
items = c.fetchall()
for item in items:
print(item)
t = ('RHAT',)
sql='SELECT * FROM stocks WHERE symbol=?'
c.execute(sql,t)
print(c.fetchone())
purchases = [('2006-03-28','BUY','IBM',1000,45.00),
('2006-04-05... |
import numpy as np
def AND(x1,x2):
w1, w2, theta = 0.5, 0.5, 0.7
tmp = x1*w1 + x2*w2
if tmp <= theta:
return 0
elif tmp > theta:
return 1
x = np.array([0,1])
w = np.array([0.5, 0.5])
b = -0.7
print(np.sum(w*x)+b)
def AND_1(x1,x2):
x = np.array([x1,x2])
w = np.array([0.5... |
from bs4 import BeautifulSoup
import urllib.request
url = 'https://music.bugs.co.kr/chart'
response = urllib.request.urlopen(url)
soup = BeautifulSoup(response,'html.parser')
results = soup.select('th>p.title > a')
print(results)
print('______')
for result in results:
print(result.string) |
class RedditPost():
def __init__(self, input):
try:
self.title = input["title"]
self.score = input["score"]
self.url = input["permalink"]
if "thumbnail" in input.keys():
self.thumbnail = input["thumbnail"]
else:
... |
n=int(input("Enter number of elements:"))
count=0
list=[]
for i in range(0,n):
elements=int(input())
list.append(elements)
search=int(input("Enter the number you want to search:"))
for i in range(0,n):
if list[i]==search:
print("number is present at index:",i+1)
count... |
def subset(arr, k):
if sum(arr) == k:
return True
if not arr:
return False
elif arr[-1] <= k:
return (subset(arr[:-1], k-arr[-1])) or (subset(arr[:-1], k))
elif arr[-1] > k:
return subset(arr[:-1], k)
print(subset([1, 2, 3], 4))
|
a = input()
ma = 0
for i in a:
if int(i) > ma:
ma = int(i)
print(ma)
|
n = 3.912
p = 2
r1 = round(n)
print(r1)
r2 = round(n, p)
print(r2)
r3 = round(145/2)
print(r3) |
import math
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
z = int(input()) * 1000
z1 = int(input()) * 1000
x3 = int(input())
y3 = int(input())
s = int(input()) * 1000 / 3600
mx = x1 * x2
my = y1 * y2
pit = z... |
'''
- For each roman numeral, if the current value is less than the next numeral's value, we are at a 'boundary' number e.g. 4, 9, 40, 90, etc.
- If so, then instead of adding the value, we simply subtract that value.
'''
class Solution:
def romanToInt(self, s) -> int:
res = 0
r_to_i = {
... |
'''
If `word[i] == '.'`, then return the result of a search from each existing child, beginning from `word[i+1]`, as if that was the correct child.
'''
class TrieNode:
def __init__(self):
self.children = [None]*26
self.isEnd = False
def contains(self, child):
return self.children[chi... |
'''
- Store paths instead of path length. It does seem like a lot of space, but even if you use pointers its the same amount of space.
- Once there is a min path, terminate any other path that is the same length.
- Do not use a global visited - we need all paths, including paths that use the same nodes. Instead, che... |
'''
For each new element, traverse the string backwards looking for elements to form new symmetries with, deriving the new length from the length of inner palindromes. Start from `0`, and every time you shift `i` to the right, shift `j` backwards from `i-1` to `0`.
1. Let `dp(j, i)` be the length of the longest pal... |
'''
- If zero, add to zeros, which is the number of consecutive zeroes directly before index i.
- If non-zero and we have no consecutive zeros: pass.
- If non-zero and we have at least one zero before i:
- swap the first zero(at index i - zeros) with the current value.
- note that the number of consecutive zero... |
import itertools
from typing import List
class Solution(object):
def twoSum(self, target, nums):
res = []
l = 0
r = len(nums) - 1
while l < r:
diff = nums[l] + nums[r] - target
if diff < 0:
l += 1
elif dif... |
class Solution:
def findDuplicate(self, nums):
i = 0
while i != nums[i]:
print(i)
k = nums[i]
nums[i] = i
i = k
print(nums)
return i
r = Solution().findDuplicate([1, 1, 2, 3, 4])
print(r)
r = Solution().findDuplicate(... |
class SolutionRec:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
else:
return max(self.maxDepth(root.right), self.maxDepth(root.left)) + 1
class Solution:
def writeMaxDepth(self, node: TreeNode, depth):
if node is not None:
... |
'''
- Only pop and unpack what is necessary.
- Pop and unpack when `hasNext` is called - it ensures there is a next available for `next`, if there really is a next.
- At the end only need to check if stack is nonempty - stack nonempty and last element not integer is not possible.
'''
class NestedIterator(object):
... |
'''
- We present a simple linear solution.
- It is possible to do binary search, but deceivingly tricky to decide what to return or the indexes to insert at.
- An attempt is done below.
'''
from typing import List
class SolutionLinear:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> Li... |
import sys
def get_rank(X):
indices = list(range(len(X)))
indices.sort(key=lambda x: X[x])
rank = [0] * len(indices)
for i, x in enumerate(indices):
rank[x] = i
return rank
def correlation(*args):
X = args[0]
Y = args[1]
n_obs = args[2]
r_X = get_rank(X)
r_... |
class Solution:
def smallestSubsequence(self, s: str) -> str:
last_index = {}
for index, char in enumerate(s):
last_index[char] = index
result = []
for index, char in enumerate(s):
if char not in result:
... |
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n = len(nums)
if n <= 1:
return nums
cand1=None
cand2=None
count1=0
count2=0
for num in nums:
... |
if __name__ == '__main__':
nested_list = []
for _ in range(int(input())):
name = input()
score = float(input())
nested_list.append([name,-score])
max_v = float("-inf")
runner_v = float("-inf")
runner_stu = []
max_stu = []
for name, score in nested_list:
if... |
from typing import List
class Solution:
def thirdMax(self, nums: List[int]) -> int:
max_num = set()
for num in nums:
max_num.add(num)
if len(max_num) > 3:
max_num.remove(min(max_num))
if len(max_num) < 3:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.