text stringlengths 37 1.41M |
|---|
#!/usr/bin/python3
"""
A module that test differents behaviors
of the Base class
"""
import unittest
import pep8
from models.base import Base
from models.rectangle import Rectangle
class TestRectangle(unittest.TestCase):
"""
A class to test the Rectangle Class
"""
def test_pep8_base(self):
"""
Test that checks PEP8
"""
syntax = pep8.StyleGuide(quit=True)
check = syntax.check_files(['models/rectangle.py'])
self.assertEqual(
check.total_errors, 0,
"Found code style errors (and warnings)."
)
def test_rectangle_subclass(self):
"""
Test if Rectangle class inherit from
Base class
"""
self.assertTrue(issubclass(Rectangle, Base))
def test_parameters(self):
"""
Test parameters for Rectangle class
"""
r1 = Rectangle(10, 2)
r2 = Rectangle(2, 10)
r3 = Rectangle(10, 2, 0, 0, 12)
self.assertEqual(r1.id, 4)
self.assertEqual(r1.width, 10)
self.assertEqual(r1.height, 2)
self.assertEqual(r1.x, 0)
self.assertEqual(r1.y, 0)
self.assertEqual(r2.id, 5)
self.assertEqual(r2.width, 2)
self.assertEqual(r2.height, 10)
self.assertEqual(r2.x, 0)
self.assertEqual(r2.y, 0)
self.assertEqual(r3.id, 12)
self.assertEqual(r3.width, 10)
self.assertEqual(r3.height, 2)
self.assertEqual(r3.x, 0)
self.assertEqual(r3.y, 0)
with self.assertRaises(TypeError):
r4 = Rectangle()
def test_string(self):
"""
Test string parameters for a
Rectangle class
"""
with self.assertRaises(TypeError):
Rectangle('Monty', 'Python')
def test_type_param(self):
"""
Test different types of parameters
for a Rectangle class
"""
with self.assertRaises(TypeError):
Rectangle(1.01, 3)
raise TypeError()
with self.assertRaises(ValueError):
Rectangle(-234234242, 45)
raise ValueError()
with self.assertRaises(TypeError):
Rectangle('', 4)
raise TypeError()
with self.assertRaises(TypeError):
Rectangle(True, 4)
raise TypeError()
with self.assertRaises(TypeError):
Rectangle(5, 1.76)
raise TypeError()
with self.assertRaises(TypeError):
Rectangle(5, "Hello")
raise TypeError()
with self.assertRaises(TypeError):
Rectangle(5, False)
raise TypeError()
with self.assertRaises(ValueError):
Rectangle(5, -4798576398576)
raise ValueError
with self.assertRaises(TypeError):
Rectangle(5, 1, 1.50)
raise TypeError()
with self.assertRaises(TypeError):
Rectangle(5, 6, "test")
raise TypeError()
with self.assertRaises(TypeError):
Rectangle(5, 7, False)
raise TypeError()
with self.assertRaises(ValueError):
Rectangle(5, 7, -4798576398576)
raise ValueError()
with self.assertRaises(TypeError):
Rectangle(5, 1, 1, 1.53)
raise TypeError()
with self.assertRaises(TypeError):
Rectangle(5, 6, 5, "test")
raise TypeError()
with self.assertRaises(TypeError):
Rectangle(5, 7, 7, False)
raise TypeError()
with self.assertRaises(ValueError):
Rectangle(5, 9, 5, -4798576398576)
raise ValueError()
|
#Kate Cough
#May 25 2017
#Homework 2, part 2
#1) Make a list called "countries" - it should contain seven different countries and NOT be in alphabetical order
countries = ["zimbabwe", "algeria", "malawi", "congo", "egypt", "burundi", "rwanda"]
print(countries)
#2) Using a for loop, print each element of the list
for country in countries:
print(country)
#3) Sort the list permanently.
countries.sort()
print(countries)
#sort_country = sorted(countries)
#print(sort_country)
#4) Display the first element of the list.
print(countries[0])
#5) Display the second-to-last element of the list.
print(countries[-2])
#6) Delete one of the countries from the list using its name.
del countries['zimbabwe']
#7) Using a for loop, print each country's name in all caps.
for country in countries:
print(countries)
print(countries.upper())
#These will require LATITUDE and LONGITUDE. You can ask Google for latitude and longitude by
#typing in *coordinates of CITYNAME*. You can also use http://itouchmap.com/latlong.html.
#Store the latitude and longitude without the N/S/E/W - if the latitude is S, make it negative.
#If the longitude is W, make it negative. See here for explanation:
#https://answers.yahoo.com/question/index?qid=20080211182008AAMdUe8
#1) Make a dictionary called 'tree' that responds to 'name', 'species', 'age', 'location_name', 'latitude' and 'longitude'.
# Pick a tree from: https://en.wikipedia.org/wiki/List_of_trees
tree = {
"name":"Herbie",
"species":"Ulmus americana",
"age":212,
"location_name":"Yarmouth, Maine",
"latitude":43.8006,
"longitude": -70.1867
}
#print(tree.keys())
#2) Print the sentence "{name} is a {years} year old tree that is in {location_name}"
print(tree["name"], "is a", tree["age"], "year old tree that is in", tree["location_name"])
#3) The coordinates of New York City are 40.7128° N, 74.0059° W. Check to see if the tree is south of NYC, and print
#"The tree {name} in {location} is south of NYC" if it is. If it isn't, print "The tree {name} in {location} is north of NYC"
print(tree["name"] + ", the tree in", tree["location_name"], "is north of NYC.")
#better to do an if else for this
nyc =
{
'latitude' : 40.7128
'longitude': -74.0059
}
if nyc['latitude'] < tree['latitude']:
print("The tree", tree['name'], "in", tree['location_name'], "is south of NYC")
#4) Ask the user how old they are. If they are older than the tree, display "you are {XXX} years older than {name}."
# If they are younger than the tree, display "{name} was {XXX} years old when you were born."
user_age = int(input("How old are you?"))
if user_age < tree["age"]:
print(tree["name"], "is roughly", (int(tree["age"]) - user_age), "years older than you are.")
#1) Make a list of dictionaries of five places across the world - (1) Moscow, (2) Tehran, (3) Falkland Islands, (4) Seoul,
#and (5) Santiago. Each dictionary should include each city's name and latitude/longitude (see note above).
#2) Loop through the list, printing each city's name and whether it is above or below the equator (How do you know?
#Think hard about the latitude.). When you get to the Falkland Islands, also display the message "The Falkland Islands are a biogeographical part of the mild Antarctic zone," which is a sentence I stole from Wikipedia.
#3) Loop through the list, printing whether each city is north of south of your tree from the previous section. |
# ALL ABOUT APIs
# darkskynet/dev/account
# https://api.darksky.net/forecast/13d3600a5cd0883a0f7c94181a175dd3/37.8267,-122.4233
#endpoint :: is a URL. the list of URLs you can talk to
#first, bring in the requests library
import requests
#module = library = package they're all the same
#use PIP to install packages/modules/library
#run this in the terminal ::: pip install requests
#define the URL you want
url = "https://api.darksky.net/forecast/13d3600a5cd0883a0f7c94181a175dd3/37.8267,-122.4233"
#hey requests, go get that url! and save the response as "response"
#"reponse" is now a dictionary. to check, print it! then you can see what a variable is
#to get what's in there, use .text or .content
response = requests.get(url)
print(response.text)
#what type of data is this?
# print(type(response.text))
#let's tell response to treat this as JSON
print(response.json)
#you get this error:
#<bound method Response.json of <Response [200]>>
#which means it needs parenthesis, so we write:
print(response.json())
data = response.json()
#what kind of data type is it?
print(type(data))
#look at the keys, because it's kind of like a dictionary
print(data.keys())
#one of them is currently, so we can do data['currently']
print(data['currently'])
#inside of currently (which is inside of data), let's look at the temperature
print(data['currently']['temperature'])
#run jupyter notebook
#we're starting a server on our computer ctrl c will stop it if you want
#we get to the server by going to the browser and go to: localhost:8888. it's opened in the same directory you were in
|
#! /usr/bin/python3
def count_vowel(s):
vowels = ['u', 'e', 'o', 'a', 'i']
ret = 0
for i in s:
if i in vowels:
ret += 1
return ret
msg = input('Enter a String: ')
print('The number of vowels : {}'.format(countVowel(msg)))
|
'''
Created on May 23, 2016
Simulated Annealing
When the cost is higher, the new solution can still become the current solution with certain probability.
This aims at avoiding local optimum.
The temperature - willingness to accept a worse solution
When the temperature decreases, the probability of accepting a worse solution is less
'''
import random
import math
def simulated_annealing(domain, costf, dest, people, flights, T = 10000.0, cooling_rate = 0.95, step = 1):
# random initialization
rs = [random.randint(domain[i][0], domain[i][1]) for i in range(len(domain))]
while T > 0.1:
new_dir = random.randint(-step, step)
# randomly choose one of the index
idx = random.randint(0, len(domain) - 1)
rsc = rs
rsc[idx] += new_dir
if rsc[idx] < domain[idx][0]: rsc[idx] = domain[idx][0]
if rsc[idx] > domain[idx][1]: rsc[idx] = domain[idx][1]
pre_cost = costf(rs, dest, people, flights)
curr_cost = costf(rsc, dest, people, flights)
p = pow(math.e, (-pre_cost-curr_cost)/T)
if (curr_cost < pre_cost or random.random() < p):
rs = rsc
T *= cooling_rate
return rs, curr_cost
|
"""
This script is parsing data exported from Apple Health app in order to count steps made per day. The number of steps is then writen into a CSV file. Some mock data could be found on my GitHub: github.com/hsarka
A blog post with visualization could be seen on my blog sarka.hubacek.uk
"""
import xmltodict
import csv
with open("healthMockData.xml") as fd:
doc = xmltodict.parse(fd.read())
doc["HealthData"]
# recordList contains only data from this part of the xml file
recordList = doc["HealthData"]["Record"]
# making an empty dictionary to fill up later with dates and steps
records = {}
# iterating record by record in recordList to find the "step count" records
for record in recordList:
# choosing only the record type "step count"
if record["@type"] == "HKQuantityTypeIdentifierStepCount":
# strip the date to YYYY-MM-DD format
tempKey = "%.10s" % record["@startDate"]
# if the key is in records dict, add new value to the current value
if tempKey in records:
records[tempKey] = int(records[tempKey]) + int(record["@value"])
# if the key is not there yet, make a new entry
else:
records[tempKey] = int(record["@value"])
# write parsed data to CSV file
header = ["date", "steps"]
with open("stepCountMockData.csv", mode="w") as f:
writer = csv.writer(f, delimiter=",")
writer.writerow(header)
for key in records.keys():
f.write("%s,%s\n"%(key,records[key])) |
#!/bin/python3
adhoc=[1,2,3,1,4,5,66,22,2,6,0,9]
x=[]
y=[]
print("1. Numbers greater than 5 :")
for i in adhoc:
if i>5:
print(i)
x.append(i)
print("2. Numbers less than or equal to 2 : ")
for i in adhoc :
if i <=2 :
print(i)
y.append(i)
print("List 1 is :",x)
print("List 2 is :",y)
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def vector_add(v1: list, v2: list):
"""Vector addition"""
assert len(v1) == len(v2)
return [x + y for x, y in zip(v1, v2)]
def vector_scal(scalar, v: list):
"""Scalar multiplication of a vector"""
return [scalar * x for x in v]
def vector_is_zero(v):
"""Tests if v is the zero vector."""
return all([not e for e in v])
def vectors_are_inde(v1: list, v2: list):
"""Tests if v1 and v2 are independant vectors."""
assert len(v1) == len(v2)
if vector_is_zero(v1):
return not vector_is_zero(v2)
else:
i = 0
while not v1[i]:
i += 1
if not v2[i]:
return True
else:
v1_reduced = vector_scal(v1[i].inverse() * v2[i], v1)
return v1_reduced != v2
def reduced_row_echelon_form(system: list):
"""Returns the reduced row echelon form of matrix `system`
using Gaussian elimination"""
p = len(system)
q = len(system[0])
for col in range(q):
i = col
while i < p and not system[i][col]:
i += 1
if i != p:
system[i], system[col] = system[col], system[i]
k = system[col][col].inverse()
system[col] = vector_scal(k, system[col])
for j in range(p):
if j != i:
l = vector_scal(-system[j][col], system[col])
system[j] = vector_add(system[j], l)
return system |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from elliptic_curves.elliptic_curve import EllipticCurve
from structures.fields.finite import FiniteField
from maths.math_lib import gcd
from maths.primes import primes_range
from math import log
from IFP.primepower import isprimepower
from primality.prime import is_prime
from random import randrange
def randomCurve(p):
"""Returns a random curve on field `GF(p)` and a random point on it."""
x, y = randrange(1, p), randrange(1, p)
a = randrange(1, p)
b = (y ** 2 - x ** 3 - a * x) % p
field = FiniteField(p)
curve = EllipticCurve(field, a, b)
point = curve(x, y)
return curve, point
def ECMFactor(n, sieve, limit, times):
"""Finds a non-trivial factor of `n` using
the elliptic-curve factorization method"""
for _ in range(times):
g = n
while g == n:
curve, point = randomCurve(n)
g = gcd(n, curve.discriminant().remainder())
if g > 1:
return g
for prime in sieve:
prod = prime
i = 0
while prod < limit and i < 10:
i += 1
try:
point = prime * point
except ZeroDivisionError as e:
return gcd(e.args[1], n)
prod *= prime
return n
def ECM(n, times=5):
"""Returns the list of prime factors of `n`
using ECM factorization algorithm."""
factors = []
k = int(13 * log(n) ** 0.42)
bound = max(10 * k ** 2, 100)
sieve = primes_range(2, bound)
for prime in sieve:
q, r = divmod(n, prime)
while r == 0:
n = q
factors.append(prime)
q, r = divmod(n, prime)
root, power = isprimepower(n)
if power != 1:
return [root] * power
if is_prime(n):
return [n]
while n != 1:
factor = ECMFactor(n, sieve, bound, times)
factors += ECM(factor)
n //= factor
return sorted(factors)
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from maths.math_lib import gcd
from primality.prime import is_prime
def pollard_rho_search_floyd(f, n: int, x0=2):
"""Pollard's-rho algorithm to find a non-trivial
factor of `n` using Floyd's cycle detection algorithm."""
d = 1
tortoise = x0
hare = x0
while d == 1:
tortoise = f(tortoise)
hare = f(f(hare))
d = gcd(abs(tortoise - hare), n)
return d
def pollard_rho_search_brent(f, n: int, x0=2):
"""Pollard's-rho algorithm to find a non-trivial
factor of `n` using Brent's cycle detection algorithm."""
power = 1
lam = 0
tortoise = x0
hare = x0
d = 1
while d == 1:
if power == lam:
tortoise = hare
power *= 2
lam = 0
hare = f(hare)
d = gcd(abs(tortoise - hare), n)
lam += 1
return d
def pollard_brent_search(f, n: int, x0=2, size=100):
"""Pollard's-rho algorithm to find a non-trivial
factor of `n` using Brent's cycle detection algorithm,
and including the product speed improvment."""
power = 1
lam = 0
tortoise = x0
hare = x0
d = 1
while d == 1:
prod = 1
last_pos = hare
for c in range(size):
if power == lam:
tortoise = hare
power *= 2
lam = 0
hare = f(hare)
lam += 1
prod = (prod * abs(tortoise - hare)) % n
d = gcd(prod, n)
if not (is_prime(d)):
return pollard_rho_search_brent(f, n, last_pos)
else:
return d
def pollard_rho(n: int):
"""Pollard's-rho algorithm to find the factorization of `n`
using Brent's cycle detection algorithm, and including
the product speed improvment."""
f = lambda x: (x ** 2 + 1) % n
factors = []
while not (is_prime(n)):
x0 = 2
factor = pollard_brent_search(f, n)
while factor == n:
x0 += 1
factor = pollard_brent_search(f, n)
factors.append(factor)
n //= factor
if n != 1:
factors.append(n)
return factors |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from structures.rings import CommutativeRingElement
class FieldElement(CommutativeRingElement):
"""
A base class for field elements that provides default operator overloading.
"""
def __truediv__(self, other):
other = self.field()(other)
return self.__mul__(other.inverse())
def __rtruediv__(self, other):
return self.inverse() * other
def __pow__(self, n):
n = int(n)
if n < 0:
return self.inverse().__pow__(-n)
else:
return super().__pow__(n)
def inverse(self):
raise NotImplementedError
def ring(self):
raise NotImplementedError
def field(self):
return self.ring() |
"""
Challenge #4:
Create a function that takes length and width and finds the perimeter of a
rectangle.
Examples:
- find_perimeter(6, 7) ➞ 26
- find_perimeter(20, 10) ➞ 60
- find_perimeter(2, 9) ➞ 22
"""
# Input, Output both int, no type conversion
# length and width of a rectangle, 4 sides, 2 length, 2 width
# Perimeter is the sum of all the sides.
# Expand: no negative values can be passed in
# if length < 0 or width < 0:
# return 0
def find_perimeter(length, width):
return (2 * length) + (2 * width)
#Examples
print(find_perimeter(6, 7))
print(find_perimeter(20, 10))
print(find_perimeter(2, 9))
|
# Program to send emails from python
# Written in Python 3.3
import smtplib
import getpass
def send_mail(username, password, serv):
# Asks for the from email address, the to email address and then the
# messages
from_email = input('From Email : ')
to_email = input('To Email : ')
message = input('Message: ')
# Sends message
server = smtplib.SMTP(serv)
server.starttls()
server.login(username,password)
server.sendmail(from_email, to_email, message)
#Confirmation message
print("Sent email to " + to_email)
server.quit()
if __name__ == "__main__":
# Asks for username and password
username = input('Username : ')
password = getpass.getpass()
provider = input('Gmail, Outlook, or Hotmail: ')
provider = provider.strip().lower()
if provider == 'gmail':
serv = 'smtp.gmail.com:587'
elif provider == 'outlook' or provider == 'hotmail':
serv = 'smtp.live.com:587'
send_mail(username, password, serv)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
s = 'hi hello, world.'
b = list(s)
# print('b=',b)
# to remove , and . (nutzlich mit Worter, die mit /def/ anfangen, damit g nicht , oder . sein)
a = s.split(' ')
# print('a=',a)
c = ' '.join(a)
# print(c)
# for i in a:
# if (i.endswith(',')) or (i.endswith('.')):
# a[a.index(i)] = i[:len(i)-1]
# print('a=',a)
# Analyse:
s = 'Noch wird \abc nicht veraendert. Aber jetzt kommt eine Makrodefinition \def\abc?abcA\?B\?Cabc?, die dann hier \abc zu einer Textersetzung f�hrt.'
# ss = s.encode(encoding='UTF-8', errors='strict')
# ss = s.decode('utf8')
print(s)
# a = s.split(' ')
# for i in a:
# # if(i.startswith('\def\\')):
# # if(i[1:4]=='def'):
# print(i)
print('\def\\')
|
##Recursive Function to print out the digits of a number in English
## By: Piranaven Selva
##NumToEng.py
def Numtoeng(Number):
English = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}
Number=str(Number)
if len(Number) == 0:
return
else:
first = int(Number[0])
english = English[first]
print(english, end= " ")
Numtoeng(Number[1:])
|
# calculator.py
# A program that asks the user for an expression
# and then prints out the value of the expression
# by: Piranaven Selvathayabaran
def main():
x=eval(raw_input("Give me an expression:"))
print("The value is: "+ x)
main()
|
# distance.py
# Program that computes the distance between two points
from math import*
def main():
print("This program calculates th distance between two coordinates.")
cx1,cy1=eval(input("Please enter the first coordinate point (x1,y1): "))
cx2,cy2=eval(input("Please enter the second coordinate point (x2,y2): " ))
distance=(sqrt(((cx2-cx1)**2)+((cy2-cy1)**2)))
float(distance)
print("The distance between the two points is : ",distance)
main()
|
"""
File: stack.py
Stack implementations
"""
from arrays import Array
class ArrayStack(object):
""" Array-based stack implementation."""
DEFAULT_CAPACITY = 10 # Class variable for all array stacks
def __init__(self):
self._items = Array(ArrayStack.DEFAULT_CAPACITY)
self._top = -1
self._size = 0
def push(self, newItem):
"""Inserts newItem at top of stack."""
# Resize array if necessary
if len(self) == len(self._items):
temp = Array(2 * self._size)
for i in xrange(len(self)):
temp[i] = self._items[i]
self._items = temp
# newItem goes at logical end of array
self._top += 1
self._size += 1
self._items[self._top] = newItem
def pop(self):
"""Removes and returns the item at top of the stack.
Precondition: the stack is not empty."""
oldItem = self._items[self._top]
self._top -= 1
self._size -= 1
# Resizing the array is an exercise
return oldItem
def peek(self):
"""Returns the item at top of the stack.
Precondition: the stack is not empty."""
return self._items[self._top]
def __len__(self):
"""Returns the number of items in the stack."""
return self._size
def isEmpty(self):
return len(self) == 0
def __str__(self):
"""Items strung from bottom to top."""
result = ""
for i in xrange(len(self)):
result += str(self._items[i]) + " "
return result
from node import Node
class LinkedStack(object):
""" Link-based stack implementation."""
def __init__(self):
self._top = None
self._size = 0
def push(self, newItem):
"""Inserts newItem at top of stack."""
self._top = Node(newItem, self._top)
self._size += 1
def pop(self):
"""Removes and returns the item at top of the stack.
Precondition: the stack is not empty."""
oldItem = self._top.data
self._top = self._top.next
self._size -= 1
return oldItem
def peek(self):
"""Returns the item at top of the stack.
Precondition: the stack is not empty."""
return self._top.data
def __len__(self):
"""Returns the number of items in the stack."""
return self._size
def isEmpty(self):
return len(self) == 0
def __str__(self):
"""Items strung from bottom to top."""
# Helper recurses to end of nodes
def strHelper(probe):
if probe is None:
return ""
else:
return strHelper(probe.next) + \
str(probe.data) + " "
return strHelper(self._top)
def main():
# Test either implementation with same code
s = ArrayStack()
#s = LinkedStack()
print "Length:", len(s)
print "Empty:", s.isEmpty()
print "Push 1-10"
for i in xrange(10):
s.push(i + 1)
print "Peeking:", s.peek()
print "Items (bottom to top):", s
print "Length:", len(s)
print "Empty:", s.isEmpty()
print "Push 11"
s.push(11)
print "Popping items (top to bottom):",
while not s.isEmpty(): print s.pop(),
print "\nLength:", len(s)
print "Empty:", s.isEmpty()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
class BinarySearch():
def chop(self, value, array):
if len(array) == 0:
return -1
i = 0
k = len(array) - 1
while k - i > 1:
mid = i + (k - i) / 2
if array[mid] == value:
return mid
elif array[mid] < value:
i = mid
else:
k = mid
if (value == array[i]):
return i
elif(value == array[k]):
return k
else:
return -1
|
#!/usr/bin/env python3
import argparse
import math
def ms10(x):
return math.floor(x * x / 100000) % int(math.pow(10, 10))
def neumann(n):
succ = n * n
succ_str = str(succ)
if len(succ_str) < 20:
succ_str = '0'*(20-len(succ_str)) + succ_str
if len(succ_str) == 20:
succ = int(succ_str[5:15])
else:
succ = -1
return succ
def main():
parser = argparse.ArgumentParser(description='10 digits PRNG')
parser.add_argument("N", help="apply middle number algorithm to N", type=int)
parser.add_argument("times", help="how many times the algorithm is applied", type=int)
args = parser.parse_args()
curr = args.N
for i in range(args.times):
curr = ms10(curr)
print(curr)
if __name__ == "__main__":
main()
|
import hashlib
mystring = input('Enter String to hash: ')
# Assumes the default UTF-8
hash_object = hashlib.md5(mystring.encode())
print(hash_object.hexdigest()) |
def CheckVowels(s):
if s=='a' or s== 'e' or s== 'i' or s== 'o' or s== 'u':
return True
else:
return False
vchar=input('Enter any character ')
Ans=CheckVowels(vchar)
print(Ans)
|
import sys
# 算个税
class TaxCalculator:
def __init__(self):
self.degree_array = [0, 3000, 12000, 25000, 35000, 55000, 80000]
self.tax_rate_array = [0.03, 0.1, 0.2, 0.25, 0.3, 0.35, 0.45]
def calculate_tax(self, salary):
if salary <= 5000:
return 0
else:
tax_value = 0
tax_part = salary - 5000
for index in range(len(self.degree_array)):
if tax_part <= self.degree_array[index]:
tax_value += (tax_part-self.degree_array[index-1]) * self.tax_rate_array[index-1]
for i in range(1, index):
tax_value += (self.degree_array[i]-self.degree_array[i-1])*self.tax_rate_array[i-1]
return tax_value
else:
if index == len(self.degree_array)-1:
tax_value += (tax_part-self.degree_array[-1])*self.tax_rate_array[-1]
for i in range(1, index+1):
tax_value += (self.degree_array[i] - self.degree_array[i-1]) * self.tax_rate_array[i-1]
return tax_value
def down_4_up_5(self, num):
if (num - 0.5) >= int(num):
return num + 1
else:
return num
if __name__ == "__main__":
# 读取第一行的n
tax_calc = TaxCalculator()
res = []
n = int(sys.stdin.readline().strip())
for i in range(n):
line = sys.stdin.readline()
salary = int(line)
tax = int(tax_calc.down_4_up_5(tax_calc.calculate_tax(salary)))
res.append(tax)
for tax in res:
print(tax) |
"""
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
"""
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = []
N = len(nums)-1
if N < 2:
return res
div_pos = -1
for i, num in enumerate(nums):
if num >= 0:
div_pos = i
break
# print(nums)
# print(div_pos)
if div_pos == -1:
return res
if sum([int(n == 0) for n in nums]) >= 3:
res.append([0, 0, 0])
for l_index in range(div_pos):
target = -nums[l_index]
start = div_pos
end = N
while start < end:
i, j = self.edgeSearch(target, nums, start, end)
if i > -1 and j > -1:
res.append([nums[l_index], nums[i], nums[j]])
start = i+1
end = j-1
else:
break
for r_index in range(div_pos, N+1):
target = -nums[r_index]
start = 0
end = div_pos-1
while start < end:
i, j = self.edgeSearch(target, nums, start, end)
if i > -1 and j > -1:
res.append([nums[i], nums[j], nums[r_index]])
start = i+1
end = j-1
else:
break
res.sort()
# print(res)
tmp_pos = 0
while tmp_pos < len(res)-1:
if res[tmp_pos+1] == res[tmp_pos]:
del res[tmp_pos+1]
else:
tmp_pos += 1
return res
def edgeSearch(self, target, nums, i, j):
while i < j:
if nums[i] + nums[j] == target:
return i, j
elif nums[i] + nums[j] > target:
j -= 1
else:
i += 1
return -1, -1
if __name__ == "__main__":
solution = Solution()
# print(solution.threeSum([-1,0,1,2,-1,-4]))
print(solution.threeSum([0, 0, 0])) |
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
tmpNode1 = pHead1
tmpNode2 = pHead2
count1 = count2 = 0
while tmpNode1:
count1 += 1
tmpNode1 = tmpNode1.next
while tmpNode2:
count2 += 1
tmpNode2 = tmpNode2.next
long_step = count1 - count2
if long_step > 0:
for i in range(long_step):
pHead1 = pHead1.next
else:
for i in range(-long_step):
pHead2 = pHead2.next
while pHead1 and pHead2:
if pHead1 == pHead2:
break
else:
pHead1 = pHead1.next
pHead2 = pHead2.next
return pHead1
|
"""
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
"""
#coding=utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 迭代 60ms
# def reverseList(self, head):
# """
# :type head: ListNode
# :rtype: ListNode
# """
# if not head:
# return None
# elif not head.next:
# return head
#
# preNode = None
# actNode = head
# nextNode = head.next
# while nextNode:
# tmpNode = nextNode.next
# actNode.next = preNode
# preNode = actNode
# actNode = nextNode
# nextNode = tmpNode
# actNode.next = preNode
# return actNode
# 递归? 56ms
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
elif not head.next:
return head
preNode = None
actNode = head
nextNode = head.next
return self.recur(preNode, actNode, nextNode)
def recur(self, preNode, actNode, nextNode):
if nextNode:
tmpNode = nextNode.next
actNode.next = preNode
preNode = actNode
actNode = nextNode
nextNode = tmpNode
return self.recur(preNode, actNode, nextNode)
else:
actNode.next = preNode
return actNode
def printLinkList(head):
while head:
print('%f\n' % head.val)
head = head.next
if __name__ == "__main__":
solution = Solution()
# head = None
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
new_head = solution.reverseList(head)
printLinkList(new_head)
|
"""
判断5张扑克牌是否为顺子,大小王为0,可以代替任意数字
"""
# -*- coding:utf-8 -*-
import Sort_QuickSort
class Solution:
def IsContinuous(self, numbers):
# write code here
if not numbers:
return False
Sort_QuickSort.quick_sort(numbers)
zero_count = 0
diff_count = 0
for i in range(len(numbers)):
if numbers[i] == 0:
zero_count += 1
elif i == len(numbers)-1:
break
else:
if numbers[i+1] == numbers[i]:
return False
diff_count += (numbers[i+1] - numbers[i] - 1)
if diff_count <= zero_count:
return True
return False
|
'''
直接插入排序
时间复杂度:O(n²)
空间复杂度:O(1)
稳定性:稳定
基本操作是将后面一个记录插入到前面已经排好序的有序表中
'''
def insert_sort(array):
for i in range(1, len(array)):
if array[i] < array[i-1]:
j = i-1
tmp = array[i]
while j >= 0 and tmp < array[j]:
array[j+1] = array[j]
j -= 1
array[j+1] = tmp
return array
if __name__ == "__main__":
print(insert_sort([3, 6, 1, 2, 8, 4, 9, 9, 10, 8]))
print(insert_sort([]))
|
def Move(direction, current_position):
"""
args: direction - contains the letter for the direction the user wanted to move to.
current_postion - x and y for the current postion the user is at
feat: updates the user position according to the user's input
"""
if direction =='n' and current_position[0] != 0:
current_position[0] -= 1
elif direction =='e' and current_position[1] != 4:
current_position[1] += 1
elif direction == 's' and current_position[0] != 4:
current_position[0] += 1
elif direction == 'w' and current_position[1] != 0:
current_position[1] -= 1 |
from Course import Course
from Student import Student
from DILevel import Level_3_Students
import os
class School(Course,Level_3_Students ,Student):
def __init__(self):
self.file1_data = []
self.file2_data = []
self.file3_data = []
''' Section 1: PASS Level
Read from a file specified in command line,
create a list of Student
objects and a list of Course objects. '''
def read_level_1_file(self, file):
self.score_data = self.read(file)
self.generate_table(self.score_data)
avg_of_top_result = self.calculate_average(self.score_data)
print(avg_of_top_result)
# To calculate average score of the student with the top score
def calculate_average(self, score_data):
formatted_array = self.reformat_data(self.score_data)
# print(formatted_array)
data_to_calculate_avg = [[j for j in i if type(j) != str] for i in formatted_array]
avg = [sum(i) // len(i) if (len(i) != 0) else " " for i in data_to_calculate_avg]
record = {}
for i in range(len(formatted_array)):
if (type(avg[i] == int)):
record[formatted_array[i][0]] = avg[i]
else:
record[formatted_array[i][0]] = 0
p = sorted(record.items(), key=lambda x: x[1])
output = "{} students, {} courses the top student is {}, average is {}".format(len(p),
len(formatted_array[0]) - 1,
p[-1][0], p[-1][1])
return output
# To generate a table for Pass Level
def generate_table(self, score_data):
d = self.score_data[0][0]
d = d.split()
d[0] = " "
d = [[i for i in d]]
table = self.reformat_data(self.score_data)
table = d + table
# print(table)
for i in table[:1]:
print("{:<8} | {:<10} | {:<10} | {:<10} | {:<10}".format(i[0], i[1], i[2], i[3], i[4]))
print("{:<8} | {:<10} | {:<10} | {:<10} | {:<10}".format('________', '__________', '__________', '__________',
'__________'))
for i in table[1:]:
print("{:<8} | {:<10} | {:<10} | {:<10} | {:<10}".format(i[0], i[1], i[2], i[3], i[4]))
print("{:<8} | {:<10} | {:<10} | {:<10} | {:<10}".format('________', '__________', '__________', '__________',
'__________'))
# To reforamt the data in the rows
def reformat_data(self, score_data):
formatted_array = []
# print(score_data)
for i in score_data[1:]:
x = []
for j in i:
x.append(j.split()[0])
for k in j.split()[1:]:
if k.isnumeric() and (0 <= int(k) <= 100):
x.append(int(k))
elif (int(k) == 888):
x.append("--")
else:
x.append(" ")
formatted_array.append(x)
# print(formatted_array)
return formatted_array
# Level-2 Implementation
# To read scores from scores.txt and course.txt
''' Section 2: CREDIT Level
At this level, program can support two types of courses. One is Compulsory Course.
Compulsory courses may have different credit points. Another type is Elective Course.
All elective courses have the same credit point.'''
def read_level_2_files(self, file1, file2):
self.file1_data = self.reformat_data(self.read(file1))
self.file2_data = (self.read(file2))
self.create_course_object()
# To create courses object
def create_course_object(self):
self.formatted_course_object = []
for i in self.file2_data:
c = ",".join(i)
self.formatted_course_object.append(c)
# print(self.formatted_course_object)
marks_of_course = self.calculate_average_of_courses(self.file1_data)
for i in range(len(self.formatted_course_object)):
self.formatted_course_object[i] += " " + str(len(marks_of_course[i]))
self.formatted_course_object[i] += " " + str(sum(marks_of_course[i]) // len(marks_of_course[i]))
# print(self.formatted_course_object)
for i in range(len(self.formatted_course_object)):
self.formatted_course_object[i] = self.formatted_course_object[i].split()
# print(self.formatted_course_object)
self.list_course_object = self.create_list_course_object()
self.list_course_object[0].get_course_summary(self.list_course_object)
# To create list of course objects
def create_list_course_object(self):
total_course = []
for i in range(len(self.formatted_course_object)):
id = self.formatted_course_object[i][0]
name = self.formatted_course_object[i][1]
type = self.formatted_course_object[i][2]
credit = self.formatted_course_object[i][3]
enroll = self.formatted_course_object[i][4]
average = self.formatted_course_object[i][5]
d = Course(id, name, type, credit, enroll, average)
total_course.append(d)
return total_course
# Calculate marks for each course
def calculate_average_of_courses(self, score_file):
course_marks = []
for i in range(1, len(score_file[0])):
x = [j[i] for j in score_file if j[i] != " "]
course_marks.append(x)
# print(course_marks)
return course_marks
# Level-3 Implementation
# Read data from scores.txt, courses.txt, student.txt
''' Section 3: DI Level ---
At this level, program can support two types of Students, full time students (FT) and part time
students (PT). A full time student is required to enrol in at least 3 compulsory courses. A part time
student is required to enrol in at least 2 compulsory courses.'''
def read_level_3_files(self, file1, file2, file3):
self.file1_data = self.reformat_data(self.read(file1))
self.file2_data = (self.read(file2))
self.file3_data = (self.read(file3))
self.create_student_object()
# Create student object
def create_student_object(self):
c = []
for i in range(len(self.file3_data)):
c = ",".join(self.file3_data[i])
c = c.split(" ")
self.file3_data[i] = c
self.list_students_object = self.create_list_student_object()
self.list_students_object[0].get_student_report_table(self.list_students_object)
# Create list of student objects
def create_list_student_object(self):
final = self.create_student_data()
total_student = []
for i in range(len(final)):
id = final[i][0]
name = final[i][1]
student_type = final[i][2]
enrolled = final[i][3]
main_enrolled = final[i][4]
gpa = final[i][5]
d = Level_3_Students(id, name, student_type, enrolled, main_enrolled, gpa)
total_student.append(d)
return total_student
# Fetch details of the student like sid, name, marks
def create_student_data(self):
self.res = []
for i in self.file1_data:
d = i[1:]
self.res.append(d)
print(self.res)
res = self.calculate_gpa(self.res)
number_of_courses = res[0]
gpa_of_student = res[1]
number_of_compulsory_course = res[2]
for i in range(len(self.file1_data)):
self.file3_data[i].append(number_of_courses[i])
self.file3_data[i].append(number_of_compulsory_course[i])
self.file3_data[i].append(gpa_of_student[i])
print(self.file3_data)
return self.file3_data
# This method willl return list of GPA , Total courses Enrolled , compulsory course enrolled by students
def calculate_gpa(self, c):
gpa = []
main_enrolled_list = [[j for j in i[:-1] if type(j) != str] for i in c]
main_enrolled = [len(i) for i in main_enrolled_list]
c = [[j for j in i if type(j) != str] for i in c]
# print(c)
enrolled = [len(i) for i in c]
# print(enrolled)
for i in c:
x = 0
for j in i:
x += self.get_gpa(j)
final = round(x / len(i), 2)
gpa.append(final)
print(gpa)
return [enrolled, gpa, main_enrolled]
# Level 4 implementation starts from here
'''Section 4: HD Level
At this level, your program can handle some variations in the files.'''
def read_level_4_files(self, file1, file2, file3):
self.file1_data = self.read(file1)
self.file2_data = self.read(file2)
self.file3_data = self.read(file3)
a = self.format_array(self.file1_data)
self.b = self.format_array(self.file2_data)
c = self.format_array(self.file3_data)
list = self.sort_file(a, c)
self.a = list[0]
self.c = list[1]
res = self.credit_point()
self.individual_credit = res[0]
self.individual_GPA = res[1]
self.compulsion_enrolled = res[2]
self.crpt = res[3]
# print(self.individual_credit)
# print(self.individual_GPA)
# print(self.compulsion_enrolled)
# print(self.c)
self.level4_object = self.create_final_report_object()
self.level4_object[0].get_student_report_table(self.level4_object)
# creating final report object
def create_final_report_object(self):
self.c = self.create_final_report_list()
list_of_di_object = []
for i in range(len(self.c)):
id = self.c[i][0]
name = self.c[i][1]
student_type = self.c[i][2]
credits = self.c[i][6]
compulsion_enrolled = self.c[i][4]
gpa = self.c[i][5]
d = Student(id, name, student_type, credits, compulsion_enrolled, gpa)
list_of_di_object.append(d)
return list_of_di_object
# Creating list in - order to create final list of object
def create_final_report_list(self):
for i in range(len(self.c)):
self.c[i].append(self.individual_credit[i])
self.c[i].append(self.compulsion_enrolled[i])
self.c[i].append(self.individual_GPA[i])
self.c[i].append(self.crpt[i])
self.c.sort(reverse=True, key=lambda x: x[6])
return self.c
# This method will return list consisting of student credit, gpa, compulsory course
def credit_point(self):
course_credit = [int(j[3]) for j in self.b]
res = self.formatting_final_report_data(self.a)
marks_of_student = res[0]
compulsion_enrolled = res[1]
individual_credit = []
gpa = []
Crpt = []
for i in marks_of_student:
credit = 0
d = 0
crpt = 0
for j in range(len(i)):
if type(i[j]) != str:
d += i[j] * course_credit[j]
credit += course_credit[j]
if (i[j] > 0):
crpt += course_credit[j]
Crpt.append(crpt)
d = round((d / credit), 2)
individual_credit.append(credit)
gpa.append(d)
return [individual_credit, gpa, compulsion_enrolled, Crpt]
# This method will validate the score of student
def formatting_final_report_data(self, a):
final_score = []
for i in a[1:]:
d = []
for j in i[1:]:
if j == "TBA":
d.append("-")
elif j.isalpha():
d.append(" ")
elif str(int(float(j))).isnumeric():
c = self.get_gpa(int(float(j)))
d.append(c)
final_score.append(d)
course_enrolled = [[j for j in i[:-1] if type(j) != str] for i in final_score]
compulsion_enrolled = [len(i) for i in course_enrolled]
return [final_score, compulsion_enrolled]
# This method will get the gpa according to marks of the stdent
def get_gpa(self, a):
if a >= 80:
return 4
elif 70 <= a <= 79:
return 3
elif 60 <= a <= 69:
return 2
elif 50 <= a <= 59:
return 1
else:
return 0
# Format array
@staticmethod
def format_array(file):
c = []
for i in range(len(file)):
c = ",".join(file[i])
c = c.split(" ")
file[i] = c
return file
# sort file
@staticmethod
def sort_file(a, c):
a.sort()
c.sort()
return [a, c]
# To read data from file and generate a nested list of the rows
@staticmethod
def read(file):
list_of_rows_from_file = []
if os.stat(file).st_size == 0:
# print("File Contents is empty")
exit("File Contents is empty")
with open(file, "r") as content:
for line in content:
rows = []
i = line.strip()
rows.append(i)
# print(i , rows)
list_of_rows_from_file.append(rows)
return list_of_rows_from_file
|
# -*- coding:utf-8 -*-
'''获取文件中存储的cookie'''
def read_cookie():
with open('cookie_file', 'r', encoding='utf-8') as f: # 打开文件
line = f.readline() # 读取所有行
f.close()
return line
'''更新文件中存储的cookie'''
def write_cookie():
temp = input("请更新在谷歌浏览器登录weibo.cn时所获取的cookie(输入n/N不更新cookie):")
if (temp == 'n' or temp == 'N'):
return
cookie = temp
with open('cookie_file', 'w', encoding='utf-8') as f: # 打开文件
f.write(cookie)
f.close()
return cookie
|
from modules.Geometry import Point
from modules.Utils import vector
import math
class Line2D:
# general Equation of line ax + by +c =0
def __init__ (self):
self.a = 0
self.b = 0
self.c = 0
def newLine ( a, b, c):
ln = Line2D()
ln.a = a
ln.b = b
ln.c = c
return ln
def getLine( pt1 , pt2):
line = Line2D()
x1 = pt1[0]
y1 = pt1[1]
x2 = pt2[0]
y2 = pt2[1]
line.a = (y2-y1)
line.b = (x1-x2)
line.c = -1*(x1*(line.a) + y1*(line.b))
return line
def getLinePoint(pt1, pt2):
return Line2D.getLine((pt1.x,pt1.y),(pt2.x,pt2.y))
def getY(self, x):
if self.b == 0:
if self.a * x == int (-1*self.c):
return math.inf
else :
return None
return int(-1*round((float(self.a*x+self.c)/float(self.b)),0))
def getX (self,y):
if self.a == 0:
if self.b*y == int (-1*self.c):
return math.inf
else :
return None
return int(-1*round((float(self.b*y+self.c)/float(self.a)),0))
def getDistance(self, point):
mod = math.sqrt( self.a**2 + self.b**2)
value = float (abs( self.a*point.x + self.b*point.y + self.c ))
return value/mod;
def equate ( eq1, eq2):
base = eq2.b * eq1.a - eq1.b * eq2.a
num1 = eq1.c * eq2.a - eq2.c * eq1.a # num of y
num2 = eq1.c * eq2.b - eq2.c * eq1.b # num of x
#case many solution
if ( base == 0 and num1 ==0 ):
return 1, -1*((eq1.c + eq1.a)/eq1.b)
if ( base == 0 and num1 !=0 and num2 !=0):
return None , None
if ( base != 0):
return num2/base, -1*num1/base
def printLine(self):
print (self.a, self.b, self.c)
class Line3D:
def __init__ (self):
self.pos = vector.vector3D()
self.dir = vector.vector3D()
def line3D(pt1, pt2):
self.pos = pt1.pointToVec()
self.dir = vector.vector3D.getUnitVector(vector.vector3D.getVector3D(pt1, pt2))
def line3D( vec1 , vec2 ):
ln = Line3D()
ln.pos = vec1
ln.dir = vector.vector3D.getUnitVector(vector.vector3D.subVector(vec1, vec2))
return ln
def newLine ( pos, direction ):
ln = Line3D()
ln.pos = pos
ln.dir = vector.vector3D.getUnitVector(direction )
return ln
def onLine ( vec1 , line ):
temp = vector.vector3D.subVector(line.pos , vec1)
return vector.vector3D(temp, line.dir)
def isParallel ( ln1 , ln2):
return vector.vector3D.isParallel(ln1.dir,ln2.dir)
def isConcurrent ( ln1 , ln2 ):
if (isParallel(ln1, ln2) and onLine(ln1, ln2.pos)):
return True
return False
def getDistancePoint ( ln , pt ):
return getDistance(ln, pt.pointToVec())
def getDistance ( ln , vec):
vec = vector.vector3D.subVector(vec, ln.pos)
return vector.vector3D.crossProduct(vec, ln.dir).getMagnitude()
def getDistanceLines ( ln1, ln2 ):
vec = vector.vector3D.crossProduct(ln1.dir, ln2.dir)
return vector.vector3D.crossProduct(vec, vector.vector3D.subVector(ln1.pos,ln2.pos)).getMagnitude()
def printLine(self):
print("Axis")
self.dir.printVector()
print("Position")
self.pos.printVector()
def getMinimumDisPoints (ln1, ln2):
a = ln1.dir.dotProduct(ln2.dir)
c1 = ln1.dir.dotProduct(ln1.pos) - ln1.dir.dotProduct(ln2.pos)
c2 = ln2.dir.dotProduct(ln1.pos) - ln2.dir.dotProduct(ln2.pos)
"""
ln1.dir += (di,0,dj)
delta c1
"""
"""
tTo solve the equation we consider two arbitary point on the system
lamda nad nue two variable
(a1 - a2).L1 =0
(a1 -a2).L2 = 0
a1.L1 = L1.L1 x - pos1.L1 = 0
a2.L1 = L2.L1 x - pos2.L1 = 0
therefore
eq1 = x - ay = c1
eq2 = ax - y = c2
solution of x and y are value of lambda and nue
"""
eq1 = Line2D.newLine(1, -1*a , -1*c1)
eq2 = Line2D.newLine(a, -1, -1*c2 )
t , u = Line2D.equate( eq1 ,eq2)
# if no nearest point exist
if ( t == None and u == None):
return None , None
vec1 = vector.vector3D.addVector(ln1.pos,vector.vector3D.scalerMultpy(ln1.dir, t))
vec2 = vector.vector3D.addVector(ln2.pos, vector.vector3D.scalerMultpy(ln2.dir, u))
return vec1 , vec2
|
import math
class vector:
def __init__(self, x = 0, y =0 ):
self.x = (x)
self.y = (y)
def unitVector(self):
mag = self.getModulus()
if mag == float(0):
return (vector2D())
return vector2D(self.x/mag, self.y/mag)
def getModulus(self):
return math.sqrt( self.x **2 + self.y **2)
## return vector2D
def addVector( self, A):
return ( vector2D(self.x+A.x,self.y+A.y))
def scaledVector(self ,mag):
n = self.unitVector()
return (vector2D( mag * n.x , mag * n.y ))
def printVector(self):
print ( self.x , self.y)
|
def list_of_words(file_name):
"""Returns: the words in a text file in a list format"""
with open(file_name, 'r') as file :
words = file.read()
split_words = words.split()
return split_words
def hist_dictionary(words):
""" Retruns: the dictionary histogram
representation of a given list of words"""
dictionary = {}
for word in words:
if word in dictionary :
dictionary[word] += 1
else :
dictionary[word] = 1
return dictionary
def hist_list(words):
""" Retruns: the list of list histogram
representation of a given list of words"""
index = 0
count = 0
big_list = []
# starts with all words with a zero value
# when looping through split words, whenever the word exists,
# increase value by 1
for word in words:
if [word,count] not in big_list :
big_list.append([word,count])
for word in words:
for i in range(len(big_list)) :
if big_list[i][index] == word :
big_list[i][1] += 1
return big_list
def hist_tuple(words):
""" Retruns: the list of tuple histogram
representation of a given list of words"""
#frequency of each word
word_freq = []
for word in words:
word_freq.append(words.count(word))
#tuple A
big_tuple = []
for word in words:
if (word,words.count(word)) not in big_tuple :
big_tuple.append((word, words.count(word)))
return big_tuple
#tuple B
#https://programminghistorian.org/en/lessons/counting-frequencies
tuple_histogram = list(zip(words, word_freq))
unique_tuple = []
for pairs in tuple_histogram :
if pairs not in unique_tuple :
unique_tuple.append(pairs)
def hist_counts_list(words):
""" In progress : list of counts histogram..."""
with open('alice.txt') as file :
words = file.read()
split_words = words.split()
#counts_list
counts_list = []
for word in split_words:
if (split_words.count(word), [word]) not in counts_list:
for i in counts_list:
# if counts_list.index(i)[0] == split_words.count(word):
# counts_list.index(i)[1].append(word)
# else:
# counts_list.append((split_words.count(word),[word]))
print(counts_list.index(word))
def unique_words_dict(list) :
"""Returns: the number of unique words (types) in a list"""
count = 0
for _ in list :
count += 1
return count
def frequency_dict(word, histogram) :
"""Returns: The number of time a word got mentioned in a histogram """
return histogram[word]
def write_list(histogram) :
"""Writes the list of list histogram file to a .txt file """
with open('write_hist.txt', 'w') as file :
for word in histogram :
file.write(word[0] + ' ')
file.write(str(word[1])+ '\n')
def write_dict(histogram) :
"""Writes the dictionary histogram file to a .txt file """
with open('write_dict.txt', 'w') as file :
for k, v in histogram.items():
file.write(str(k) + ': '+ str(v) + '\n')
def analysis(histogram):
""" Analysis of the histogram """
sum = 0
for word in histogram :
sum += word[1]
print(f'sum: {sum}')
mean = sum/len(histogram)
print(f'mean: {mean}')
if __name__ == '__main__':
words = list_of_words('words.txt')
hist_dict = hist_dictionary(words)
histogram_list = hist_list(words)
histogram_tuple = hist_tuple(words)
unique_words_dict(hist_dict)
# print(frequency_dict('two',hist))
#analysis(hist)
# write_dict(hist)
|
import random
from histogram import hist_dictionary, hist_list, list_of_words
import sys
def sample_by_frequency(histogram):
"""
Input: Histogram of text file
Return : a random word based on the weight(occurence)
"""
tokens = sum(histogram.values())
rand = random.randrange(tokens)
for key, value in histogram.items():
if rand < value:
return key
rand -= value
def test():
"""
A test for sample_by_frequency histogram
"""
list_of_output = []
words_list = list_of_words(sys.argv[1])
#change the text file to a dictionary histogram
histogram = hist_dictionary(words_list)
#takes a random weighed sample from the histogram 1000x
#appends it to a list (list_of_output)
for _ in range(1000):
list_of_output.append(sample_by_frequency(histogram))
#changes the list_of_output list to a dictionary histogram
#prints out the result
final = hist_dictionary(list_of_output)
for key in final.keys():
print(f"{key}: {final[key]}")
if __name__ == '__main__':
words_list = list_of_words(sys.argv[1])
histogram = hist_dictionary(words_list)
test()
print(sample_by_frequency(histogram))
|
nr_stari = int(input("Introduceti numarul de stari: "))
nr_tranz = int(input("Introduceti numarul de tranzitii: "))
alf = input("Introduceti alfabetul (fara spatiu): ")
v_fin = input("Introduceti starile finale (cu virgula): ")
st_in = input("Introduceti starea initiala: ")
matrix = [""]*100
lista = []
# citim tranzitiile:
print("Cititi tranzitiile: ")
for i in range(nr_tranz):
a=input().split();
st_prec=a[0]
ch=a[1]
st_urm=a[2]
lista.append((st_prec, ch, st_urm))
AFD = []
coada_stari = []
coada_stari.append(st_in)
afd_fin = []
st = dr = 0
pos = -1
while st <= dr:
for ch_index in range(len(alf)): #pentru fiecare litera din alfabet
stare_in = coada_stari[st]
pos = pos + 1
for x in coada_stari[st]:
for nr in range(nr_tranz):
if x == lista[nr][0] and alf[ch_index] == lista[nr][1]:
if matrix[pos].find(lista[nr][2]) == -1:
matrix[pos] = matrix[pos] + lista[nr][2]
if matrix[pos] != "":
AFD.append((coada_stari[st], alf[ch_index], matrix[pos]))
if matrix[pos] not in coada_stari:
coada_stari.append(matrix[pos])
ok = 0
for x in range(len(matrix[pos])):
if matrix[pos][x] in v_fin.split(","):
ok = 1
if ok ==1:
afd_fin.append(matrix[pos])
if stare_in == st_in and st_in in v_fin.split(",") and st_in not in afd_fin:
afd_fin.append(st_in)
dr = dr + 1
st = st + 1
print(AFD)
print("Stari finale: ", end=" ")
print(afd_fin)
print("Starea initiala: " , st_in)
|
# First type of approach that came to mind
def solution1():
total = 0
for i in range(3, 1000):
if i % 3 == 0 or i % 5 == 0:
total += i
return total
# An approach using list comprehension
def solution2():
return sum(x for x in range(1000) if (x %3 == 0 or x % 5 == 0))
|
class Queue:
def __init__(self,max=10):
self.queue = []
self.max = max
self.rear = -1
def enqueue(self,data):
if self.rear == self.max - 1:
raise Exception("Queue is full")
self.queue.append(data)
self.rear += 1
return self.rear
def dequeue(self):
if self.rear == self.max -1:
raise Exception("Queue is empty")
self.rear -= 1
return self.queue.pop(0)
def isEmpty(self):
return self.queue == []
def isFull(self):
return self.rear == self.max - 1
def peek(self):
return self.queue[0]
names = Queue()
print("is empty",names.isEmpty())
print('is full',names.isFull())
print('push',names.enqueue('hello'))
print('push',names.enqueue('world'))
print('push',names.enqueue('coding'))
print('peek',names.peek())
print('pop',names.dequeue())
print('is empty',names.isEmpty())
print('is full',names.isFull()) |
import unittest
from warehouse import Warehouse
from inventory_allocator import InventoryAllocator
# Assumptions:
# 1. I assume that in the list of warehouses as the second input, warehouses cannot have the same name
class TestInventoryAllocator(unittest.TestCase):
def test_not_enough_inventory_for_single_item(self):
# no warehouses
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10}, []) )
# warehouse object is null
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse() ]) )
# warehouse exist, but does not have item
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse('wh1', {'item2': 10}) ]) )
# not enough quantity in a single warehouse
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse('wh1', {'item1': 5}) ]) )
# not enough quantity in a multiple warehouses
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse('wh1', {'item1': 5}), Warehouse('wh2', {'item1': 2}), Warehouse('wh3', {'item1': 2}) ]) )
def test_not_enough_inventory_for_multiple_items(self):
# no warehouses
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10, 'item2': 10}, []) )
# warehouse object is null
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10, 'item2': 10}, [ Warehouse() ]) )
# warehouse exist, but does not have item
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10, 'item2': 10}, [ Warehouse('wh1', {'item2': 10}) ]) )
# not enough quantity in a single warehouse
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10, 'item2': 10}, [ Warehouse('wh1', {'item1': 5}) ]) )
# not enough quantity in a multiple warehouses
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10, 'item2': 10}, [ Warehouse('wh1', {'item1': 5}), Warehouse('wh2', {'item1': 2}), Warehouse('wh3', {'item1': 2}) ]) )
# enough quantity in for an item, but not the rest of the order
self.assertEqual([], InventoryAllocator().allocate_order({'item1': 10, 'item2': 10}, [ Warehouse('wh1', {'item1': 5}), Warehouse('wh2', {'item1': 5}), Warehouse('wh3', {'item1': 5}) ]) )
def test_enough_inventory_for_single_item(self):
# single warehouse with single item in inventory -- exact quantity
self.assertEqual([{'wh1' : {'item1': 10}}], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse('wh1', {'item1': 10}) ]))
# single warehouse with single item in inventory -- over quantity
self.assertEqual([{'wh1' : {'item1': 10}}], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse('wh1', {'item1': 20}) ]))
# multiple warehouses -- multiple items in inventory -- over quantity in first warehouse
self.assertEqual([{'wh1' : {'item1': 10}}], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse('wh1', {'item1': 10}), Warehouse('wh2', {'item1': 20}) ]))
# multiple warehouses -- multiple items in inventory -- not enough quantity in first warehouse
self.assertEqual([{'wh1' : {'item1': 4}}, {'wh2' : {'item1': 6}}], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse('wh1', {'item1': 4}), Warehouse('wh2', {'item1': 20}) ]))
# multiple warehouses -- exact quantity needed
self.assertEqual([{'wh1' : {'item1': 4}}, {'wh2' : {'item1': 6}}], InventoryAllocator().allocate_order({'item1': 10}, [ Warehouse('wh1', {'item1': 4}), Warehouse('wh2', {'item1': 6}) ]))
def test_enough_inventory_for_multiple_items(self):
# single warehouse with exact quantity
self.assertEqual([{'wh1' : {'item1': 10, 'item2':10}}], InventoryAllocator().allocate_order({'item1': 10, 'item2':10}, [ Warehouse('wh1', {'item1': 10, 'item2':10}) ]))
# single warehouse with over quantity
self.assertEqual([{'wh1' : {'item1': 10, 'item2':10}}], InventoryAllocator().allocate_order({'item1': 10, 'item2':10}, [ Warehouse('wh1', {'item1': 20, 'item2':20}) ]))
# multiple warehouses -- multiple items in inventory -- over quantity in first warehouse
self.assertEqual([{'wh1' : {'item1': 10, 'item2':10}}], InventoryAllocator().allocate_order({'item1': 10, 'item2':10}, [ Warehouse('wh1', {'item1': 20, 'item2':20}), Warehouse('wh2', {'item1': 20, 'item2':20}) ]))
# multiple warehouses -- multiple items in inventory -- not enough quantity in first warehouse
self.assertEqual([{'wh1' : {'item1': 4, 'item2': 5}}, {'wh2' : {'item1': 6, 'item2': 5}}], InventoryAllocator().allocate_order({'item1': 10, 'item2':10}, [ Warehouse('wh1', {'item1':4, 'item2':5}), Warehouse('wh2', {'item1': 20, 'item2':20}) ]))
# multiple warehouses -- exact quantity needed
self.assertEqual([{'wh1' : {'item1': 4, 'item2': 5}}, {'wh2' : {'item1': 6, 'item2': 5}}], InventoryAllocator().allocate_order({'item1': 10, 'item2':10}, [ Warehouse('wh1', {'item1':4, 'item2':5}), Warehouse('wh2', {'item1': 6, 'item2':5}) ]))
if __name__ == '__main__':
unittest.main(verbosity = 2) |
def is_substring(st, sb):
i = 0
lsb = len(sb)
while i < len(st):
j = lsb
while j > 0 and (i+j-1) < len(st):
if sb[j-1] != st[i+j-1]:
break
j -= 1
if j == 0:
return i+1
i+=1
return -1
if __name__=='__main__':
print("python substring program")
st = input("Enter the main string")
sb = input("Enter the substring to find")
pos = is_substring(st, sb)
if pos != -1:
print("The substring %s is found in the string %s at index %d" %(sb,st,pos))
else:
print("The substring %s is NOT found in the string %s" %(sb,st)) |
import random
def selection_sort(a, N):
for i in range(N):
pos = i
for j in range(i+1, N):
if a[j] < a[pos]:
pos = j
tmp = a[pos]
a[pos] = a[i]
a[i] = tmp
def bubble_sort(a, N):
for i in range(N):
flag = 0
for j in range(N-i-1):
if a[j] > a[j+1]:
tmp = a[j+1]
a[j+1] = a[j]
a[j] = tmp
flag = 1
# all are sorted elements
if flag == 0:
break
def insertion_sort(a, N):
for i in range(1,N):
j = i-1
tmp = a[i]
while j >= 0 and a[j] > tmp:
a[j+1] = a[j]
j = j-1
a[j+1] = tmp
if __name__=="__main__":
print("program for selection sort, bubble sort and insertion sort")
N = int(input("How many numbers?"))
lt = random.sample(range(1, 1000), N)
print(lt)
lt2= list()
lt2.extend(lt)
lt3 = list()
lt3.extend(lt)
selection_sort(lt, N)
bubble_sort(lt2, N)
insertion_sort(lt3,N)
print("selection sort")
print(lt)
print("Bubble sort")
print(lt2)
print("insertion sort")
print(lt3)
|
import random
def negate(a):
neg = 0
if a > 0:
sign = -1
else:
sign = 1
delta = sign
while a != 0:
newsign = (a+delta > 0) != (a > 0)
if newsign and a+delta != 0:
delta = sign
a += delta
neg += delta
delta += delta
return neg
if __name__=="__main__":
print("Python program to substract two numbers without using '-' operator")
ar = range(1,1000)
print (ar)
a = random.sample(range(1,1000), 2)
print("The input numbers are %d %d" %(a[0], a[1]))
print("The negate of %d is %d" %(a[1], negate(a[1])) )
print("The numbers difference is : %d (%d [-])" %(a[0]+negate(a[1]), a[0]-a[1])) |
from binarytree import Node, pprint
class dnode(Node):
def __init__(self, val):
Node.__init__(self, val)
self.depth = 0
class BStree:
def __init__(self):
self.root = None
def insert(self, node):
if self.root == None:
self.root = node
else:
cur = self.root
prev = cur
depth = 0
while cur!= None:
if node.value <= cur.value:
prev = cur
cur = cur.left
else:
prev= cur
cur = cur.right
depth +=1
node.depth = depth
if node.value <= prev.value:
prev.left = node
else:
prev.right = node
def display(self, msg):
print(msg)
pprint(self.root)
def print_tree(self, msg):
print(msg)
lt = list()
lt.append(self.root)
pd =self.root.depth
i = 0
while i < len(lt):
node = lt[i]
if node.left:
lt.append(node.left)
if node.right:
lt.append(node.right)
if pd != node.depth:
print()
pd = node.depth
print("%d " %node.value , end="")
i+=1
if __name__=="__main__":
print("Python program to Binary search tree level traversal")
N = int(input("How many elements?"))
bst= BStree()
for i in range(N):
val = int(input("Enter the value for the element %d" %(i+1)))
bst.insert(dnode(val))
bst.display("Input Binary tree is as follows")
bst.print_tree("Input binary tree in level order ")
|
import random
max_width = 16
class HashTable:
def __init__(self, size):
self.lt = [None]*size
self.size = size
def insert(self,value):
rem = value%self.size
if self.lt[rem] == None:
self.lt[rem]= list()
self.lt[rem].append(value)
id = len(self.lt[rem])
key = ((id-1) << max_width) | rem
return key
def get_value(self, key):
rem = key & (max_width-1)
id = key >> max_width
return self.lt[rem][id]
def get_key(self, value):
rem = value%self.size
found = False
for i in range(len(self.lt[rem])):
if self.lt[rem][i] == value:
found = True
break
if found:
return (i << max_width) | rem
else:
return -1
def printt(self, msg):
print(msg)
print(self.lt)
for ar in self.lt:
if ar == None:
continue
for val in ar:
key = self.get_key(val)
if key == -1:
print("Hash key not found for the value %d" %val)
else:
value = self.get_value(key)
print("hash key = %d (%x), value = %d" %(key, key, value))
if __name__=="__main__":
print("Python program to create an Hash Table")
N = int(input("How many numbers?"))
if N > 64:
print("Maximum 64 numbers only")
exit()
a = random.sample(range(1,100), N)
print("The input numbers are")
print(a)
ht = HashTable(10)
for val in a:
ht.insert(val)
ht.printt("Hash Table contents are as follows")
|
from binarytree import Node, pprint
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, node):
if self.root == None:
self.root = node
else:
cur = self.root
prev = cur
while cur!= None:
if node.value <= cur.value:
prev = cur
cur = cur.left
else:
prev= cur
cur = cur.right
if node.value <= prev.value:
prev.left = node
else:
prev.right = node
def remove(self, val):
cur = self.root
prev = self.root
while cur != None and prev!= None:
if cur.value == val:
# found the node to be deleted
tmp = cur
# balance the tree
if tmp.left != None:
cur = tmp.left
nxt = cur
while nxt.right != None:
nxt = nxt.right
nxt.right = tmp.right
else:
cur = tmp.right
if tmp == self.root:
if self.root.left:
self.root = self.root.left
else:
self.root = self.root.right
elif tmp == prev.left:
prev.left = cur
else:
prev.right = cur
del tmp
prev = None
elif cur.value < val:
prev = cur
cur = cur.right
else:
prev = cur
cur = cur.left
return prev
def display(self, msg):
print(msg)
pprint(self.root)
def rec_inorder(self, cur, lt):
if cur != None:
self.rec_inorder(cur.left, lt)
lt.append(cur.value)
self.rec_inorder(cur.right, lt)
def inorder(self, msg):
print(msg)
lt = list()
self.rec_inorder(self.root, lt)
size = len(lt)
for i in range(size-1):
print("%d->" %lt[i], end="")
print("%d" %lt[-1])
def rec_preorder(self, cur):
if cur != None:
print("%d " %cur.value, end="")
self.rec_preorder(cur.left)
self.rec_preorder(cur.right)
def preorder(self, msg):
print(msg)
self.rec_preorder(self.root)
print()
def rec_postorder(self, cur):
if cur != None:
self.rec_postorder(cur.left)
self.rec_postorder(cur.right)
print("%d " %cur.value, end="")
def postporder(self, msg):
print(msg)
self.rec_postorder(self.root)
print()
def print_tree(self, msg):
print(msg)
lt = list()
lt.append(self.root)
i = 0
while i < len(lt):
node = lt[i]
if node.left:
lt.append(node.left)
if node.right:
lt.append(node.right)
print(node.value)
i+=1
if __name__=="__main__":
print("Python program to create the Binary search Tree")
N= int(input("How many elements?"))
bst = BinarySearchTree()
for i in range(N):
val = int(input("Enter element %d " %(i+1)))
bst.insert(Node(val))
bst.display("Tree elements are")
bst.inorder("Inorder traversal")
bst.preorder("Preorder traversal")
bst.postporder("Postoder travesal")
val = int(input("Enter the value to remove from the tree"))
if bst.remove(val):
print("The %d not found in tree" %val)
else:
bst.display("The tree elements after the removal")
bst.inorder("Inorder traversal after removal")
|
import random
def extract_array(a,m,n):
lt =list()
for i in range(m,n):
lt.append(a[i])
return lt
def equal_array(a, m, n):
count = 0
for i in range(m, n):
if a[i] ==0:
count+=1
else:
count-=1
return (count == 0)
def get_arr(a):
lt =list()
for i in range(len(a),0,-1):
for j in range(0, i):
if equal_array(a,j,i):
lt.append(extract_array(a,j,i))
return lt
def get_delta(a):
lt = list()
count=0
for item in a:
if item == 0:
count+=1
else:
count-=1
lt.append(count)
return lt
def get_large_array(delta):
hash={}
max = 0
ms=0
me =0
for i in range(len(delta)):
if delta[i] in hash:
k = hash.get(delta[i])
d = i-k
if d > max:
max = d
ms = k
me = i
else:
hash.update({delta[i]:i})
return ms,me
def get_max_subarray(a):
delta= get_delta(a)
ms, me = get_large_array(delta)
return extract_array(a,ms,me+1)
if __name__=="__main__":
print("Python program to return the sub arrays of equal 0s and 1s")
N=int(input("How many numbers?"))
ar=[random.randint(0,1) for x in range(N)]
print("The input list is")
print(ar)
print("The largest array with equal number of 0s and 1s ")
print(get_max_subarray(ar))
lt = get_arr(ar)
print("The equal size arrays are as follows")
for l in lt:
print(l)
|
import random
def max_order(ar, index, n, order,memo):
if index >= n:
return 0
if index < len(memo):
return memo[index]
t1 = ar[index]+max_order(ar,index+2,n,order,memo)
t2 = max_order(ar,index+1,n,order,memo)
if t1 > t2:
memo.append(t1)
if index not in order:
order.append(index)
if index+1 in order:
order.remove(index+1)
else:
memo.append(t2)
if index in order:
order.remove(index)
if index+1 not in order:
order.append(index+1)
return memo[-1]
if __name__=="__main__":
print("Python program to print the maximum service order for masseuse")
N=int(input("How many continues requests?"))
ar = random.sample(range(10,100),N)
print("The input order is")
print(ar)
order = list()
memo = list()
max=max_order(ar,0,len(ar),order,memo)
print("The max order is %d" %max)
print("Massage sequence are")
for index in order:
print("%d " %ar[index], end="")
print()
|
class node:
def __init__(self,value):
self.value = value
self.next = None
def add(first , node):
if( first == None):
first = node
return first
cur = first
while (cur.next != None):
cur = cur.next
else:
cur.next = node
return first
def delete(first, value):
prev = first
cur = first
while (cur != None and cur.value != value):
prev = cur
cur = cur.next
else:
if (cur == None):
return None
elif (prev == cur):
first = cur.next
del prev
return first
else:
prev.next = cur.next
del cur
return first
def display(first):
if (first == None):
print("empty Linked List")
else:
print("The Linked list content are as follows")
while (first != None):
print("%d" %first.value, end="")
first = first.next
if (first == None):
print("")
else:
print("->", end="")
def reverse(first):
if (first == None):
print("empty Linked List")
return first
else:
rev_head = first
prev = None
while(first.next != None):
first = first.next
rev_head.next = prev
prev = rev_head
rev_head = first
else:
rev_head.next = prev
return rev_head
def rev_recursion(first, rh):
if (first == None):
print("empty Linked List")
return None, None
elif (first.next == None):
return first, first
else:
rev_head, rhead = rev_recursion(first.next, rh)
rev_head.next = first
return first, rhead
if __name__=='__main__':
print("Python Linked List program")
first = None
while(True):
print("Choose the operation")
print("1-Display")
print("2-Add value to linked list")
print("3-Delete the value from linked list")
print("4-Reverse a linked list")
print("5-Reverse a linked list by recursion")
print("Press any other key to exit")
choice=int(input(""))
if (choice == 1):
display(first)
elif (choice == 2):
value = int(input("Enter the value to add"))
first = add(first, node(value))
elif(choice == 3):
value = int(input("enter the value to delete"))
ret = delete(first,value)
if ret != None:
print("The node value %d Successfully deleted" %value)
first = ret
else:
print("The node value %d Not found in the list" %value)
elif(choice == 4):
first = reverse(first)
display(first)
elif(choice == 5):
tmp = first
rev_head, first = rev_recursion(first, None)
tmp.next = None
display(first)
else:
print("program terminates")
break
|
import random
class heapsort:
def __init__(self):
pass
def heapfiy(self, a, N):
for i in range(1, N, 1):
item = a[i]
j = i//2
while j >= 0 and item > a[j]:
a[i] = a[j]
i = j
if j:
j //=2
else:
break
a[i] = item
def adjust(self, a, N):
i = 0
item = a[i]
j = 1
while j <= N:
if j+1 < N and a[j] < a[j+1]:
j+=1
if item < a[j]:
a[i] = a[j]
i = j
j = 2*i+1
else:
break
a[i] = item
def sort(self, a, N):
self.heapfiy(a, N)
for i in range(N-1, 0, -1):
tmp = a[i]
a[i] = a[0]
a[0] = tmp
self.adjust(a, i-1)
print("The list after heapsort")
print(a)
if __name__=="__main__":
print("Python program for heap sort")
N = int(input("How many numbers?"))
a = random.sample(range(1,1000), N)
print("The input numbers are")
print(a)
hs = heapsort()
hs.sort(a, N)
|
def rotate_one(mat,r, c, N):
temp = [None]*4
for i in range(N-1):
# move right the first row
temp[0] = mat[r][c+N-1]
for j in range(N-2, 0, -1):
mat[r][j+1]= mat[r][j]
#move down the last colum
temp[1] = mat[r+N-1][c+N-1]
for j in range(N-2, 0, -1):
mat[r+j+1][N-1] = mat[r+j][N-1]
#move left the last row
temp[2] = mat[r+N-1][c]
for j in range(N-2):
mat[r+N-1][c+j] = mat[r+N-1][c+j+1]
#move up the first column
temp[3] = mat[r][c]
for j in range(N-2):
mat[r+j][c] = mat[r+j+1][c]
mat[r+1][c+N-1] = temp[0]
mat[r+N-1][c+N-2] = temp[1]
mat[r+N-2][c] = temp[2]
mat[r][c+1] = temp[3]
def rotate_matrix(mat, N):
r = 0
c = 0
for i in range(N, 1,-2):
rotate_one(mat,r, c,i)
r =r+1
c =c+1
if __name__=='__main__':
print("Python Matrix Rotation program")
N = int(input("Enter the Size of N*N matrix"))
mat = list()
for i in range(N):
mat.append(list())
print("*** Row %d ***" %(i+1))
for j in range(N):
val = int(input("Enter the value for mat[%d][%d]" %(i+1, j+1)))
mat[i].append(val)
print("Input matrix")
print(mat)
rotate_matrix(mat, N)
print("Matrix rotated by 90 degrees right")
print(mat)
|
import random
def find_pair(ar,sum):
ar.sort()
size = len(ar)
last = size-1
first = 0
lt=list()
while first < last:
tmp = ar[first]+ar[last]
if tmp == sum:
lt.append([ar[first],ar[last]])
first+=1
last-=1
elif tmp < sum:
first+=1
else:
last-=1
return lt
if __name__=="__main__":
print("Python program to print the pair of values which sums to input value")
N=int(input("How many values?"))
ar=random.sample(range(-10,10),N)
print("The input array is as follows")
print(ar)
sum=int(input("Enter the sum value"))
lt=find_pair(ar,sum)
if len(lt):
print("The list of pairs which the sum %d" %sum)
print(lt)
else:
print("There is no list of pairs")
|
import random
def find_next(big, element, index):
for i in range(index, len(big)):
if big[i] == element:
return i
return -1
def find_closure(big,small, index):
max = -1
for item in small:
next = find_next(big, item, index)
if next == -1:
return next
if max < next:
#index = next
max = next
return max
def short_sequence(big, small):
start = -1
end = -1
for i in range(len(big)):
tmp = find_closure(big,small, i)
if tmp == -1:
break
if start == -1 or (tmp-i < end-start):
start = i
end = tmp
return start, end
def create_indecies(big,small):
ind= [None]*len(small)
for i in range(len(small)):
ind[i]=list()
for j in range(len(big)):
if small[i] == big[j]:
ind[i].append(j)
return ind
def get_sequence(ind,tmp):
seq= [None]*len(tmp)
#print("sequence indexes")
#print(tmp)
for i in range(len(tmp)):
seq[i] = ind[i][tmp[i]]
#print("sequences")
#print(seq)
return seq
def get_min_seq(seq):
min = seq[0]
max = seq[0]
for item in seq:
if item < min:
min = item
if item > max:
max = item
return min,max
def get_min(one,two):
if one[0] == None:
return two, True
val1 = one[1]-one[0]
val2 = two[1]-two[0]
if val1 < val2:
return one, True
else:
return two, False
def get_short_sequence(ind):
tmp = [0]*len(ind)
best_min=[None,None]
i = len(tmp)-1
index = i
l = index
while index >= 0:
seq = get_sequence(ind,tmp)
min = get_min_seq(seq)
best_min, flag = get_min(best_min, min)
print("sequence: ", end="")
print(seq)
print("best min: ", end="")
print(best_min)
if flag and tmp[l] < len(ind[l])-1:
tmp[l]+=1
else:
for k in range(index, len(tmp)):
tmp[k]=0
i = len(tmp)-1
index-=1
if index >= 0:
tmp[index]+=1
return best_min
def get_short_sequence_method2(big, small):
ind = create_indecies(big,small)
print("Indexes are")
print(ind)
tmp = get_short_sequence(ind)
print(tmp)
if __name__=="__main__":
print("Python program to find the shortest subsequence")
N = int(input("what is the size of big array?"))
M = int(input("what is the size of sub array?"))
big=[random.choice([1,2,3,4,5,6,7,8,9]) for x in range(N)]
#big = random.sample(range(1,N+1),N)
small = list()
for i in range(M):
pos = random.randint(0, N-1)
if big[pos] not in small:
small.append(big[pos])
print("The big array")
print(big)
print("The small array")
print(small)
start, end = short_sequence(big, small)
if start != -1:
print("The sequence positions are %d and %d" %(start, end))
else:
print("The short sequence not found")
get_short_sequence_method2(big,small)
|
import numpy as np
# First some linear algebra
a = np.array([[1,2,3], [1,2,3]])
b = np.array([1,2,3])
print(a)
print(b)
print ('Numpy dot product of a and b: {}'.format(np.dot(a, b)))
print('''\n-------------------\nSection 2\n-------------------\n''')
input = np.array([1])
weight = np.array([0.6])
def binary_threshold(input, weight, threshold):
if sum(input * weight) > threshold:
return 1
else:
return 0
# The problem with induction is that it is not working.
# So why do we expect that neural networks based on induction will create new knowledge?
input = np.array([1,2,3])
weight = np.array([1,2,3])
print (input*weight)
print ('Binary threshold: {}'.format(binary_threshold(input, weight, 0.4)))
# def relu(input, weight):
# return max(0, (input * weight))
# print ('Relu: {}'.format(relu(input, weight)))
def diu(input, weight):
'''Non-vectorized digital unit implementation.'''
if sum(input * weight) > 0.5:
return 1
else:
return 0
def diu(input, weight):
'''Vectorized digital unit implementation.'''
a = np.array(sum(input * weight))
a[a<0.5] = 0
a[a>=0.5] = 1
return a
print ('Diu: {}'.format(diu(input, weight)))
def weight_init(shape):
return (np.array(np.random.random(shape))/shape[0])
print weight_init((3,2))
# print np.array([1,2,3]) * np.array([1,2,3])
# print np.array(np.random.random((1,3))) * np.array([1,2,3])
# print sum(np.array(np.random.random((1,3))) * np.array([1,2,3]))
# print sum(weight_init((1,3)) * np.array([1,2,3]))
# def diu(input, weight):
# '''Vectorized digital unit implementation.'''
# a = np.array(sum((input * weight).T))
# print ('Pruduct of input * weight: {}'.format(input * weight))
# print ('Sum of activations: {}'.format(sum((input * weight).T)))
# a[a<0.5] = 0
# a[a>=0.5] = 1
# print ('Result of diu activation: {}'.format(a))
# return a
# input = np.array([1,0.5,0.2])
# # weight = weight_init((3,3))
# weight = np.array([(0.1,1,10), (0.1,1,10), (0.1,1,10)]).T
# # weight = np.array([(0.1,0.1,0.1), (1,1,1), (10,10,10)])
# print ('Weight: {}'.format(weight))
# print ('Input: {}'.format(input))
# # print ('Diu: {}'.format(diu(input, weight)))
# diu(input, weight)
# input = np.array([1])
# weight = weight_init((1,1))
# # print ('Diu: {}'.format(diu(input, weight)))
# def diu(input, weight):
# '''Vectorized digital unit implementation.'''
# a = np.array(sum((input * weight)))
# print ('Pruduct of input * weight: {}'.format(input * weight))
# print ('Sum of activations: {}'.format(sum((weight * input).T)))
# print ('Sum of activations (dot product): {}'.format(np.dot(weight, input)))
# a[a<0.5] = 0
# a[a>=0.5] = 1
# print ('Result of diu activation: {}'.format(a))
# return a
# def diu(input, weight):
# '''Vectorized digital unit implementation.'''
# a = np.dot(weight, input)
# print ('Weight: {}'.format(weight))
# print ('Input: {}'.format(input))
# print ('Pruduct of input * weight: {}'.format(input * weight))
# print ('Sum of activations (dot product): {}'.format(np.dot(weight, input)))
# a[a<0.5] = 0
# a[a>=0.5] = 1
# print ('Result of diu activation: {}'.format(a))
# return a
# input = np.array([1,0.5,0.2])
# W1 = np.array([(0.1,0.1,0.1), (1,1,1), (10,10,10)])
# a1 = diu(input, W1)
# W2 = np.array([(0.1,0.1,0.1), (1,1,1), (10,10,10)])
# a2 = diu(a1, W2)
# input = np.array([1,0.5,0.2])
# W1 = weight_init((3,3))
# a1 = diu(input, W1)
# W2 = weight_init((3,3))
# a2 = diu(a1, W2)
# W3 = weight_init((3,3))
# a3 = diu(a2, W3)
# W4 = weight_init((3,3))
# a4 = diu(a3, W4) |
def num(number):
if number % 100 < 10:
return number
else:
check = number % 10
return check + num(number//10)
a = num(99)
if a >10:
print(num(a))
else:
print(a)
|
from collections import deque
graph = {'Ruslan':[]}
def person_is_seller(person):
pass
def serch_graph(name):
serch_deque = deque()
serch_deque += graph[name]
check_list = []
while serch_deque:
person = serch_deque.popleft()
if not person in check_list:
if person_is_seller(person):
print(person+"is a seller mango")
check_list.append(person)
return True
else:
serch_deque+= graph[person]
check_list.append(person)
return False
serch_graph('Ruslan') |
"""
This code is taken from the epydemic advanced tutorial.
It creates a network with a powerlaw distribution of connectivity, cutoff at a certain maximum node degree.
"""
import networkx as nx
import math
import numpy as np
from mpmath import polylog as Li # use standard name
def make_powerlaw_with_cutoff(alpha, kappa ):
'''Create a model function for a powerlaw distribution with exponential cutoff.
:param alpha: the exponent of the distribution
:param kappa: the degree cutoff
:returns: a model function'''
C = Li(alpha, math.exp(-1.0 / kappa))
def p( k ):
return (pow((k + 0.0), -alpha) * math.exp(-(k + 0.0) / kappa)) / C
return p
def generate_from(N, p, maxdeg = 100 ):
'''Generate a random graph with degree distribution described
by a model function.
:param N: number of numbers to generate
:param p: model function
:param maxdeg: maximum node degree we'll consider (defaults to 100)
:returns: a network with the given degree distribution'''
# construct degrees according to the distribution given
# by the model function
ns = []
t = 0
for i in range(N):
while True:
k = 1 + int (np.random.random() * (maxdeg - 1))
if np.random.random() < p(k):
ns = ns + [ k ]
t = t + k
break
# if the sequence is odd, choose a random element
# and increment it by 1 (this doesn't change the
# distribution significantly, and so is safe)
if t % 2 != 0:
i = int(np.random.random() * len(ns))
ns[i] = ns[i] + 1
# populate the network using the configuration
# model with the given degree distribution
g = nx.configuration_model(ns, create_using = nx.Graph())
g = g.subgraph(max(nx.connected_components(g), key = len)).copy()
g.remove_edges_from(list(nx.selfloop_edges(g)))
return g |
# A simple Finch dance in Python
from finch import Finch
from time import sleep
print("Finch's First Python program.")
# Instantiate the Finch object
snakyFinch = Finch()
# Do a six step dance
snakyFinch.led(254,0,0)
snakyFinch.wheels(1,1)
sleep(2)
print("second line")
snakyFinch.led(0,254,0)
snakyFinch.wheels(0,1)
sleep(2)
print("third line")
snakyFinch.led(0,0,254)
snakyFinch.wheels(1,0)
sleep(2)
print("third line")
snakyFinch.led(254,0,254)
snakyFinch.wheels(-1,-1)
sleep(2)
print("third line")
snakyFinch.led(0,254,254)
snakyFinch.wheels(0.2,-1)
sleep(2)
print("third line")
snakyFinch.led(254,254,254)
snakyFinch.wheels(0.3,0.3)
sleep(2.5)
print("third line")
snakyFinch.wheels(0,0)
snakyFinch.close();
|
def addup(num):
if num == 2:
return 2
else:
return num + addup(num - 2)
print(addup(10))
def factorial(number, times):
if number == 1:
return 1
else:
return number * factorial(number - 1, times - 1)
print(factorial(4, 4))
|
def partition(array, low, high):
i = low - 1
pivot = array[high]
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[high] = array[high], array[i + 1]
return i + 1
def quick_sort(array, low, high):
if len(array) == 1:
return array
if low < high:
part_index = partition(array, low, high)
quick_sort(array, low, part_index - 1)
quick_sort(array, part_index + 1, high)
#array = [1,8,6,3,9,99,121,2,3]
#quick_sort(array, 0, 8)
#print(array)
|
#L2-Password-Safe: V6
#Daniel Herbert
#28th March 2019
#
# This program is the first stage of a password manager - which provides an interface to remember the multitude of passwords use across various web sites and/or applications
# which require a user name and password combination, to provide authentication access.
#
# There are three main functions, called from a main menu
# 1. View
# 2. Add
# 3. Modify (change)
#
# There are three hard coded websites, with respective username and passwords - this is not good practice for an actual
# password manager app ( storing passwords in application code is not good practice ) though used here for illustrative purposes.
#
# Note: This program contains no real passwords, I use.
#
# Limitations of this program
# 1. This version will not store the username/password combo, persistently, meaning a restart will lose any previous entries
# 2. Passwords entered, are displayed in plain text - no masking on the display or encrypting ( hash alogrithm ) the input.
#
import time
#function used as a print to separate the code
#looks cleaner for the user
def print_dash_line():
print("-----------------------------------------")
### view ### : function lets the user view a certain account which is stored with in the program
#Will be also able to view user added accounts once they are created
def view(sites_list,usernames,passwords):
#sites_list in this print statement tells the user of all websites that have the account info already saved
print("Which account would you like to select out of")
#in this section I have added a for loop. This is so the list will print out clean with only the content and no square brackets
for web in sites_list:
print(sites_list.index(web),web)
while True:
try:
website = int(input("Please enter the corresponding number: "))
print_dash_line()
if website >= len(sites_list):
print ("Sorry " +name+ ", that number is greater than the requested range. Look at the question carefully and try again.")
continue
elif website < 0:
print("Sorry " +name+ ", that number is smaller than the requested range. Look at the question carefully and try again.")
continue
else:
print(usernames.get(sites_list[website]))
print(passwords.get(sites_list[website]))
time.sleep(2)
break
except ValueError:
print("That is not a number " +name+ ", try entering a number.")
continue
### add ### function allowing creation of a user specified website.
#asks for all needed information for an account, apends and inserts that info into the matching lists and dictionaries
def add(sites_list,usernames,passwords):
while True:
#variable so the program knows the name of the website you want to add
addweb = input("What is the name of the website you would like to add?: ").capitalize()
if addweb in sites_list:
print("Sorry " +name+ ",that is already an existing website. Please try again with a different website name.")
continue
#appends the users website they would like to add to the sites_variable
#I have used append because it will add the new element onto the end of the list and that is exactly where I want It
elif not addweb:
print("A website name is required, please enter one")
continue
else:
adduser = input("What is the username you would like to add?: ")
addpass = input("What is the name of the password you would like to add?: ")
sites_list.append(addweb)
break
while True:
#checks user entered the correctly and are happy with the values they have entered
confirm = input("Are you happy with what you have entered? 'yes' or 'no': ").lower()
if confirm.startswith('y'):
usernames[addweb] = ('Username:'+adduser)
passwords[addweb] = ('Password:'+addpass)
print(usernames[addweb])
print(passwords[addweb])
break
elif confirm.startswith('n'):
#starts mode 2 again so then the user can have another go at entering the website
#I have done this because it makes my program more flexible and able to handle more tasks
print("Ok " +name+ ", we will go back to the main menu.")
break
else:
print("Please try again as that input was not 'yes' or 'no'.")
continue
### modify ### allows user to change a username or password for one of the websites
#asks user whether they want to change username or password
#Than asks them what website they want to change
#Than asks them for the change and inserts it into dictionary
def modify(usernames,passwords,sites_list,run):
while True:
#I have used a nested while loop here so I am able to have an exception so that my program want break.
#I am able to check validness for to different inputs
#asking whether the username or password wants to be changed
change = input("would you like to change your username or password: ").lower()
#user wishes to change username
if change.startswith('u'):
while run<=1:
try:
#displays all websites available to be changed
print("What is the website you would like to change your password for?\nOut of")
for web in sites_list:
print(sites_list.index(web),web)
uchange = int(input("Please enter the site number you wish to change: "))
if uchange >= len(sites_list):
print("Sorry " +name+ ", that number is greater than the requested range. Look at the question carefully and try again.")
elif uchange < 0:
print("Sorry " +name+ ", that number is smaller than the requested range. Look at the question carefully and try again.")
else:
site_change = sites_list[uchange]
print_dash_line()
newuse = input("What is the new username you would like to enter?: ")
#enters new username into the dictionary
usernames[site_change] = ('Username: '+newuse)
#shows the user that it has been changed
print(usernames[site_change],"is now set")
#changes run to run=2 so the loop will not be ran again
run=run+1
break
except ValueError:
print("I can not accept the value you have entered " +name+ ", try entering a whole number.")
continue
#user wishes to change password
elif change.startswith('p'):
while run<=1:
try:
#displays all websites available to be changed
print("What is the website you would like to change your password for?\nOut of")
for web in sites_list:
print(sites_list.index(web),web)
pchange = int(input("Please enter the site number you wish to change: "))
if uchange >= len(sites_list):
print("Sorry " +name+ ", that number is greater than the requested range. Look at the question carefully and try again.")
elif uchange < 0:
print("Sorry " +name+ ", that number is smaller than the requested range. Look at the question carefully and try again.")
else:
site_change = sites_list[pchange]
print_dash_line()
newpass = input("What is the new password you would like to enter?: ")
#enters new password into the dictionary
passwords[site_change] = ('Password: '+newpass)
#shows the user that it has been changed
print(passwords[site_change],"is now set")
#changes run to run=2 so the loop will not be ran again
run=run+1
break
except ValueError:
print("Sorry," +name+ " that was not a valid input. Try entering either 'username' or 'password'")
continue
else:
print("Sorry," +name+ " that was not a valid input. Try entering either username or password")
continue
while True:
#checks user entered the correct values
confirm = input("Are you happy with what you have changed?. 'yes' or 'no': ").lower()
if confirm.startswith('y'):
break
elif confirm.startswith('n'):
#give the user another go at entering their new username or password
print("Ok " +name+ ", we will go back to the main menu.")
#set run back to 1 so it does not run nested while loop again
run=1
break
else:
print(name,", please try again as that input was not 'yes' or 'no'.")
continue
break
#Variables
# run is used to break out of nested loops
run=1
# amount of attempts to enter the password safe app
# if you exceed three, the app will exit
tries=0
#lists for storing websites, usernames and passwords
#stores the different names of the websites that you have saved
sites_list = ['Amazon','Mightyape','Google']
#I have decided to use dictionaries as it allows me to store multiple keys and retrieve certain ones
usernames = {'Amazon':'Username: Danny',
'Mightyape':'Username: Danny89',
'Google':'Username: Bobby'}
passwords = {'Amazon':'Password: Super01',
'Mightyape':'Password: BOyshigh61',
'Google':'Password: superduper33'}
#defines master id and master password. You have to enter these to access the program
MASID = 'daniel.h'
MASPASS = 'simple01yes'
VERSION = 'Version 6'
DATE = '26th March 2019'
# printinfo on program
print("Daniel Herbert, " + DATE + " , " + VERSION + " Password safe.")
# check user has access to run this program
print_dash_line()
name = input("What is your name?: ")
while True:
#This line represents the amount of tries user can attempt before being kicked out of the program
#I have done this to prevent people from entering a password 10000 times then eventually getting it correct.
if tries<3:
#just simple username and password to stop someone random using the program + welcome message
userid = input("Enter Master id: ")
passuser = input("Enter Master password: ")
if userid == MASID and passuser == MASPASS:
#I have not error checked for name as I let anyone be called whatever they want to be called
print ("Successfully signed in.")
print_dash_line()
print("Hello " +name+ ". This is a password safe programed in python to store account information for websites or anything else you desire.")
print("There are several modes you can select within this password safe.")
enter = input("Press enter when ready to start this program: ")
else:
tries = tries+1
print("Sorry you have either entered the username or password incorrectly, you need to enter these correctly to access the rest of the program")
continue
else:
print("Sorry you have reached the maximum amount of tries, goodbye.")
quit()
while True:
print_dash_line()
print("\nYou can choose one of the following modes:\n('1')Find an existing account\n('2')Add a new account\n('3')Change an existing username or password\n('4')Exit the program")
try:
mode = int(input("Choose selected mode by entering one of the aforementioned numbers which corresponds to the desired selection: "))
print_dash_line()
#once user has entered mode is mode 1 runs this code
if mode == 1:
#runs the code when the user is wanting to check for a existing username and password
view(sites_list,usernames,passwords)
continue
elif mode == 2:
#this runs if the user is wanting to insert a new account to the program
add(sites_list,usernames,passwords)
continue
elif mode == 3:
#mode 3 is to change an existing username or password
modify(usernames,passwords,sites_list,run)
continue
elif mode == 4:
#mode 4 quits the program
print("Good bye")
quit()
#user has not entered a correct input tells them why and runs the loop again
#here I have gone through and coded so that it tells the user exactly what they have done wrong
#I have done this because next time the user tries a input they will know exactly how to fix it
elif mode <1:
#either too low
print("Sorry " +name+ "That number is below the range of the requested values")
continue
elif mode >=5:
#too high
print("Sorry " +name+ ", that number is above the range of requested values")
continue
except ValueError:
#or not A number or float
print("You have not entered a number or you have entered a float, Please read the question carefully and try again.")
continue
|
# filename = "test.txt"
#
#
# for each_line in open(filename):
# print each_line
# for each_word in each_line.split():
# print each_word
# print "=============="
import csv
csv_file = "test.csv"
csv_obj = csv.reader(csv_file)
for row in csv_obj:
print row
|
def quick_sort(input_list):
if len(input_list) == 0 or len(input_list) == 1:
return input_list
else:
pivot = input_list[0]
i = 0
for j in range(len(input_list) - 1):
if input_list[j+1] < pivot:
temp = input_list[j+1]
input_list[j+1] = input_list[i+1]
input_list[i+1] = temp
i += 1
temp = input_list[0]
input_list[0] = input_list[i]
input_list[i] = temp
part_one = quick_sort(input_list[:i])
part_two = quick_sort(input_list[i+1:])
part_one.append(input_list[i])
return part_one + part_two
print quick_sort([4, 56, 2, -1, 45454]) |
import math
def find_factorial(n):
"""
Returns the factorial of a given number (n!)
:param n: integer input
:return: integer or error if n is negative
"""
if n < 0:
return "Error: enter positive integer"
elif n == 0 or n == 1:
return 1
else:
return n * find_factorial(n-1)
print find_factorial(256)
print math.factorial(256) |
"""
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# quotient = temp_x = x
# rev_x = 0
# if x < 0:
# return False
# if 0 < x < 10:
# return True
# while quotient != 0:
# quotient = temp_x // 10
# remainder = temp_x % 10
# temp_x = quotient
# rev_x = rev_x * 10 + remainder * 10
# if x == rev_x // 10:
# return True
# else:
# return False
if x < 0:
return False
if x < 10:
return True
str_int = str(x)
for i in range(0, len(str_int)/2):
if str_int[i] != str_int[len(str_int) - 1 - i]:
return False
else:
continue
return True
integer = 10
sol = Solution()
print(sol.isPalindrome(integer))
|
"""
Given a pyramid of consecutive integers:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
......
Find the sum of all the integers in the row number N.
For example:
The row #3: 4 + 5 + 6 = 15
The row #5: 11 + 12 + 13 + 14 + 15 = 65
"""
def sum_pyramid_numbers(row):
i = 1
last_number = 0
while i <= row:
for n in range(i):
last_number += 1
i += 1
print last_number
sum = last_number
while row != 1:
last_number -= 1
sum += last_number
row -= 1
print sum
sum_pyramid_numbers(5) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 16:53:19 2020
@author: hihyun
"""
def solution(s:str):
suffix=[]
for c in range (len(s)):
suffix.append(s[c:])
return sorted(list(suffix))
s=input()
for i in solution(s):
print(i) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 19:02:41 2020
@author: hihyun
"""
from collections import defaultdict
class graph:
def __init__(self):
self.graph=defaultdict(list)
def add(self,node1,node2):
self.graph[node1].append(node2)
def show(self):
print(self.graph)
def __len__(self):
return len(self.graph.keys())
g1=graph()
g1.add("r","s")
g1.add("r","v")
g1.add("s","r")
g1.add("s","w")
g1.add("w","s")
g1.add("w","t")
g1.add("w","x")
g1.add("t","w")
g1.add("t","x")
g1.add("t","u")
g1.add("x","t")
g1.add("x","u")
g1.add("x","y")
g1.add("u","x")
g1.add("u","y")
g1.add("u","t")
g1.add("y","u")
g1.add("y","x")
g1.add("v","r")
g1.show()
len(g1)
class queue:
def __init__(self):
self.queue=[]
def enqueue(self,v):
self.queue.append(v)
def dequeue(self):
a=self.queue[0]
self.queue=self.queue[1:]
return a
q1=queue()
q1.enqueue(1)
print(q1.queue)
q1.enqueue(2)
q1.enqueue(3)
q1.enqueue(4)
q1.dequeue()
###BFS
def BFS(G,sp):
#visit list
visit={}
length={}
for i in G.graph.keys():
visit[i]=-1
length[i]=-1
#queue
q1=queue()
visit[sp]=1
length[sp]=0
q1.enqueue(sp)
while(len(q1.queue)!=0):
point=q1.dequeue()
print(point)
adj_e=G.graph[point]
for i in adj_e:
if visit[i]==-1:
q1.enqueue(i)
visit[i]=1
length[i]=length[point]+1
return length
BFS(g1,"s")
####DFS
def DFS(G,sp,visit):
visit[sp]=1
for i in G.graph[sp]:
if visit[i]==-1:#unvisit
print(i)
DFS(G,i,visit)
visit={}
for j in g1.graph.keys():
visit[j]=-1
DFS(g1,"s",visit)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 2 15:05:13 2019
@author: hihyun
"""
def solution(priorities, location):
print_data=[]
for i in enumerate(priorities):
print_data.append(i)
x=-1
count=0
while x != location:
check=print_data.pop(0)
if any(check[1]<q[1] for q in print_data):
print_data.append(check)
else:
x=check[0]
count+=1
return count
location=int(input())
priorities=[]
try:
while True:
priorities.append(int(input()))
except:
solution(priorities, location) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 13:29:55 2019
@author: hihyun
"""
#__ --> 특별한 메소드
class Human():
def __init__(self,name,weight):
"""초기화"""
print("__init start")
self.name=name
self.weight=weight
print("name is {}, weight is {}".format(name,weight))
def ___str__(self):
"""문자열"""
return "{}'s weight {}kg".format(self.name,self.weight)
def eat(self):
self.weight+=0.1
print("{}가 먹어서 {}kg이 되었다".format(self.name,self.weight))
def walk(self):
self.weight-=0.1
print("{}가 먹어서 {}kg이 되었다".format(self.name,self.weight))
def speak(self,message):
print(message)
person=Human('hyein',50)
person.eat()
print(person)
##자동으로 return 도 해주는구만
class Animal():
def __init__(self,name):
self.name=name
def walk(self):
print("walk")
def eat(self):
x=count()
print(x)
print("eat")
def greet(self):
print("{} is 인사한다".format(self.name))
def count():
return 1
class Human(Animal):
def __init__(self,name,hand):
super().__init__(name)
self.hand=hand
def greet(self):
super().greet()
print("wave+ing using {}".format(self.hand))
class Dog(Animal):
def greet(self):
print("wag")
person=Human("사람",'right')
person.greet()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 17:22:44 2020
@author: hihyun
"""
def partition(arr,l,r):
pivot=arr[r]
p_idx=l-1
for j in range(l,r):
if arr[j]<pivot:
p_idx+=1
arr[j],arr[p_idx]=arr[p_idx],arr[j] #swap
arr[r],arr[p_idx+1]=arr[p_idx+1],arr[r]
return p_idx+1 #return pivot index
def quicksort(arr,l,r):
if(l<r):
p=partition(arr,l,r)
quicksort(arr,l,p-1)
quicksort(arr,p+1,r)
return arr
quicksort([3,2,1,5,7],0,4)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 20:44:55 2020
@author: hihyun
"""
def merge(list):
length=len(list)
if length<=1: #itialize
return list
#divide
g1=merge(list[:length//2])
g2=merge(list[length//2:])
#conquer
sorted=[]
while g1 and g2:
if g1[0]<=g2[0]:
sorted.append(g1[0])
g1=g1[1:]
elif g1[0]>g2[0]:
sorted.append(g2[0])
g2=g2[1:]
if g1:
sorted=sorted+g1
if g2:
sorted=sorted+g2
return sorted
merge([5,9,3,2,1])
def merge2(list,l,r,mid):
l_li=list[l:mid+1]
r_li=list[mid+1:r+1]
l_li.append(1000000) #infinity
r_li.append(1000000) #infinity
l_idx=0
r_idx=0
for i in range(l,r+1):
if l_li[l_idx]<=r_li[r_idx]:
list[i]=l_li[l_idx]
l_idx+=1
else:
list[i]=r_li[r_idx]
r_idx+=1
def mergesort(list,l,r):
if(l<r):
mid=(l+r)//2
mergesort(list,l,mid)
mergesort(list,mid+1,r)
merge2(list,l,r,mid)
return list
mergesort([5,9,3,2,1],0,4)
|
#!/usr/bin/python3
'''
Criar um dicionario de frutas e amarzenar nome e valor
'''
frutas = [
{'nome':'abacaxi','preco':10},
{'nome':'abacate','preco':5},
{'nome':'melao','preco':12},
{'nome':'melancia','preco':20},
{'nome':'mamao','preco':7}
]
frutas2 = []
for fruta in frutas:
fruta['preco'] += 0.5
frutas2.append(fruta)
#print(fruta)
print(frutas2) |
#!/usr/bin/python3
# pip3 install psycopg2
import psycopg2
import os
os.system('clear')
try:
con = psycopg2.connect('host=localhost dbname=projeto user=admin password=4linux port=5432')
cur = con.cursor()
print('Conectado com sucesso')
resp = input("Deseja inserir Dados; Sim ou Nao ? ")
if resp == 'Sim':
cur.execute("insert into pessoas(nome,email,idade,telefone)values('teste','teste@teste.com.br', 99, '96789999')")
else:
print("Vou apenas listar")
cur.execute("select * from pessoas")
conteudo = cur.fetchall()
#percorrendo a lista
for item in conteudo:
print(item)
#print(conteudo)
#fetchall fetchone
con.commit()
cur.close() #fecha o cursor
cur.close() #encerra a conexao
print('Conexao fechado com sucesso')
#Boas praticas == tratamento de excecao
except Exception as e:
cur.roolback()
print('Erro conexao: {}'.format(e))
|
#!/usr/bin/python3
while True:
try:
num = int(input("Digite um numero: "))
print(num)
break
except ValueError as e:
print("Nao e um inteiro:{}".format(e))
pass
except Exception as e:
print("Nao e um inteiro:{}".format(e)) |
#!/usr/bin/python
"""See if I can implement Quick Sort."""
import random
def qsort(a):
"""Quick Sort array "a" in place."""
def sort_part(first, last):
"""First and last point to the first and last elements (inclusive) in
"a" to be sorted."""
if last <= first:
# A zero- or one-element array is already sorted. A more efficient implementation
# would check whether the array was short (say, 5 or fewer items) and fall back
# on an insertion sort, which is faster than Quick Sort for small arrays.
return
# We pick our pivot element from the middle of the array so that the sort
# will behave well if the array is already sorted. Another option here is
# to shuffle the entire array when we're first given it (in qsort(), not
# in this subroutine) and just use the first element here (and skip the
# swap just below). Our approach here will result in a more even partition
# if the array is already sorted, since a pure shuffle will have some
# imbalance.
#
# Note the method used to find the middle element. We could use
# (first + last)/2, but that may overflow in languages with limited
# range. (E.g., a 2-billion element array in Java).
pivot_index = first + (last - first)/2
pivot_value = a[pivot_index]
# Put pivot at the front so we can partition the rest of the elements. We need
# to keep the pivot element separate so that the two partitions we recurse into
# are guaranteed to be smaller than the original.
a[pivot_index], a[first] = a[first], a[pivot_index]
# The entire array is split into four sections:
#
# 1. The pivot (length 1).
# 2. Elements <= the pivot value (initially empty, possibly always empty).
# 3. Unprocessed elements (empty at the end).
# 4. Elements >= the pivot value (initially empty, possibly always empty).
#
# The "low" and "high" indices point to the first and last unprocessed elements.
low = first + 1
high = last
# Throughout the partitioning process we maintain the following invariant:
#
# a[first..low) <= pivot_value <= a(high..last]
# Continue this loop as long as we have any unprocessed elements left.
while low <= high:
# See if we can shorten the unprocessed area on the left. If the left-most
# element (at "low") is <= pivot_value, just move "low" up. Only do this
# if the unprocessed section is non-empty (low <= high).
while low <= high and a[low] <= pivot_value:
low += 1
# See if we can shorten the unprocessed area on the right. If the right-most
# element (at "high") is >= pivot_value, just move "high" down. Only do this
# if the unprocessed section is non-empty (low <= high).
while low <= high and a[high] >= pivot_value:
high -= 1
# After the above two loops, we either have no more unprocessed elements left
# (low > high) or the two indices got stuck. Note that we'll never have
# low == high since we won't have a case above where both loops get stuck on
# the same element. So we don't need to check for "low <= high".
assert low != high
if low < high:
# If they got stuck, then they each got stuck at elements that should be
# in the opposite section (since both criteria together cover the entire
# domain). We swap the two elements they got stuck on.
assert a[low] > a[high]
a[low], a[high] = a[high], a[low]
# Since these two elements are now processed, we move the indices to
# push the elements into the processed sections. This part is optional
# since the above loops will do that for us anyway, but it's a nice way
# to capture the idea that the swap moved the elements into the outer
# sections. Also it's a convenient way to prove that this loop will
# eventually terminate: at each iteration, either this "if" will run
# (and the unprocessed section will shrink) or it will be the last
# iteration.
low += 1
high -= 1
# The processed section is now empty. The array looks like this:
#
# 1. The pivot (length 1).
# 2. Elements <= the pivot value (possibly empty).
# 3. Unprocessed elements (empty).
# 4. Elements >= the pivot value (possibly empty).
#
# The "low" and "high" indices are adjacent (low == high + 1) and represent
# the empty section 3. That means that "high" points to the last element of
# section 2 and "low" points to the first element of section 4.
assert low == high + 1
# We could now recurse on sub-arrays [first..high] and [low..last],
# since the pivot technically is allowed to belong to section 2. If
# this terminated, the array would be correctly sorted. But it's not
# guaranteed to terminate since section 4 may be empty (if all elements
# in the array are <= the pivot).
#
# To guarantee that the recursion is always smaller than the original,
# we don't recurse on the pivot element. But after sorting we'll want
# the pivot to be between the two sub-arrays. To put the pivot in the
# right place we could swap it to either a[high] or a[low], but the
# swapped element will end up in a[first], which we'll recurse with
# section 2, so we must swap the pivot with a[high].
pivot_index = high
# Note also that it's possible that first == pivot_index, if section 2
# is empty. That's fine, we'll swap with ourselves and the first
# recursion below will do nothing.
a[first], a[pivot_index] = a[pivot_index], a[first]
# Recurse on our two sub-arrays, avoiding the pivot. If the "pivot_value"
# appeared multiple times in the original array, it'll be in one or both
# of the sub-arrays and will end up adjacent to "pivot_index".
sort_part(first, pivot_index - 1)
sort_part(pivot_index + 1, last)
# Sort the entire array.
sort_part(0, len(a) - 1)
def test():
# Many tests.
for i in range(100000):
# Generate random array. Keep it short so we have duplicates.
a = []
for j in range(random.randint(0, 1000)):
a.append(random.randint(-100, 100))
# Make a copy that we'll sort separately.
b = a[:]
# Our own sort.
qsort(a)
# Python's sort.
b.sort()
# Progress bar.
if i % 1000 == 0:
print i
# See if we got it right.
if a != b:
print a
print b
if __name__ == "__main__":
try:
test()
except KeyboardInterrupt:
# After the ^C printed by the terminal (or by Python?).
print
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Read input values from CSV file
data = pd.read_csv('input1.txt', names = ['x', 'y'])
X_col = pd.DataFrame(data.x)
y_col = pd.DataFrame(data.y)
m = len(y_col) #Size of input values
iterations = 400 #Number of iterations
alpha = 0.001 #Desired value of alpha (Learning rate)
theta = np.array([0, 0]) #Set initial value of theta0 and theta1 to 0
print("Linear Regression with one variable initial parameters:")
print("Number of Iterations=",iterations)
print("Alpha= ",alpha)
print("Initial Theta0= 0")
print("Initial Theta1= 0")
X_col['i'] = 1 #Add initial X-intercept
X = np.array(X_col) #convert to numpy arrays for easy math functions
Y = np.array(y_col).flatten()
def gradient_descent(X, Y, theta, alpha, iterations):
cost_arr = [0]*iterations #initialize cost_arr array
for i in range(iterations):
h = X.dot(theta)
gradient = X.T.dot(h-Y)/m
theta = theta - alpha*gradient
cost = cost_function(X, Y, theta)
cost_arr[i] = cost
print("Final cost=",cost_arr[iterations-1])
np_X = [0] * iterations
np_cost_hist=np.array(cost_arr)
np_X=list(range(400))
plt.figure(figsize=(10,8))
plt.plot(np_X, np_cost_hist, '-')
plt.ylabel('Cost J(Theta)')
plt.xlabel('Iterations')
plt.title('Cost J vs Number of iterations')
return theta, cost_arr
def cost_function(X, y, theta):
m = len(y)
J = np.sum((X.dot(theta)-y)**2)/(2*m) #calculate cost
return J
(theta_final, cost_final) = gradient_descent(X,Y,theta,alpha,iterations)
print("Final Theta0=",theta_final[0])
print("Final Theta1=",theta_final[1])
regression_x = list(range(25))
regression_y = [theta_final[1] + theta_final[0]*xi for xi in regression_x] #staright line equation
plt.figure(figsize=(10,8)) #plot graph
plt.plot(X_col.x, y_col.y, 'ro')
plt.plot(regression_x, regression_y, '-')
plt.axis([0,6.5,0,14])
plt.xlabel('X')
plt.ylabel('Y')
plt.title('X vs Y -- Regression Line') |
# Modification of pong: Squash
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True
bounce_record = 0
paddle_color = "White"
# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel, bounces
ball_pos = [WIDTH / 2, HEIGHT / 2]
ball_vel = [0, 0]
if direction == RIGHT:
ball_vel[0] = random.randrange(4, 8)
ball_vel[1] = random.randrange(-6, -2)
#ball_vel[0] = random.randrange(2, 4)
#ball_vel[1] = random.randrange(-3, -1)
else:
ball_vel[0] = random.randrange(-4, -2)
ball_vel[1] = random.randrange(-3, -1)
bounces = 0
# define event handlers
def new_game():
global paddle_pos, paddle_vel # these are numbers
paddle_pos = [HALF_PAD_WIDTH, HEIGHT / 2]
paddle_vel = [0, 0]
spawn_ball(RIGHT)
def draw(canvas):
global paddle_pos, ball_pos, ball_vel, bounces, bounce_record, paddle_color
# draw mid line and gutters
#canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
#canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
if (ball_pos[0] >= (WIDTH - 1) - BALL_RADIUS):
ball_vel[0] = - ball_vel[0]
paddle_color = "White"
if (ball_pos[1] <= BALL_RADIUS) or (ball_pos[1] >= (HEIGHT - 1) - BALL_RADIUS):
ball_vel[1] = - ball_vel[1]
paddle_color = "White"
if ball_pos[0] <= BALL_RADIUS + PAD_WIDTH:
if (ball_pos[1] <= paddle_pos[1] - HALF_PAD_HEIGHT) or (ball_pos[1] >= paddle_pos[1] + HALF_PAD_HEIGHT):
paddle_color = "Red"
spawn_ball(RIGHT)
else:
paddle_color = "Green"
ball_vel[0] = - ball_vel[0] * 1.1
ball_vel[1] = ball_vel[1] * 1.1
bounces += 1
if bounces > bounce_record:
bounce_record = bounces
# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "White", "White")
# update paddle's vertical position, keep paddle on the screen
if paddle_vel[1] > 0:
if (paddle_pos[1] + HALF_PAD_HEIGHT < HEIGHT - 1):
paddle_pos[1] += paddle_vel[1]
else:
if paddle_pos[1] - HALF_PAD_HEIGHT > 0:
paddle_pos[1] += paddle_vel[1]
paddle_pos_up = paddle_pos[1] - HALF_PAD_HEIGHT
paddle_pos_bottom = paddle_pos[1] + HALF_PAD_HEIGHT
# draw paddles
canvas.draw_polygon([(0, paddle_pos_up), (PAD_WIDTH - 1,paddle_pos_up), (PAD_WIDTH - 1, paddle_pos_bottom), (0, paddle_pos_bottom)], 1, paddle_color, paddle_color)
# draw number of bounces
canvas.draw_text(str(bounces) + " bounce(s)", [30, 30], 20, "White")
canvas.draw_text("Bounce record: " + str(bounce_record), [30, 50], 20, "Red")
def keydown(key):
global paddle_vel, BALL_RADIUS
paddle_acc = 5
if key == simplegui.KEY_MAP["up"]:
paddle_vel[1] += -paddle_acc
elif key == simplegui.KEY_MAP["down"]:
paddle_vel[1] += paddle_acc
elif key == simplegui.KEY_MAP["left"]:
if BALL_RADIUS - 5 > 0:
BALL_RADIUS -= 5
elif key == simplegui.KEY_MAP["right"]:
if BALL_RADIUS + 5 <= 40:
BALL_RADIUS += 5
def keyup(key):
global paddle_vel
if key == simplegui.KEY_MAP["up"]:
paddle_vel[1] = 0
elif key == simplegui.KEY_MAP["down"]:
paddle_vel[1] = 0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("Restart", new_game, 100)
frame.add_label("Press left or right arrow to decrease or increase ball size", 100)
# start frame
new_game()
frame.start()
|
from HelperMethods import *
from WordCounter import WordCounter
import random
# Create WordCounters with nonsense words and a random word count
wc = WordCounter(makeNonsenseWord(), random.randint(1,45))
print(wc)
wc = WordCounter(makeNonsenseWord(), random.randint(1,45))
print(wc)
wc = WordCounter(makeNonsenseWord(), random.randint(1,45))
print(wc)
wc = WordCounter(makeNonsenseWord(), random.randint(1,45))
print(wc)
wc = WordCounter(makeNonsenseWord(), random.randint(1,45))
print(wc)
|
n = int(input())
fibo = [0, 1]
for i in range(2, n+1):
fibo.append(fibo[i-2]+fibo[i-1])
if n == 0:
print(fibo[0])
else:
print(fibo[-1]) |
N = int(input())
# 소수
prime = [True for _ in range(N+1)]
prime[0] = False
prime[1] = False
for i in range(2, N+1):
if prime[i]:
for j in range(i*2, N+1, i):
prime[j] = False
data = [i for i, boolean in enumerate(prime) if boolean]
# 투포인터
output = 0
end_idx = 0
for i in range(len(data)):
#print('start ', data[i])
start_idx = i
while start_idx <= end_idx:
total_sum = sum(data[start_idx:end_idx])
#print('total sum ', total_sum)
if total_sum == N:
output += 1
break
elif total_sum < N:
end_idx += 1
else:
break
# 소수 합으로 못 구하는 숫자
if end_idx > len(data):
break
print(output) |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
numOfA = 0
if(len(s) >= n):
for i in range(n):
if s[i] == 'a':
numOfA += 1
return numOfA
# truncate division (returns floor)
reps = n // len(s)
prefix = s.count('a') * reps
suffix = s[:n % len(s)].count('a')
numOfA = prefix + suffix
return numOfA
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
n = int(input())
result = repeatedString(s, n)
print(result)
# fptr.write(str(result) + '\n')
# fptr.close()
|
"""
T: O(NlogN)
S: O(N)
Remember the initial position of athlete's scores, sort scores, map places to
medal names.
"""
from typing import List
class Solution:
def findRelativeRanks(self, nums: List[int]) -> List[str]:
num_positions = {num: i for i, num in enumerate(nums)}
nums.sort(reverse=True)
relative_ranks = [""] * len(nums)
for i, num in enumerate(nums, 1):
position = num_positions[num]
medal = str(i)
if i == 1:
medal = "Gold Medal"
if i == 2:
medal = "Silver Medal"
if i == 3:
medal = "Bronze Medal"
relative_ranks[position] = medal
return relative_ranks
|
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
prev = float('inf')
write = -1
for num in nums:
if num != prev:
prev = num
write += 1
nums[write] = num
return write+1
|
from typing import List
class Solution:
def distanceBetweenBusStops(self,
distance: List[int],
start: int,
destination: int) -> int:
start, destination = sorted([start, destination])
direct_route = detour_route = 0
for i, dist in enumerate(distance):
if start <= i < destination:
direct_route += dist
else:
detour_route += dist
return min(direct_route, detour_route)
|
from typing import List
class Solution:
NUM_OF_COLORS = 3
def shortestDistanceColor(self,
colors: List[int],
queries: List[List[int]]) -> List[int]:
lefts = self.get_left_positions(colors)
rights = self.get_right_positions(colors)
distances = []
for i, color in queries:
color -= 1
distance = i - lefts[color][i]
distance = min(distance, rights[color][i] - i)
distances.append(-1 if distance == float('inf') else distance)
return distances
def get_left_positions(self, colors: List[int]) -> List[List[float]]:
N = len(colors)
left = [[float('-inf') for _ in range(N)]
for _ in range(self.NUM_OF_COLORS)]
last = [float('-inf'), float('-inf'), float('-inf')]
for i in range(N):
color = colors[i]-1
last[color] = i
for j in range(self.NUM_OF_COLORS):
left[j][i] = last[j]
return left
def get_right_positions(self, colors: List[int]) -> List[List[float]]:
N = len(colors)
right = [[float('inf') for _ in range(N)]
for _ in range(self.NUM_OF_COLORS)]
last = [float('inf'), float('inf'), float('inf')]
for i in reversed(range(N)):
color = colors[i]-1
last[color] = i
for j in range(self.NUM_OF_COLORS):
right[j][i] = last[j]
return right
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def helper(self, node: TreeNode, add_sum: int) -> int:
if not node:
return 0
original = node.val
right_sum = self.helper(node.right, add_sum)
node.val += right_sum + add_sum
left_sum = self.helper(node.left, node.val)
return original + right_sum + left_sum
def bstToGst(self, root: TreeNode) -> TreeNode:
_ = self.helper(root, 0)
return root
|
"""
T: O(N)
S: O(N)
We need to only store one mapping using this scheme. Also, the performance of
the encoding method can be treated as O(1) due to the total number of short
URLs being quite large - 62**6.
"""
import random
import string
class Codec:
ALPHABET = string.digits + string.ascii_letters
def __init__(self, url_len=6):
self.url_len = url_len
self.url_map = {}
def encode(self, longUrl: str) -> str:
short_url = self._get_short_url()
while short_url in self.url_map:
short_url = self._get_short_url()
self.url_map[short_url] = longUrl
return short_url
def decode(self, shortUrl: str) -> str:
return self.url_map[shortUrl]
def _get_short_url(self) -> str:
return "".join(
random.choice(self.ALPHABET) for _ in range(self.url_len))
|
class Solution:
DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def dayOfYear(self, date: str) -> int:
year, month, day = map(int, date.split('-'))
day += sum(self.DAYS_IN_MONTH[:month-1])
february_index = 2
if self.is_leap(year) and month > february_index:
day += 1
return day
def is_leap(self, year: int) -> bool:
if not year % 400:
return True
if not year % 100:
return False
if not year % 4:
return True
return False
|
"""
T: O(N)
S: O(1)
Time to travel between two points is the maximum of their coordinate
differences. Firstly, we can move diagonally, and cover MIN(D1, D2) distance.
After that, we start moving horizontally or vertically for ABS(D1, D2) units.
Combining these two measurements gives as MAX(D1, D2).
"""
from typing import List
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
total = 0
N = len(points)
for i in range(1, N):
y1, x1 = points[i-1]
y2, x2 = points[i]
d1, d2 = abs(y1-y2), abs(x1-x2)
total += max(d1, d2)
return total
|
"""
T: O(N)
S: O(N)
A good example of making a recursive solution into an iterative one.
For each node, we need to get to know the depths of their left and right
branches. Using this information, we find the diameter for the current node
and current node depth. The maximum seen diameter is the maximum diameter
of the tree.
"""
from typing import Dict, Optional
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
max_diameter = 0
if not root:
return max_diameter
node_depths = {None: 0} # type: Dict[Optional[TreeNode], int]
nodes_to_process = [root]
while nodes_to_process:
curr = nodes_to_process[-1]
left, right = curr.left, curr.right
if left and left not in node_depths:
nodes_to_process.append(left)
elif right and right not in node_depths:
nodes_to_process.append(right)
else:
_ = nodes_to_process.pop()
left_depth = node_depths[left]
right_depth = node_depths[right]
node_depths[curr] = 1 + max(left_depth, right_depth)
max_diameter = max(max_diameter, left_depth + right_depth)
return max_diameter
|
class Solution:
def validPalindrome(self, s: str) -> bool:
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
no_left = s[left+1:right+1]
no_right = s[left:right]
return self.is_palindrome(no_left) or \
self.is_palindrome(no_right)
left += 1
right -= 1
return True
def is_palindrome(self, s: str) -> bool:
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
|
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
forest = []
nodes_to_delete = set(to_delete)
def delete_nodes(node, is_root):
if node:
is_deleted = node.val in nodes_to_delete
if not is_deleted and is_root:
forest.append(node)
node.left = delete_nodes(node.left, is_deleted)
node.right = delete_nodes(node.right, is_deleted)
return None if is_deleted else node
delete_nodes(root, True)
return forest
|
"""
T: O(N)
S: O(1)
Move two pointers from the ends of both arrays. If we reach the beginning of
either array, we should if it is the first pointer. If so, we still have more
elements to copy using the second pointer.
"""
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
write_pointer = m + n - 1
nums1_pointer = m - 1
nums2_pointer = n - 1
while nums1_pointer >= 0 and nums2_pointer >= 0:
first = nums1[nums1_pointer]
second = nums2[nums2_pointer]
if first > second:
nums1[write_pointer] = first
nums1_pointer -= 1
else:
nums1[write_pointer] = second
nums2_pointer -= 1
write_pointer -= 1
while nums2_pointer >= 0:
nums1[write_pointer] = nums2[nums2_pointer]
write_pointer -= 1
nums2_pointer -= 1
|
"""
T: O(N**3)
S: O(N) -> does not consider output space
We move through the text and collect prefixes that are present in words.
When we seen an actual word, we add its position to the result.
"""
from typing import List
class Trie:
WORD_MARK = '*'
def __init__(self):
self.trie = {}
def insert(self, word: str) -> None:
trie = self.trie
for ch in word:
trie = trie.setdefault(ch, {})
trie[self.WORD_MARK] = {}
def full_match(self, word: str) -> bool:
trie = self.trie
for ch in word:
if ch in trie:
trie = trie[ch]
else:
return False
return self.WORD_MARK in trie
def starts_with(self, prefix: str) -> bool:
trie = self.trie
for ch in prefix:
if ch in trie:
trie = trie[ch]
else:
return False
return True
class Solution:
def indexPairs(self, text: str, words: List[str]) -> List[List[int]]:
trie = self.build_trie(words)
index_pairs = []
S = len(text)
for left in range(S):
for right in range(left, S):
curr_substring = text[left:right + 1]
if not trie.starts_with(curr_substring):
break
if trie.full_match(curr_substring):
index_pairs.append([left, right])
return index_pairs
def build_trie(self, words: List[str]) -> Trie:
trie = Trie()
for word in words:
trie.insert(word)
return trie
|
import random
class RandomizedCollection:
def __init__(self):
self.L = {}
self.N = []
def insert(self, val: int) -> bool:
result = val not in self.L
if result:
self.L[val] = set()
self.L[val].add(len(self.N))
self.N.append(val)
return result
def remove(self, val: int) -> bool:
if val not in self.L:
return False
loc = self.L[val].pop()
tail_index = len(self.N) - 1
if loc != tail_index:
last = self.N[-1]
self.N[-1], self.N[loc] = self.N[loc], self.N[-1]
self.L[last].remove(tail_index)
self.L[last].add(loc)
self.N.pop()
if not self.L[val]:
del self.L[val]
return True
def getRandom(self) -> int:
return random.choice(self.N)
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def twoSumBSTs(self,
root1: TreeNode,
root2: TreeNode,
target: int) -> bool:
min_stack, max_stack = [], []
while True:
while root1:
min_stack.append(root1)
root1 = root1.left
while root2:
max_stack.append(root2)
root2 = root2.right
if not min_stack or not max_stack:
return False
min_node, max_node = min_stack[-1], max_stack[-1]
total = min_node.val + max_node.val
if total == target:
return True
if total < target:
too_small = min_stack.pop()
root1 = too_small.right
else:
too_large = max_stack.pop()
root2 = too_large.left
|
"""
T: O(N)
S: O(N)
Remember numbers we have seen so far alongside their indices.
Return a sorted pair of indices when we see a number that is complement to the
previously seen one.
"""
from typing import Dict, List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen_nums = {} # type: Dict[int, int]
for i, num in enumerate(nums):
complement = target - num
if complement in seen_nums:
return [seen_nums[complement], i]
seen_nums[num] = i
return [-1, -1]
|
from typing import List
"""
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
class NestedInteger:
def __init__(self, value=None):
pass
def isInteger(self):
pass
def add(self, elem):
pass
def setInteger(self, value):
pass
def getInteger(self):
pass
def getList(self):
pass
class Solution:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
unweighted = weighted = 0
while nestedList:
unweighted += sum([x.getInteger() for x in nestedList
if x.isInteger()])
nestedList = sum([x.getList() for x in nestedList
if not x.isInteger()], [])
weighted += unweighted
return weighted
|
"""
T: O(N)
S: O(1)
To figure out the next number, we can observe that is it just a previous number
shifted to the left by one-bit with one bit value added to the right. The code
also demonstrates how to deal with the overflow issue using modulo.
"""
from typing import List
class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
answers = []
current_number = 0
for num in A:
current_number = (current_number * 2 + num) % 5
answers.append(current_number == 0)
return answers
|
"""
T: O(N)
S: O(1)
Iterate from the back, remember the max element to right, reassign the current
element before updating the max.
"""
from typing import List
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
max_right, N = -1, len(arr)
for i in reversed(range(N)):
arr[i], max_right = max_right, max(max_right, arr[i])
return arr
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.