text
stringlengths
5
121k
from typing import List class Solution: def lemonadeChange(self, bills: List[int]) -> bool: count5, count10 = 0, 0 for bill in bills: if bill == 5: count5 += 1 ...
from typing import List class Solution: ...
from typing import List class Solution: def checkPossibility(self, nums: List[int]) -> bool: changed = False for i in range(len(nums)-1): if nums[i] > nums[i+1]: if changed: return False changed = True ...
class Solution: def addDigits(self, num: int) -> int: def get_nums(num): res = 0 while num: res += num % 10 num //= 10 return res if num < 10: return num res = get_nums(num) while res >= 10: ...
class Solution: def reverseLeftWords(self, s: str, n: int) -> str: return s[n:] + s[:n] obj = Solution() s = "abcdefg" k = 2 print(obj.reverseLeftWords(s, k)) s = "lrloseumgh" k = 6 print(obj.reverseLeftWords(s, k))
from typing import List import bisect class Solution: def searchInsert(self, nums: List[int], target: int) -> int: if nums[-1] < target: return len(nums) left, right = 0, len(nums) - 1 while left < right: mid = left + right >> 1 ...
from typing import List def maxArea(height: List[int]) -> int: res = float('-inf') left, right = 0, len(height)-1 while left < right: res = max(res, (right-left)*min(height[left], height[right])) if height[left] < height[right]: ...
from typing import List class Solution: def isPrefixString(self, s: str, words: List[str]) -> bool: i = 0 for word in words: n = len(word) if s[i:n+i] != word: return False i += n if i == len(s): return True...
class Solution: def hammingDistance(self, x: int, y: int) -> int: return bin(x ^ y).count('1') s = Solution() x = 1 y = 4 print(s.hammingDistance(x, y))
from typing import List class Solution: def runningSum(self, nums: List[int]) -> List[int]: for i in range(1, len(nums)): nums[i] += nums[i-1] return nums s = Solution() nums = [1,2,3,4] print(s.runningSum(nums)) nums = ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: class Solution: def isSameTree(self, p: TreeNode, q: Tre...
class MyCircularQueue: def __ini...
from typing import List class Solution: ...
class Solution: def largestOddNumber(self, num: str) -> str: for i in range(len(num)-1, -1, -1): if int(num[i]) & 1: return num[:i+1] return '' s = Solution() num = "52" print(s.largestOddNumber(num)) num = "4206" print(s.largestOddNumber(num)) num = "35427" print(s.l...
class Solution: def detectCapitalUse(self, word: str) -> bool: return word.isupper() or word.islower() or word.istitle() s = Solution() word = "USA" print(s.detectCapitalUse(word)) word = "FlaG" print(s.detectCapitalUse(word))
from functools import reduce from operator import ixor from typing import List class Solution: ...
from typing import List import bisect class Solution: def search(self, nums: List[int], target: int) -> int: left = bisect.bisect_left(nums, target) if left == len(nums) or nums[left] != target: return 0 right = bisect.bisect(nums, target) ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def recoverTree(self, root: TreeNode) -> None: def inorder(root): if not root: return [] return...
from typing import List class Solution: def removeElement(self, nums: List[int], val: int) -> int: i = 0 for num in nums: if num != val: nums[i] = num ...
import turtle turtle.shape('turtle') def koch(order, size): if order == 0: turtle.forward(size) else: koch(order-1, size/3) turtle.left(60) koch(order-1, size/3) turtle.right(120) koch(order-1, size/3) turtle.left(60) koch(order-1, size/3) koch(4...
import random def BirthdayParadox(): birthdayList = [] birthdayList = [random.randint(1, 365) for i in range(25)] birthdayList.sort() for a in range(len(birthdayList)): while a < (len(birthdayList))-1: if birthdayList [a] == birthdayList [a+1]...
class Solution: def rotate(self, nums, k: int) -> None: nums[:] = nums[-(k % len(nums)):] + nums[:-(k % len(nums))] if __name__ == '__main__': s = Solution() list1 = [1, 2] s.rotate(list1, 3) print(list1)
import turtle import random """ ustawienia początkowe i rysowanie ramki """ pen = turtle.Turtle() pen.pensize(1) pen.pencolor('blue') pen.penup() pen.goto(-220, 220) pen.pendown() pen.forward(400) pen.right(90) pen.forward(400) pen.right(90) pen.forward(400) pen.right(90) pen.forward(400) pen.penup() pen.goto(-200, 20...
height = float(input('enter your height (cms)\n')) weight = float( input('enter your weight (kg)\n')) bmi = round(weight/(height/100)**2,2) if bmi < 18.5: bmi_type="Under Weight" elif bmi < 25 : bmi_type="Normal" elif bmi < 30 : bmi_type="Over Weight" elif bmi< 35 : bmi_type="Obesity" else...
from typing import List from element.person import Person class Teacher(Person): def __init__(self, name: str, address: str): super().__init__(name, address) self.__courses: List[str] = [] def add_course(self, course: str) -> bool: if len(self.__courses) < 3: self.__cour...
from typing import List from element.person import Person class Student(Person): def __init__(self, name: str, address: str): super().__init__(name, address) self.__courses: List[str] = [] self.__grades: List[int] = [] def __str__(self) -> str: datas = [] for i in ran...
import typing as t class Person: name: str MyPerson = t.NewType("MyPerson", Person) OptionalMyPerson2 = t.NewType("OptionalMyPerson", t.Optional[Person]) OptionalMyPerson3 = t.NewType("OptionalMyPerson2", t.Optional[MyPerson]) MyPeople = t.NewType("MyPeople", t.List[Person]) MyPeople2 = t.NewType("MyPeople2", ...
try: mylist=[] name=input("Enter file name:") file=open(name,"r") count=0 for line in file: if line.startswith("X-DSPAM-Confidence:"): count+=1 trim=line.find(":") extract=float(line[trim+1:]) mylist.append(extract) print("Average spam conf...
Hours = float(input("Enter hours: ")) Rate = float(input("Enter rate: ")) Gross_pay = Hours * Rate print("Pay:",Gross_pay)
def chop(list): print(list[1:-1]) def middle(list): middle = (list[1:-1]) print(middle) list = ['goat','cow','cat','sheep','dog','hen'] chop(list) middle(list)
import random print ("Flip coin...") coin = random.randint(1,2) if(coin == 1): print ("It is heads!") elif(coin == 2): print ("It is tails!") print ("Rolling die...") die = random.randint(1,6) if (dice == 1): print("You rolled a 1!") elif(dice == 2): print("You rolled a 2!") elif(dice == 3): print...
def matches(word, pattern): for i in range(0, len(word) - len(pattern) + 1): checkPattern = pattern j = 0 for c in checkPattern: if 65 <= ord(c) <= 90: if not word[i + j] in checkPattern: checkPattern = checkPattern.replace(c, word[i + j]) ...
number1 = int(input("Ingrese el primer entero del rango: ")) number2 = int(input("Ingrese el segundo entero del rango: ")) suma = 0 for i in range (number1,number2+1): suma = suma + i print (suma)
while True: name = input ("Ingrese su nombre: ") if name == "done": print ("I'm done") elif name == "END": break else: print (name)
quarters = 10 dimes = 10 nickels = 10 pennies = 10 price = 0 int_paid = 0 print("\nWelcome to change-making program.") print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format( quarters, dimes, nickels, pennies)) price = input("Enter the purchase price (xx.xx) or 'q' to quit: "...
Rods = input("Input rods: ") Rods = float(Rods) print("You input " + str(Rods) + " rods.") print("Conversions") Furlongs = round(float(Rods / 40) ,3) Meters = round(float(Rods * 5.0292) , 3) Feet = round(float(Meters / .3048) ,3) Miles = ...
import misc from simethods.newton_2d import newton_2d from siplot.plot import Dot from siplot.plot_2d import plot_2d def f(x: float, y: float) -> float: """Test function.""" return y**4 + x * y**3 + 2 * (y**2) * (x**2) + y + x**4 - x def main() -> None: """Newton method example.""" start_x = misc....
from tkinter import Tk, Menu, Text, messagebox, END, filedialog def context(event): context_menu.tk_popup(event.x_root, event.y_root) def close(): if messagebox.askyesno(exit_out_txt, asky_exit_txt): window.destroy() def new_file(): if messagebox.askyesno(new_file_txt, asky_new_txt): t...
""" Outputs graphs in ready-to-draw format """ import networkx as nx def whole(distances): g = nx.DiGraph() for start in distances: for key, value in distances[start].items(): if not value == "inf" and not start == key: g.add_edge(start, key, weight=value) return g def tree(start, predecessors...
class Tweet(object): tweet = "" datetime = "" user = "" sentiment = "" def __init__(self, tweet, user, datetime): """ Creates a tweet object container a tweet """ self.tweet = tweet self.datetime = datetime self.user = user self.sentiment = ''...
class Node: def __init__(self, data, llink = None, rlink = None): self.data = data self.llink = llink self.rlink = rlink def Search(head,a): while True: if head.rlink.data >= a: return head.rlink break else: head = ...
class QQ(): def __init__(self,n): self.q=[] self.front=0 self.rear=0 self.size=n for i in range(n): self.q.append(None) def isFull(self): if (self.rear+1)%(self.size)==(self.front) and self.q[self.rear]!=0: return True else...
from Node import * class UnorderedList: def __init__(self): self.head=None def isEmpty(self): return self.head==None def add(self, item): temp=Node(item) temp.set_next(self.head) self.head=temp def size(self): current=self.head count=0 while current!=None: count=count+1 current=current.get_ne...
''' M. Steven Towns 10/5/16 Homework 02 Part A THIS MUST BE RUN WITH PYTHON 3 ''' def BinarySearch01(A,k): low=0 high=len(A)-1 while True: mid=(low+high)//2 if A[mid]==k: return mid elif A[mid]>k: high=mid-1 else: low=mid+1 if low>=high: return "NIL" usrIn=input("Please give a list of nu...
import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart port = 465 receiver_email = "" sender_email = "" password = "" message = MIMEMultipart("alternative") message["Subject"] = "multipart test" message["From"] = sender_email message["To"] = receiver_email text =...
""" Created on Sun May 10 18:30:36 2020 @author: User """ for i in range(1,11): if(i==7): continue; print(i)
zbior = set() print(zbior) zbior.add("x") zbior.add(1) print(zbior) for element in zbior: print(element) print(dir(zbior)) a = {1, 2, 3} b = {2, 3, 4} print(a | b) print((a & b)) print(a - b) print(a ^ b) print(a.pop()) print(a) print(dir(set()))
first_number = int(input("Podaj pierwszą liczbę: ")) second_number = int(input("Podaj drugą liczbę: ")) kind_of_operation = input("Podaj znak operacji: ") if kind_of_operation == "+": result = first_number + second_number elif kind_of_operation == "-": result = first_number - second_number elif kind_of_operat...
x = (1, 2, 3, 10, 12, "ala", "mm", 2.0) print(x) print(type(x)) print(dir(x)) print(x.index("ala")) print(len(x)) print(len("Ala")) print(x.count(12)) print(3 in x) print(x[0]) y = "mariola" print(y[::-1]) print(tuple("123"))
elementy = [1, 2, 3, 4, 5, "xxx", 2.0, 2] print((type(elementy))) print(list()) x = elementy.append("cos") print(elementy) print(x) print(len(elementy)) while len(elementy) <11: elementy.append("xx") print(dir(elementy))
pol_ang = {"kot": "cat", "ptak": "bird"} pol_ang["pies"] = "dog" pol_ang["kot"]= "kitten" print(pol_ang) dict_2 =dict(a=18, b=22, c=33) print(dict_2)
class CashMachine: def __init__(self): self.__money = [] @property def cash_is_available(self): return len(self.__money) > 0 def put_money_into(self, bills): self.__money += bills def withdraw_money(self, amount): to_withdraw = [] for bill in sorted(self....
def read_lines(filename="", nb_lines=0): with open(filename) as f: i = len(list(f)) if nb_lines >= i or nb_lines <= 0: nb_lines = i f.seek(0, 0) for count in range(nb_lines): print(f.readline(), end="")
from sys import argv from calculator_1 import add, sub, mul, div if __name__ == "__main__": if len(argv) != 4: print("Usage: ./100-my_calculator.py <a> <operator> <b>") quit(1) a = int(argv[1]) b = int(argv[3]) operators = ["+", "-", "*", "/"] functions = [add, sub, mul, div] fo...
def print_sorted_dictionary(my_dict): for y in sorted(my_dict.keys()): print("{}: {}".format(y, my_dict[y]))
""" Take an input stream and hash it's contents using MD5 and return the hash digest """ from hashlib import sha1 from hashlib import md5 def hash_stream_sha1(stream, chunk_size=4096): """ Hash a stream of data using sha1 """ shash = sha1() for chunk in iter(lambda: stream.read(chunk_size), '...
import math print( ''' Please Provide Information for the lens: 1. Radius 2. Clear Aperature 3. Given Tolerance ''' ) radius = float(input('Radius?')) ca = float(input('Clear Aperature?')) tol = float(input('Tolerance?')) ''' Can change this if nec...
import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats import math mu = int(input("Please enter the mean\n")) variance = int(input("Please enter the variance\n")) sigma = math.sqrt(variance) x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100) plt.plot(x, stats.norm.pdf(x, mu, sigma)) plt.show()
import sys def all_same(items): return all(x == items[0] for x in items) def ask_ok(prompt, retries=4, complaint='s or e, please!'): while True: ok = input(prompt) if ok in ('e', 'E'): return True if ok in ('s', 'S'): return False retries = ret...
import os import time import threading import multiprocessing NUM_WORKERS = multiprocessing.cpu_count() print("The number of workers is",NUM_WORKERS) def only_sleep(): print("PID: %s, Process Name: %s, Thread Name: %s" % ( os.getpid(), multiprocessing.current_process().name, threading...
import torch import math import matplotlib.pyplot as plt class RoundingNoGrad(torch.autograd.Function): """ RoundingNoGrad is a rounding operation which bypasses the input gradient to output directly. Original round()/floor()/ceil() opertions have a gradient of 0 everywhere, which is not useful when d...
import string def PrintOutput(output): print("OUTPUT", output) def LoadFile(file_name): with open(file_name) as file: my_list = file.read().splitlines() return my_list def UpdateString(s1, s2, index): my_list = list(s1) my_list[index] = s2 PrintOutput("".join(my_list)) def...
""" Created on Wed Nov 4 14:51:37 2020 @author: tatyanamironova """ user_info = {"who": "Katten", "what": "loves", "whom": "Medvezhaten"} for v in user_info.values(): print(v)
""" Created on Mon Sep 21 13:18:18 2020 @author: tatyanamironova """ from random import randint player_wins = 0 computer_wins = 0 winning_score = 3 while player_wins < winning_score and computer_wins < winning_score: print (f'Player score: {player_wins} Computer score: {computer_wins}') print('Rock...') ...
""" Created on Mon Sep 21 16:26:47 2020 @author: tatyanamironova """ ''' r = range(10) print(list(r)) ''' nums = range(1,10,2) print(list(nums))
""" Created on Mon Nov 16 13:30:04 2020 @author: tatyanamironova """ person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]] answer = {thing[0]: thing[1] for thing in person} print(answer)
""" Created on Wed Nov 4 14:51:37 2020 @author: tatyanamironova """
def fibonacci(N): fib = [0] * N fib[0] = 1 fib[1] = 1 for i in range(2, N): fib[i] = fib[i-1] + fib[i-2] return fib def solution(A, B): M = max(A) fib = fibonacci(M+1) N = len(A) res = [0] * N for i in range(N): res[i] = fib[A[i]] & ((1 << B[i]) - 1) ...
"""Este programa fara a soma, subtracao e divisao de varios numeros""" a = 4 b = 3 print('a soma de a e b e: ' + str(a + b)) print('a multiplicacao de a e b e: ' + str(a * b)) print('a subtracao de a e b e: ' + str(a - b))
def font_style( custom_font, font): """ Changes font family :param custom_font: font used by Message in Tkinter GUI :param font: font the user selects :return: font used by GUI """ custom_font.config(family=font) return custom_font def font_size( custom_font, f_size): ...
def reverseWords(inp): i, j = 0, len(inp)-1 lDelim, rDelim = ' ', ' ' while(i <= j): if inp[i].isalpha() and inp[j].isalpha(): i += 1 j -= 1 elif not inp[i].isalpha(): while i <= j and not inp[i].isalpha(): lDelim += inp[i] ...
''' Question --> This problem was asked by Microsoft. Implement the singleton pattern with a twist. First, instead of storing one instance, store two instances. And in every even call of getInstance(), return the first instance and in every odd call of getInstance(), return the second instance. Approach --> Create two...
''' Question --> This problem was asked by Jane Street. Generate a finite, but an arbitrarily large binary tree quickly in O(1). That is, generate() should return a tree whose size is unbounded but finite. Approach --> Use python lazy properties to generate a tree Node's left and right are only computed the first time...
def main(): s = int(input()) h=s//3600 m=(s%3600)//60 s=(s%3600)%60 print("{}:{}:{}".format(h,m,s)) if __name__ == "__main__": main()
def main(): string = input() if string.find("bad") != -1: if string.find("not") < string.find("bad"): part1 = string.split('not')[0] part2 = string.split('bad')[1] print(part1 + "good" + part2) else: print(string) else: ...
def RecSum(n): if n <= 9 and n >= 0: return n s = 0 for i in str(n): s += int(i) return RecSum(s) def main(): n = int(input()) print(RecSum(n)) if __name__ == "__main__": main()
quiz_max, exam_max, assignment_max, project_max = 20, 100, 100, 50 def inputCheck(type, type_max): if type > type_max: return ("ERROR: Invalid Marks {} > {}".format(type, type_max)) elif type < 0: return ("ERROR: Invalid Marks {} < {}".format(type, 0)) def read_marks(): quiz = ...
fruit = 'BANANA' index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 fruit = 'BANANA' index = -1 while index < len(fruit): letter = fruit[index] print(letter) index = index - 1
from RetirementCalc import retirementCalc import unittest class RetirementTest(unittest.TestCase): def retirementCalcTest(self): agemet = retirementCalc(25, 6500, .5, 150000) self.assertEqual(agemet, (59.0, False)) agemet = retirementCalc(10, 5, .1, 1000000) self.asser...
niz=[1,2,3,4,5,3,7,7] broj=3 pozicije=[] for i in range(len(niz)): if niz[i] == broj: pozicije.append(i) print(pozicije)
import datetime as dt class Record: def __init__(self, amount, comment, date=None): self.amount = amount self.comment = comment if type(date) is str: self.date = dt.datetime.strptime(date, '%d.%m.%Y').date() else: self.date = dt.d...
lst = [] n = int(input("Enter number of elements : ")) for i in range(0, n): ele = input() lst.append(ele) a = "" for j in lst: a += j print(a) def reverse(string): string = string[::-1] return string print(reverse(a[2::]))
import pandas as pd glass_data = pd.read_csv('glass.csv') x=glass_data.drop('Type',axis=1) y=glass_data['Type'] from sklearn import model_selection X_train, X_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=0.2,random_state=0) from sklearn.naive_bayes import GaussianNB model = Ga...
n=int(input("Digite o maximo de numeros:")) def ler_numeros(n): l=[] for i in range(n): x=float(input("Digite os numeros:")) l.append(x) i=i+1 return l print(ler_numeros(n))
""" @Makers Write a function square_number that takes in a number and squares it. """ def square_number(number): return number ** 2 def test_square_number(): assert square_number(2) == 4 assert square_number(8) == 64 assert square_number(10) == 100 print("YOUR CODE IS CORRECT!") test_squar...
import string import math def decode(digits, base): decoded = [] """Decode given digits in given base to number in base 10. digits: str -- string representation of number (in given base) base: int -- base of given number return: int -- integer representation of number (in base 10)""" ...
''' def mySum(n1: int, n2: int) -> None: print(f"{n1} + {n2} = {n1+n2}") mySum(2,3) mySum(5,7) mySum(10,15) ''' def mySum(n1: int, n2: int) -> None: print(f"{n1} + {n2} = {n1+n2}") res1 = mySum(2,3) res2 = mySum(5,7) res3 = mySum(10,15) print("---------") print(res1) print(res2) print(res3) ''' def mySum...
num1 = 3 num2 = 5 print(num1 + num2) print(num1 - num2) print(num1 * num2) print(num1 / num2) print(num1 % num2) print(num1 ** num2)
from tkinter import * window = Tk() window.title("Mile to Km converter") window.minsize(width=300, height=150) window.config(padx=60, pady=30) miles_input = Entry(width=10) miles_input.grid(row=0, column=1) miles_input.grid(padx=10) miles_input.insert(END, "0") miles_label = Label(text="Miles") miles_label.grid(row=...
''' Task: The durability map is represented as a matrix with digits. Each number is the durability measurement for the cell. To find the weakest point we should find the weakest row and column. The weakest point is placed in the intersection of these rows and columns. Row (column) durability is a sum of cell dura...
''' Find the earliest ancestor of a node ''' from graph import Graph def earliest_ancestor(ancestors, starting_node): ''' Input: list of ancestor tuples and a starting point. First value in tuple is the parent, remainder are children. Output: longest graph path from given starting node. ''' vert ...
import numpy as np import matplotlib.pyplot as plt ''' Plot test mass trajectories in the restricted three-body problem ''' a = 1 G = 1 m = 1 M_2 = 1 delta_t = 0.001 mass_ratios = {"i": 1, "ii": 0.041, "iii": 0.039, "iv": 19/20000} def determine_mass_of_M_1(mass_ratio, M_2): return mass_ratio * M...
class LruCache: def __init__(self, capacity) -> None: self.capacity = capacity self.price_table = {} def lookup(self, isbn): if isbn not in self.price_table: return -1 price = self.price_table.pop(isbn) self.price_table[isbn] = price ...
def findTyposCount(): txt = input("Please enter the searching text here:") pat = input("Please enter the searchable pattern here:") pat_len = len(pat) txt_arr = txt.split(" ") counter_list = [] for each in txt_arr: counter = 0 txt_len = len(each) if(txt_le...
def countBits(n): count = 0 while (n): count += 1 n >>= 1 return count i = 65 print(countBits(i)) import math def countBitsByLog(number): return int((math.log(number) / math.log(2)) + 1); num = 65; print(countBitsByLog(num));
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node ...
def jump_over_numbers(mylist): index = 0 maxjump = 0 while(index < len(mylist)): if(mylist[index] == 0): return -1 index = index + mylist[index] maxjump = maxjump + 1 return maxjump mylist = [3, 4, 1, 2, 5, 6, 9, 0, 1, 2, 3, 1] print(jum...
import heapq H = [21,1,45,78,3,5] heapq.heapify(H) print(H) heapq.heappush(H,8) print(H) heapq.heappop(H) print(H) heapq.heapreplace(H,6) print(H)
def outer_function(): message = 'Hi' def inner_function(): print(message) return inner_function my_func = outer_function() my_func() my_func() my_func()
age=int(input("Enter Your Age:")) if(age>28): print("Yes U can Drink Alcohol") elif( age>15): print("You can take Only soft Drinks") else: print("You can only drink Water") if(12>6):print("hello ") x=50 if(x>40): print("Above Ten") if(x>30): print("and also greater than 30") if(x>20)...