text stringlengths 37 1.41M |
|---|
import pandas as pd
from keras.utils.np_utils import to_categorical
def load_train():
return pd.read_csv('train.csv')
def load_test():
return pd.read_csv('test.csv')
def separate_train(train):
Y_train = train['label']
X_train = train.drop(labels=['label'], axis=1)
return (X_train, Y_train)
de... |
'''
Created on 2020. 8. 7.
@author: GDJ24
'''
def calc(a, b, c) :
if c == "+" :
return a+b
elif c == "-" :
return a-b
elif c == "*" :
return a*b
elif c == "/" :
return a//b
oper = input("연산자를 선택하세요. (+, -, *, /)")
var1 = int(input("첫번째 수를 입력하세요."))... |
'''
Created on 2020. 8. 7.
@author: GDJ24
'''
def getSum(l) :
sum = 0
for i in range(0, len(list)) :
sum += list[i]
return sum()
def getMean(l) :
sum = 0
for i in range(0, len(list)) :
sum += list[i]
return sum/len(list)
list = [2,3,3,4,... |
'''
Created on 2020. 8. 7.
@author: GDJ24
'''
def coffee_machine(button) :
print()
print("#1 뜨거운 물 준비")
print("#2 종이컵 준비")
if button == 1 :
print("#3 보통커피를 탄다.")
elif button == 2 :
print("#3 설탕커피를 탄다.")
elif button == 3 :
print("#3 블랙커피를 탄다.")
else :
... |
'''
Created on 2020. 8. 11.
@author: GDJ24
'''
class Car :
color = ""
speed = 0
num = 0
count = 0
#생성자
def __init__(self):
self.speed = 0 # 인스턴스 변수
Car.count += 1 # 클래스 변수
self.num = Car.count # 인스턴스 변수
def printMessage(self):
print("색상:%s, 속... |
class IntComputer:
def __init__(self, code, in_sequence=[]):
"""
This builds a new IntComputer object.
`code` is a list of integers representing the code
that the IntComputer should execute.
`in_sequence` is a list of integer inputs that will
be... |
# Here we print out a line.
print "How old are you?",
# Here we define a variable called age and then we ask for the user to input info.
# That info is stored in the variable age.
age = raw_input()
# Here we print out a line.
print "How tall are you?",
# Here we define a variable called height and then we ask for the u... |
import sys
from datetime import datetime
# Takes string value and attempts to
# strip percentage and convert to float
def convertPercentToFloat(passedValue):
# Try catch block, attempt to convert passed value to float, if it fails throw exception
try:
return float(passedValue.strip('%'))
except E... |
#5x^3 − 17x^1 + 42x^0
#[42,-17,0,5]
class Polynomial:
def __init__(self,lst):
self.lst = lst
def __repr__(self):
lst = [str(self.lst[n])+"x^"+str(n) for n in range(len(self.lst)-1,-1,-1)]
return "+".join(lst)
def eval(self,value):
s = 0
for i in range(len(self.lst))... |
import turtle
class BinarySearchTreeMap:
class Item:
def __init__(self,key,value = None):
self.key = key
self.value = value
def __repr__(self):
return "("+str(self.key) + " : "+ str(self.value)+")"
class Node:
def __init__(self,item,left = None,righ... |
#Problem 1
class ArrayDeque:
CAPACITY = 8
def __init__(self):
self.data = [None] * ArrayDeque.CAPACITY
self.size = 0
self.front = None
self.back = None
def __len__(self):
return self.size
def is_empty(self):
return len(self) == 0
def first(self):
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
for i in range(n):
try:
a, b = input().split(" ")
a = int(a)
b = int(b)
print(a//b)
except ZeroDivisionError as e:
print("Error Code:", e)
except ValueError as v:
print("Err... |
# Task
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to, print Not Weird
# If is even and in the inclusive range of to, print Weird
# If is even and greater than, print Not Weird
n = int(input())
if (n % 2 != 0):
print('weird... |
import threading
class Stack:
def __init__(self):
self.items = []
self.lock = threading.Lock()
def push(self, item):
self.lock.acquire()
try:
self.items.append(item)
finally:
self.lock.release()
def append(self, item):
... |
def foo(x):
x = 5
var = 10 # immutable type
foo(var)
print(var)
def foo2(a_list):
a_list.append(10)
a_list[0] = 0
my_list = [1,2,3,4]
foo2(my_list) # list is mutable and can be changed
print(my_list) #[0, 2, 3, 4, 10]
def foo_rebind(a_list):
a_list = [100, 200, 300]
a_list.append(400)
my_list2 ... |
#Dictionary, key-value pairs, unordered, mutable
#create dictionary
my_dict1 = {"name": "Max", "age": 34, "city": "New York"}
print(my_dict1)
print(my_dict1["name"])
my_dict2 = dict(name="Max", age=34, city="New York")
print(my_dict2)
print(my_dict2["age"])
#my_dict2["lastname "] #Key ERROR
my_dict3 = my_dict2
my_dict3... |
def mygenerator():
yield 1
yield 2
yield 3
g1 = mygenerator()
print(g1)
for i in g1:
print(i)
g2 = mygenerator()
print(next(g2))
print(next(g2))
print(next(g2))
g3 = mygenerator()
print(sum(g3))
g4 = mygenerator()
print(sorted(g4))
def countdown(num):
while num > 0:
yield num
... |
#!/usr/bin/env python3
import pytest
import string
from math import *
from coordinates import Coordinate as coord
from collections import defaultdict
from operator import itemgetter
def num_to_char(num):
return chr(97+num)
def manhattan_distance(a, b):
return abs(a.x - b.x) + abs(a.y - b.y)
def test_manhattan_di... |
import time
from Person import Person
class Race:
segundos = 0
ganador = ""
runK = 10000
pedalK = 20000
swimK = 1000
teamWrites = 2
travel = list()
def stopWatch(self):
self.initRecorrido()
while True:
resultado = False
... |
from operator import itemgetter
def topItems(noteslist, n): #noteslist = "notes.txt" например
favNotes = []
nn = []
result = []
with open(noteslist, "r") as myfile:
favNotes = myfile.readlines()
for note in favNotes:
x = favNotes.count(note)
if note not in nn:
... |
from pprint import pprint
def next_empty(puzzle):
for r in range(9):
for c in range(9):
if puzzle[r][c] == 0:
return r, c
return None, None
def is_valid(puzzle, guess, r, c):
row_vals = puzzle[r]
if guess in row_vals:
return False
... |
def binToDec(inNum):
numberx=inNum
dec_number= int(numberx, 2)
return (dec_number)
#print('The decimal conversion is:', dec_number)
#print(type(dec_number))
print(binToDec(input("Enter binary number: "))) |
'''
Module that handles tasks related to processes
'''
import os
import subprocess
import time
import psutil
def is_running(process_name):
'''
Check if there is any running process that contains
the given name process_name.
'''
try:
# Iterate over the all the running process
for p... |
"""
Python job scheduling for humans.
An in-process scheduler for periodic jobs that uses the builder pattern
for configuration. Schedule lets you run Python functions (or any other
callable) periodically at pre-determined intervals using a simple,
human-friendly syntax.
Inspired by Addam Wiggins' article "Rethinking... |
# https://projecteuler.net/problem=7
# Calculate the 10,001st prime number
# For example: 13 is the 6th prime number (2, 3, 5, 7, 11, 13, 17, ...)
import math
# Function to check whether a number is a prime number
def isPrime(number):
if number > 1: # Prime number must bigger than 1 and not a negative number
if n... |
# https://projecteuler.net/problem=1
# Find sum of all multiples of 3 and 5
#
# All numbers divisible by 3 would be: 3, 6, 9, 12, ...
# Sum all of them together:
# = (3 + 6 + 9 + 12 + ...)
# = 3 * (1 + 2 + 3 + 4 + ...)
#
# Similar for all numbers divisible by 5
from __future__ import division
MAX_VALUE = 999
def sum_... |
# https://projecteuler.net/problem=5
# Find the smallest number that evenly divisible by all of the numbers from 1 to 20
# For further divisibility rules, read the following link:
# https://en.wikipedia.org/wiki/Divisibility_rule
###################################################################################
impo... |
finalcount = 0
count = 0
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
fizzlist = ["fizz", "fizz", "fizz", "dog"]
fizz_count(fizzlist)
print(count)
print(len(fizzlist))
print(fizzlist.count("fizz"))
|
answers=0
print('1. Какой язык программирования мы начали учить в этом семестре?')
answer1=input()
if answer1=='Python' or answer1=='python':
answers+=1
print('Правильно')
else:
print('Не правильно')
print('2. Каким образом в python тело функции отделяется от заголовка?')
answer2=input()
if answer2==... |
#variables demonstrated
print ("This program is a demo of how variables work")
v = 1
print ("The value of v is now",v)
v = v + 1
print ("v is now equal to itself plus one, making it worth",v)
v = 51
print ("v can sotre a numerical value, that can be used elsewhere.")
print ("For example, in this sentence, v is worth",... |
#Clase objeto para simular objetos de tipo A,B y C
#el traibuto tipo es de tipo entero
#si tipo = 1 entonces el objeto es de tipo A
#si tipo = 2 entonces el objeto es de tipo B
#si tipo = 3 entonces el objeto es de tipo C
class Objeto:
def __init__(self, id, tipo):
self.id = id
self.tipo = tipo
def getTipo(self... |
print ("NOTE:\n")
print ("Maturity period for PPF is 15 years . Hence gross is calculated for 15 years\n")
print ("Enter your yearsly inverstment ...")
inverstment = int(raw_input())
print ("Enter current interest rate ...")
current_interest_rate = float(raw_input())
def ppfcal(inverstment,current_interest_rate):
if... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 11:34:57 2014
@author: pruvolo
"""
# you do not have to use these particular modules, but they may help
from random import randint
import Image
from math import pi,sin,cos,sqrt
import numpy as np
def build_random_function(min_depth, max_depth):
#inputs a min and m... |
# ################################ #
# DE2-COM2 Computing 2 #
# Individual project #
# #
# Title: MAIN #
# Authors: Amy Mather #
# Last updated: 4th December 2018 #
# ################################ #
from copy imp... |
def konversiSuhu(C = "none", F = "none"):
"mengkonversikan suhu dari Celcius ke Fahrenheit dan sebaliknya"
suhu = 0
if (C == "none") and (F == "none"):
print ("Suhu 0 Celcius setara dengan 32 Fahrenheit")
elif (C == "none") and (F == "none"):
suhu = (F - 32) * 5/9
print ("... |
# 7.1
# a = int(input("ange multiplikationstabell")) # ber om multitabell
# num = 1 # vårt första värde i multitabellen
# c = 4 # antal gånge (-1) som tabellen körs
# while num < c: # medan vårt första värde är mindre än antal gånge vi kör
# b = a*num # # kommer vi multiplicera ditt tal med första värdet
#... |
import turtle
t = turtle.Turtle()
t.hideturtle()
t1 = turtle.Turtle()
t1.hideturtle()
scr = turtle.Screen()
scr.bgcolor('black')
def filler(x,y,length,x1,y1,len):
t.begin_fill()
t.fillcolor('white')
t.up()
t.goto(x,y)# moves that co ordinates
t.down()
t.circle(length)
t.end_fill()
t1.be... |
def convert_seconds(seconds):
hours=seconds//3600
minutes=(seconds-hours*3600)//60
remaining_seconds=seconds-hours*3600-minutes*60
return hours,minutes,remaining_seconds
|
number_list = [-1, 1, 2, 5, 7, 8657, 2, 99997, 431, 3, 432, 4325]
def find_max(list):
largest = list[0]
for i in list:
temp = largest
# print ("temp is :", temp)
if temp < i:
largest = i
elif temp == i:
largest = i
else:
largest = tem... |
# -*- coding: utf-8 -*-
class Node(object):
"""Singly Linked List Node class"""
def __init__(self, data, next_node):
self.data = data
self.next = next_node
def __repr__(self):
return str(self.data)
class LinkedList(object):
def __init__(self):
self.head = None
... |
import random
def play_guessing_game(secret_number, max_tries):
number_tries = 1
user_number = int(input('Please enter a number:'))
while(secret_number != user_number) and number_tries < max_tries:
if(secret_number > user_number):
print("The secret number is greater ")
else:
... |
def area_square(side_length):
area = side_length * side_length
print("The area is: " + str(area) +"cm2")
area_square(10)
area_square(20)
|
# coding: utf-8
# In[44]:
#Implement a userdefined function myreduce()
def myreduce(list):
y=1
for n in list:
y=y*int(n)
return(y)
l=input("Enter a list with number\n")
l=l.split(',')
myreduce(l)
# In[126]:
#Implement a userdefined filter function myfilter()
def myfilter(list):
z=[]
... |
"""
Formatando valores com modificadores
:s - Texto (strings)
nu
:d - Inteiros (int)
:f - Números de ponto flutuante (float)
:.(NUMERO)f - Quantidade de casas decimais (float)
:(CARCTERE) (> ou < ou ^) (QUANTIDADE) (TIPO - s, d ou f)
> - Esquerda
< - Direita
^ - Centro
"""
num_1 = 10
num_2 = 3
divisao = num_1... |
"""
* Tipos de dados
str - string = textos 'Assim' ou "Assim"
int - inteiro = 123456 / 0 / -10 / -20 / 1500
float - número real/ponto flutuante = 1.25 / 2.56 / -3.60
bool - booleano/lógico = true/False 10 == 10
"""
print("Marcelo", type("Marcelo"))
print(123, type(123))
print(2.56, type(2.56))
print("L" == "l", ty... |
name ="Elif Sude"
surname="Tural"
counter = 0
def check():
global counter
inputname = input("Enter name: ")
inputsurname = input("Enter surname: ")
if (name != inputname or surname != inputsurname):
counter += 1
print("Name or surname incorrrect.")
else:
prin... |
import nltk
from nltk.corpus import wordnet as wn
def isFood(inputword):
isfood = 0
thesyns = wn.synsets(inputword.lower())
for syn in thesyns:
if isfood > 0:
break
theword=wn.synset(syn.name())
paths = theword.hypernym_paths()
for route in paths:
if... |
""" THis module is realeted to board basic one that appers without
people and bombs """
class Board:
""" THis class prints the board and populates blocks in the board"""
def __init__(self, rows, columns, x_size, y_size):
self.rows = rows
self.columns = columns
self.x_size = x_size
... |
phonebook = {"Chris": "555-111",
"Katie": "555−2222",
"Joanne": "555-333"}
""
print()
print("***** start section 1 - print dictionary ********")
print()
print(phonebook)
print(len(phonebook))
mydictionary = dict(m=8,n=9)
print(mydictionary)
print()
print("***** end section... |
from customer import Customer
class Restaurant(object):
"""A Restaurant.
This class represents a restaurant in the simulation. This is the base
class for different restaurant approaches. The main purpose of this
class to define common interfaces for different approaches. If there
are common tasks ... |
# Set of all keywords in the Jack grammar.
KEYWORDS = {
'class',
'constructor',
'function',
'method',
'field',
'static',
'var',
'int',
'char',
'boolean',
'void',
'true',
'false',
'null',
'this',
'let',
'do',
'if',
'else',
'while',
'retu... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 1 13:39:18 2021
@author: USUARIO
"""
Nombre=input("Ingrese Nombre: ")
Apellido=input("Ingrese Apellido: ")
Pais=input("Ingrese Pais: ")
Ciudad=input("Ingrese Ciudad: ")
Edad=input("Ingrese Edad: ")
print("")
print("Datos Personales")
print("Nombre: ",Nom... |
from datetime import datetime
date_entry = input('dwse imerominia etsi:ΗΗ/ΜΜ/ΕΕΕΕ')#mu vazi o user tin hmerominia
year, month, day = map(int, date_entry.split(','))#apo edo ego tha paro ta year,month,day
date = datetime(day, month, year)
from datetime import date
today = date.today().isoformat()
print("s... |
import sortLib as sl
def mergesort(inputList):
if len(inputList) == 1:
return inputList
# Floor Division
mid = len(inputList)//2
list1 = mergesort(inputList[:mid])
list2 = mergesort(inputList[mid:])
return merge(list1, list2)
def merge(list1, list2):
retList = []
while (len(li... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 06:58:59 2018
@author: Sylvia
"""
#Following Links in Python
#In this assignment you will write a Python program that expands on
#http://www.py4e.com/code3/urllinks.py. The program will use urllib to
#read the HTML from the data files below, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 24 17:39:55 2018
@author: Sylvia
"""
# Question 8: Longest Repetition
# Define a procedure, longest_repetition, that takes as input a
# list, and returns the element in the list that has the most
# consecutive repetitions. If there are multiple ... |
# -*- coding: utf-8 -*-
##PANDAS
#veri temizleme ve veri analizi modülü
#iki veri yapısına sahiptir. series ve dataframe
#numpy dizilerinde bulunan elemanlar aynı veri tipinde olurken pandas
#birden fazla farklı veri tipine sahip olabilir.
#seriler numpy dizilerine benzer
import numpy as np
import pandas as... |
class Estudiante(object):
def __init__(self, nombre_r, edad_r):
self.nombre = nombre_r
self.edad = edad_r
def hola(self):
#(%s texto) (%i numero)
return "Mi nombre es %s y tengo %i" % (self.nombre, self.edad)
e = Estudiante("Roberto", 28)
s = e.hola()
#print s
lista_de_alumnos = list()
for es in range(5... |
#! /usr/bin/python
def factorial(n):
ret = n
for i in range(1,n):
ret *= i
return ret
n = 40
print ( factorial(n) / ( factorial(n-n/2) * factorial(n/2) ) )
|
###
def minion_games(string):
string = string
vowels = 'EIUOA'
kevin = 0
stuart = 0
length_s = len(string)
for i in range(length_s):
if string[i] in vowels:
kevin = kevin + length_s - i
else:
stuart = stuart + length_s-i
if kevin > stuart:
pri... |
n = int(input("Podaj ilość liczb:"))
l = []
for i in range(n):
i = int(input("Podaj liczbe:"))
l.append(i)
l.sort()
print(l)
print(l[0])
print(l[-1]) |
import unittest
class FunInterviewQuestion(unittest.TestCase):
def test_reverse_string(self):
sentense = "I am a happy person"
expected = "Person happy a am I"
ls_sentense = sentense.split()
rv_list = list(reversed(ls_sentense))
new_sentense = " ".join(rv_list)
res... |
from random import *
import time
class Person(object):
"""
Person class
aspects of personality based on Myers Briggs Personality types
mood (int) -50 to 50
name (string)
All boolean types:
energy => Natural energy (extraverted to introverted)
perception => (sensing to intuitive)
judgement => (thinking to f... |
class Node(object):
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
class Bst(object):
def __init__(self):
self.root = None
def insert(self, data):
if not self.root:
self.root = Node(data)
else:
... |
"""
FILE: UnitTestCryptoGraph.py
AUTHOR: Joby Mathew
UNIT: COMP5008 Data Structures and Algorithms
PURPOSE: Provides a Test Harness for Linked List
REFERENCE: Lecture Slides
Last Mod: 25th October, 2020
"""
from LinkedList import DSALinkedList
# Initializing the list
testList = DSALinkedList()
# Adding to the list
... |
import numpy as np
from numpy import exp, array, random, dot
import pandas as pd
from sklearn import preprocessing
"""
Project demonstrating simple backpropogation
in Neural networks.
Data used is the marks of three exams
which are used to predict final score
"""
min_max_scaler = preprocessing.MinMaxScaler()
test... |
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
return list(x)
s = Solution()
o = s.reverse(123)
print(o) |
# Polynomial Regression
#importing Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
#fitting linear regression to dataset
from sklearn.linear_model impo... |
"""
773. Sliding Puzzle
Input: board = [[1,2,3],[4,0,5]]
Output: 1
Explanation: Swap the 0 and the 5 in one move.
On a 2x3 board, there are 5 tiles represented by the integers 1 through 5,
and an empty square represented by 0.
A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
Input: ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
return f"({self.val},{self.next})"
# try printing, simply improved the result of it
# one of Python’s “dunder” (double-underscore) met... |
"""
116. Populating Next Right Pointers in Each Node
"""
class Node:
def __init__(self, val: int = 0, left = None, right= None, next= None):
self.val = val
self.left = left
self.right = right
self.next = next
from collections import deque
class Solution:
def connect(self, root... |
import collections
# There are N students in a class.
# Some of them are friends, while some are not.
# Their friendship is transitive in nature.
# For example, if A is a direct friend of B, and B is a direct friend of C,
# then A is an indirect friend of C. And we defined a friend circle is a group of students who ar... |
"""
323. Number of Connected Components in an Undirected Graph
"""
"""
use dfs - stack to traversal all connected ones
count groups by iteration
"""
from collections import defaultdict
def countComponents(self, n: int, edges: [[int]]) -> int:
# build graph
graph = defaultdict(set)
for a, b in edges:
... |
import unittest
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
return the values of its boundary in anti-clockwise direction starting from root.
"""
class bt:
def boundaryOfBinaryTree(self, root: TreeNode):
... |
"""
406. Queue Reconstruction by Height
Suppose you have a random list of people standing in a queue.
Each person is described by a pair of integers (h, k),
where h is the height of the person
and k is the number of people in front of this person who have a height greater than or equal to h.
Write an algorithm to reco... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
from collections import deque
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
... |
"""
My idea is simple, it is kind of DP or linear search or whatever ...
One observation is that the answer should reach the end of string s.
Otherwise, you can always extend the hypothetical answer to the end of string s
which will be lexicographically larger than the hypothetical answer.
Next, let's assume the cu... |
# we all know that it's kind of difficult to figure out if a number is prime or not
# that's sort when those problems that are unsolved
# so I don't expect this to have a fantastic runtime
# and I am thinking that it's just going to use a number of heuristics(启发的), right?
# so one thing we can do here is to iterate fro... |
from typing import List
class Solution:
# dfs
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
R, C = len(image), len(image[0])
color = image[sr][sc]
if color == newColor: return image
def dfs(r, c):
if image[r][c] == ... |
"""
144. Binary Tree Preorder Traversal
1. recursive
2. non recursive
O(n) O(n)
"""
class TreeNode:
def __init__(self, val, r, l):
self.val = val
self.right = r
self.left = l
def preorderTraversal(self, root: TreeNode) :
# root, left, right
if not root: return []
res = []
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
res = str(self.val)
if self.next:
res += str(self.next)
return res
# time O(N+K), which is O(n).
# space O(1)
class... |
"""
135. Candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies yo... |
"""
46 permutations
first of all there is no efficient way to do it
it has to be brute force
we're just going to generate every single combination
let's take look at this one
[1,2,3]
you have 3 spots
and the first element/ scenario you can have up to 3 different numbers
second - 2, last position - only one number
th... |
"""
102. Binary Tree Level Order Traversal
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from collections import deque
class Solution:
def levelOrder(self, root: TreeNode):
if not root: return []
... |
# The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:
# There will be exactly one celebrity
def knows(a,b):
return True
class Solution:
def findCelebrity(self, n: int) -> int:
can = 0
def secondcele(m):
for i in range(n)... |
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
class NestedInteger:
def isInteger(self) -> bool:
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
"""
def ... |
############
# given a list find out a peek --> has both increasing and decreasing side
# brute fore
def peek(input):
length = 0
for i in range(1, len(input)):
left = i-1
right = i+1
leftcheck = True
rightcheck = False
lengthCur = 1
while left>=0 and input[left]<... |
# valid binary search tree
# should
#
# 5
# /\
# 4 7
# /
# 2
# X
# have restrictions on both upper and lower bound
# traversal the tree and pass down
#
#
# Pseudo code:
# low < n.val < high
# isValid(n.left, low, n.val)
# isValid(n.right, n.val, high)
# if node is null return True
"""recursive -... |
"""
helper(left, rigth, cur):
if length of current string == 6:
result append string
if left< n:
call helper with update parameters
le
"""
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = []
if n == 0: return []
... |
# Input: word1 = "horse", word2 = "ros"
# Output: 3
# Explanation:
# horse -> rorse (replace 'h' with 'r')
# rorse -> rose (remove 'r')
# rose -> ros (remove 'e')
# find the minimum number of operations required to convert word1 to word2.
# h o r s e
# 0 1 2 3 4 5
# r1 1 2 2 3 4
# o2 2 1 2 3 4
# s3 3 2 2 2 3
clas... |
"""
112. Path Sum
O(n)
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root: return False
# make sure node is a leaf
if root.val == sum and ... |
"""
deep copy of the graph
initialize a dictionary to pair old node with new one
traversal the tree BFS
1. create queue with [initial root nodes]
2. while loop when queue not empty:
popleft queue get the cur node
for neighbour in this old node
if node not in dic:
create new node and pair it... |
"""
use a dictionary mark groups for all ele in the list
We should be able to greedily color the graph
if and only if it is bipartite:
one node being blue implies all it's neighbors are red,
all those neighbors are blue, and so on.
for each list in graph:
for each uncolored ele in list:
start the coloring... |
"""
Design a hit counter which counts the number of hits received in the past 5 minutes.
Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earlie... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
"""using list->int->list"""
# The basic idea is to convert the linked lists to integer values (using a similiar approach as atoi).
# Then create a new linked list from the sum by adding... |
import urllib.request
from bs4 import BeautifulSoup
def get_html(url):
response = urllib.request.urlopen(url)
return response.read()
def parse(html):
soup = BeautifulSoup(html, features = "html.parser")
div = soup.find('div', class_ = 'module-kurs_nbrb')
tr = div.find_all('tr')
# print(type(tr)... |
cases = int(input())
for i in range(cases):
input()
Mg ,Mm = map(int,input().split())
Lg = input().split()
Lm = input().split()
while len(Lg) > 0 and len(Lm) > 0:
minLg=min(Lg)
minLm = min(Lm)
if minLg==minLm:
Lm.remove(minLm)
elif minLm>minLg... |
a = int(input("Enter your number: "))
b = int(input("Enter your number: "))
def addition():
total = a + b
print("Two number addition: ", total)
def subtration():
sub = a - b
print("Two number sub: ", sub)
def main():
addition()
subtration()
main()
|
"""
Algorithm
for the sequence 1, 2, 3, 6, 11, 20, 37.
the algorithm for this sequence is to take the first 3 numbers and the sum of those
number will become the fourth number,
so to get the fifth number you take the second, third and fourth number to and the sum
will be the fifth number (2+3+6 = 11)
so the algorith ... |
"""
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar.
Sentence-length palindromes may be
written when allowances are made for adjustments to capital letters, punctuation, and word dividers, such as "
", "Was it a car or a cat I sa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.