text
stringlengths 37
1.41M
|
---|
# generate list of all odd numbers starting at 3 up to and including bound
def odds_list(bound):
"""
Returns list of odds from 3 to bound (inclusive if bound is odd).
"""
odds = [(x*2 + 1) for x in range(1,bound//2)]
if bound % 2 == 1:
odds.append(bound)
return odds
#print(generate_odds(11))
def primes_list(bound):
"""
Returns a list of all primes <= bound.
"""
if bound < 2:
raise ValueError('bound must be 2 or more')
bound_root = int(bound**(1/2.0))
odds = odds_list(bound)
# x*2+3: 0->3, 1->5, 2->7, 3->9, ...
# (x-3)/2: 3->0, 5->1, 7->2, ...
for i in range(0,len(odds)):
if odds[i] > bound_root: # only go up to root of bound (which could be prime)
break # any composite above that has a prime divisor less than it's root
if odds[i] != 0:
prime = odds[i]
ctr = 3*prime # 2*prime would be even, so skip it since we only have odd numbers in our odds list
while ctr <= bound:
j = (ctr-3)/2 # get odds index from number
odds[j] = 0 # set multiples of the prime to zero
ctr += 2*prime # our list only has odd ones, and adding one prime would make it even
result = [x for x in odds if x != 0]
result.insert(0,2)
return result
#print('result: ' + str(prime_list(1)))
def factorize(n, prime_list = []):
"""
Returns prime factorization of n.
Faster if given a prime_list of appropriate size, otherwise generates one.
TODO:
- use prime list if given, verify that prime_list[-1] >= n**(1/2.0), I assume it's prime if I haven't found a prime divisor <= n**(1/2.0)
"""
def test_and_remove(my_num, ctr, primes):
# handle 1 case
if my_num == 1:
return
# handle 2 case
if my_num%2 == 0:
if primes == []:
primes.append(list([ctr]))
else:
primes[-1].append(ctr)
if my_num / 2 == 1: # last run for a power of two
return
else:
test_and_remove(my_num / 2, 2, primes)
return
if ctr == 2:
ctr += 1
# handle non-2 case
my_root = my_num ** (1/2.0)
#print('test_and_remove(' + str(my_num) + ', ' + str(ctr) + ', ' + str(primes) + ')')
while ctr <= int(my_root):
#print('my_num: ' + str(my_num) + ', ctr: ' + str(ctr) + ', primes: ' + str(primes))
if my_num % ctr == 0:
if primes == []:
primes.append(list([ctr]))
elif ctr in primes[-1]:
primes[-1].append(ctr)
else:
primes.append(list([ctr]))
test_and_remove(my_num / ctr, ctr, primes)
return
ctr += 2
# final call
#print('final call')
if primes == []:
primes.append(list([my_num]))
elif my_num in primes[-1]:
primes[-1].append(my_num)
else:
primes.append(list([my_num]))
return
# if prime_list is given
def test_and_remove_known_primes(my_num, known_ix, primes, known_primes):
# handle 1 case
if my_num == 1:
return
my_root = my_num ** (1/2.0)
my_prime = known_primes[known_ix]
#print('test_and_remove(' + str(my_num) + ', ' + str(ctr) + ', ' + str(primes) + ')')
while my_prime <= int(my_root):
#print('my_num: ' + str(my_num) + ', ctr: ' + str(ctr) + ', primes: ' + str(primes))
if my_num % my_prime == 0:
if primes == []:
primes.append(list([my_prime]))
elif my_prime in primes[-1]:
primes[-1].append(my_prime)
else:
primes.append(list([my_prime]))
test_and_remove_known_primes(my_num / my_prime, known_ix, primes, known_primes)
return
known_ix += 1
my_prime = known_primes[known_ix]
# final call
#print('final call')
if primes == []:
primes.append(list([my_num]))
elif my_num in primes[-1]:
primes[-1].append(my_num)
else:
primes.append(list([my_num]))
return
if prime_list == []:
factorization = []
test_and_remove(n, 2, factorization)
return factorization
else:
#print('prime_list[-10:-1]: ' + str(prime_list[-10:-1]))
prime_list.append(n) # if I use a prime list up to the prime before int(n**1/2), I can get an index out of bounds, so I throw n on the end, though I'll never check it 'cause I only check up to n**1/2
factorization = []
test_and_remove_known_primes(n,0,factorization,prime_list)
return factorization
# get the primes, combine into factors, sum the factors
def get_factors(n):
if n < 1:
return []
factors = [1]
root_n = n**(1/2.0)
if n%2 == 0: # odd numbers cannot have even factors
start = 2
step = 1
else:
start = 3
step = 2
for i in range(start,n+1,step):
#print('i: ' + str(i) + ' root_n: ' + str(root_n) + ' n: ' + str(n) + ' factors: ' + str(factors))
if i >= root_n: # already have all factors larger than root_n, but n might be a square
if i == root_n: # if so, add the integer root
factors.append(i)
break
if n%i == 0:
factors.append(i)
factors.append(int(n/i))
factors.sort()
#print('factors: ' + str(factors))
return factors
def permute(instr): # returns ordered permutations!
#print(f'instr: {instr}')
if len(instr) == 1: # base case
return [instr]
subperms = []
for i in range(0,len(instr)):
#print(f'letter: {instr[i]}, instr: {instr}')
for subperm in permute(instr[:i] + instr[i+1:]):
#print(f'letter: {instr[i]}, subperm: {subperm}, instr: {instr}')
subperms.append(instr[i] + subperm)
return subperms
|
#csv-comma seperated value
#writin the data in csv file-->csv.writer(),to read csv.reader()
"""import csv
with open("sales.csv","w",newline='') as f: # if we dont give newline='' it will created a blank line on csv
w=csv.writer(f) # to write
w.writerow(["product_name","product_id","product_cost"]) #header
n=int(input("Enter the no of required products: "))
for each in range(n):
product_name=input("Enyer the product name: ")
product_id=input("Enter the product id: ")
product_cost=input("enter the product cost: ")
w.writerow([product_name,product_id,product_cost]) # assined values are inserted in row
print("Required product details are inserted successfilly")
"""
import csv
f=open("sales.csv","r")
w=csv.reader(f)
for a in w:
for b in a:
print(b,"\t\t",end='')
print()
|
"""basic data types
int
float
complex
string
"""
#float
x=2.1e78 #exponential form where big value is storing in less momeory
print(x)
print(type(x))
#complex number(X+YJ)whereY is imaginary part and X is real part
x=2+3j
print(x)
print(type(x))
#============================================================
x,y=0b11,0B101
z=0b101010
print(y)
print(x,y)
print(type(x))
#binary integer 0 - start with 0b or 0B base value is 2
#octal 0-7 start with 0o or 0O base value i s8
z=0o134
i=0o245
print(i)
print(z)
#hexadecimal(0-9) a-f or A-F start with 0x or 0X
i=0xfac9
k=0xaf346
print(k)
print(i)
#Typecasting
#integer to float
x=3
y=float(x)
print(type(y))
print(y)
#integer to string
c=str(3)
print(c)
print(type(c))
#ninteger to boolean
d=bool(x)
print(d)
#integer to complex
e=complex(x)
print(e)
# string to integer
"""f="hi"
g=int(f)
print(g)
#string to float
h=float(f)
print(h)
#string to complex
i=complex(f)
print(i)
"""
#float to integer
a=2.3
b=int(a)
print(b)
#float to str
c=str(a)
print(c)
#float to boolean
d=bool(a)
print(d)
#float to complex
e=complex(a)
print(e)
# boolean to integer
f=True
g=int(f)
print(g)
h=float(f)
print(h)
i=complex(f)
print(i)
g=str(f)
print(g)
#complex to inter str bool float
x=2+3j
y=str(x)
print(y)
#z=int(x)
#print(z)
#cant convert complex to string
#z=float(x)
#print(z)
# cant convert complex to float
z=bool(x)
print(z)
|
# Programming in Python 3, pag. 41
# Nùmeros Ascii tomados de: https://gist.github.com/yuanqing/ffa2244bd134f911d365
import sys
Zero = [" 0000 ", "00 00", "00 00", "00 00", " 0000 "]
One = ["1111 ", " 11 ", " 11 ", " 11 ", "111111"]
Two = [" 2222 ", "22 22", " 22 ", " 22 ", "222222"]
Three = [" 3333 ", "33 33", " 333", "33 33", " 3333 "]
Four = ["44 44", "44 44", "444444", " 44", " 44"]
Five = ["555555", "55 ", "55555 ", " 55", "55555 "]
Six = [" 6666 ", "66 ", "66666 ", "66 66", " 6666 "]
Seven = ["777777", " 77 ", " 77 ", " 77 ", "77 "]
Eight = [" 8888 ", "88 88", " 8888 ", "88 88", " 8888 "]
Nine = [" 9999 ", "99 99", " 99999", " 99", " 9999 "]
Digits = [Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine]
try:
digits = sys.argv[1]
row = 0
while row < 5:
line = ""
column = 0
while column < len(digits):
number = int(digits[column])
digit = Digits[number]
line += digit[row] + " "
column += 1
print(line)
row += 1
except IndexError:
print("usage: bigdigits.py <número>")
except ValueError as err:
print(err, "in", digits)
|
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 + -n2
def mul(n1, n2):
res = 0
for _ in range(abs(n2)):
if n2 > 0:
res += n1
elif n2 < 0:
res = sub(res, n1)
else:
return 0
return res
def div(n1, n2):
count = 0
res = abs(n1)
while res != 0:
if sub(res, abs(n2)) < 0:
return "Non-integeral answer."
res = sub(res, abs(n2))
count += 1
return count if n2 > 0 and n1 > 0 else -count
def exponent(n1, n2):
if n2 == 0:
return 1
elif n2 < 0:
return "Non-integeral answer."
res = n1
for _ in range(n2-1):
res = mul(res, n1)
return res
def components(expression):
exp_components = expression.split(' ')
return int(exp_components[0]), exp_components[1], int((exp_components[2]))
def compute(num1, operator, num2):
if num1 == 0 and num2 == 0 and operator == "/":
return "Not-defined."
if operator == "+":
return add(num1, num2)
elif operator == "-":
return sub(num1, num2)
elif operator == "*":
return mul(num1, num2)
elif operator == "/":
return div(num1, num2)
elif operator == "^":
return exponent(num1, num2)
else:
return "Operator unknown."
if __name__ == '__main__':
while True:
expression = raw_input("> ")
num1, operator, num2 = components(expression)
print(compute(num1, operator, num2))
|
import itertools
strng = raw_input("Enter small string > ")
perms = list(itertools.permutations(strng))
perm_strings = [''.join(x) for x in perms]
for permstr in perm_strings:
print(permstr)
|
import sys
def operate(symbol, n1, n2):
if symbol == "*":
return int(n1) * int(n2)
elif symbol == "/":
return int(n1) / int(n2)
elif symbol == "+":
return int(n1) + int(n2)
elif symbol == "-":
return int(n1) - int(n2)
# 5 * 5 + 3 - 2 -> ["5 * 5", "+ 3", " - 2"]
# doesn't follow order of operations.
def calculate(exp):
result = operate(exp[1], exp[0], exp[2])
for i in range(3, len(exp), 2):
result = operate(exp[i], result, exp[i+1])
return result
print(calculate(sys.argv[1].split()))
|
count_bottles = "{} bottles of beer on the wall, {} bottles of beer."
remove_bottle = "Take one down and pass it around, {} bottles of beer on the wall."
no_more = "No more bottles of beer on the wall, no more bottles of beer."
finisher = "Go to the store and buy some more, 99 bottles of beer on the wall."
if __name__ == '__main__':
for b in range(1, 100)[::-1]:
print(count_bottles.format(b, b))
print(remove_bottle.format(b-1 if b-1>0 else 'no more'))
print(no_more)
print(finisher)
|
import itertools
import sys
# takes a list of ints + target number.
# --> 2 ints that sum to target number, or None
def pair_sums(ls):
for pair in itertools.permutations(ls, 2):
yield (pair[0] + pair[1], pair)
target = int(sys.argv[1])
ls = map(int, sys.argv[2].split(" "))
print next((pair[1] for pair in pair_sums(ls) if pair[0] == target), None)
|
from itertools import chain
def split_in_chunks(ls, size):
newls = []
for i in xrange(0, len(ls), size):
newls.append(ls[i:i+size])
return newls
def reverse_chunks(chunks):
return [x[::-1] for x in chunks]
def flatten_chunks(chunks):
return list(chain(*chunks))
chunks = split_in_chunks(raw_input("list > ").split(), int(raw_input("chunk > ")))
reversedchunks = reverse_chunks(chunks)
flattenedchunks = flatten_chunks(reversedchunks)
print(' '.join(flattenedchunks))
|
import datetime
import sys
def int2day(i):
days = ["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"]
return days[i]
if __name__ == '__main__':
try:
day = int(sys.argv[1])
month = int(sys.argv[2])
year = int(sys.argv[3])
time = datetime.date(year, month, day)
print(int2day(time.weekday()))
except IndexError as e:
print("ERROR: Missing day, month or year.")
except ValueError as e:
print("ERROR: Day/month/year must be ints within appropriate value ranges.")
|
from random import randint, sample
from typing import Iterable
class Card:
def __init__(self):
self._rows = make_lotto_card()
self._numbers = set(n for row in self._rows for n in row if n != 0)
self._marked = set()
def __contains__(self, item):
return item in self._numbers
@property
def all_marked(self):
return not self._numbers
@property
def as_table(self):
table_str = []
for row in self._rows:
row_str = []
for n in row:
cell = 'XX' if n in self._marked else str(n or '').rjust(2)
row_str.append(cell)
table_str.append(row_str)
return table_str
def mark_number(self, number):
try:
self._numbers.remove(number)
except KeyError:
raise ValueError(f'{number} is not in card.')
self._marked.add(number)
def make_lotto_card():
card = [[0], [0], [0]]
while not all(map(valid_column, zip(*card))):
card = [make_row() for _ in range(3)]
return card
def make_row() -> list[int]:
def get_rand(column: int) -> int:
min_ = column * 10 or 1
max_ = column * 10 + 9 if column < 8 else 90
return randint(min_, max_)
row = sample([0, 1], counts=[4, 5], k=9)
return [get_rand(col) * i for col, i in enumerate(row)]
def valid_column(column: Iterable[int]) -> bool:
only_nums = [x for x in column if x != 0]
no_repeats = len(only_nums) == len(set(only_nums))
return no_repeats and 0 < len(only_nums) < 3
|
'''
A useful pd.Series feature is that index labels align for arithmetic
Series arithmetic is similar to a join on dB tables.
'''
import pandas as pd
dictionary = {'California':40000000, 'Texas': 29000000, 'Florida': 22000000, 'New York':19000000}
dict2 = {'California':40000000, 'Florida':22000000, 'Utah':3200000}
def addSeries(dict1=dictionary, dict2=dict2):
print("---addSeries()---")
series1 = pd.Series(dict1)
series2 = pd.Series(dict2)
return series1 + series2
def nameSeries(series=addSeries()):
print("---nameSeries()---")
series.name = 'Population'
series.index.name = 'State'
return series
if __name__ == "__main__":
print(addSeries())
print(nameSeries()) |
'''
Ranking assigns ranks from 1-N, where N is the number of valid data points in an array (along one axis)
NOTE: By default, equal values are assigned a rank that is the average of the ranks of those values.
'''
import numpy as np
import pandas as pd
series = pd.Series([7, -5, 7, 4, 2, 0, 4])
def showRank(series=series):
print("---showRank()---")
return series.rank()
'''
NOTE: Rank starts at 1, not 0
'''
def showRankExplainedFurther(orig=series):
print("showRankExplainedFurther()---")
series = showRank()
df = pd.DataFrame({'element': orig, 'rank': series})
print("These tuples show mappings between elements and their sorted (ranked) positions as (pos, element):")
return df
if __name__ == "__main__":
print(showRank())
print(showRankExplainedFurther()) |
'''
To analyze nutrient data, the nutrients for each food are being assembled into
a single large table. This requires multiple steps:
1) Convert each list of food nutrients to a DataFrame
2) Add a column for the food id
3) Append the DataFrame to a list
4) Concatenate the two DataFrames together
'''
import json
import matplotlib.pyplot as plt
import pandas as pd
dbPath = "D:/datasets/usda_food/database.json"
db = json.load(open(dbPath))
infoKeys = ['description', 'group', 'id', 'manufacturer']
info = pd.DataFrame(db, columns=infoKeys)
nutrients = []
for rec in db:
fnuts = pd.DataFrame(rec['nutrients'])
fnuts['id'] = rec['id']
nutrients.append(fnuts)
nutrients = pd.concat(nutrients, ignore_index=True)
if __name__ == "__main__":
print(nutrients)
# check for duplicates
numDuplicates = nutrients.duplicated().sum()
print("duplicates: {}".format(numDuplicates))
# drop duplicates
nutrients = nutrients.drop_duplicates().dropna()
print(nutrients)
# renaming 2 DF objs to distinguish
colMapping = {'description': 'food', 'group': 'fgroup'}
info = info.rename(columns=colMapping, copy=False)
print(info.info())
colMapping = {'description': 'nutrient', 'group': 'nutgroup'}
nutrients.rename(columns=colMapping, copy=False)
print(nutrients)
# made the 2 DF info and nutrients, now to merge (4)
ndata = pd.merge(nutrients, info, on='id', how='outer')
print(ndata.info())
print("ndata.iloc[30000]")
print(ndata.iloc[30000])
# plot of median values by food group and nutrient type
result = ndata.groupby(['fgroup'])['value'].quantile(0.5)
result['Zinc, Zn'].sort_values().plot(kind='barh')
plt.show() |
import itertools
firstLetter = lambda x: x[0]
names = ['Alan', 'Adam', 'Wes', 'Will', 'Albert', 'Steven']
for letter, names in itertools.groupby(names, firstLetter):
print(letter, list(names))
'''
Error about itertools is inaccurate. Could not find problem online with pylint
Output:
A ['Alan', 'Adam']
W ['Wes', 'Will']
A ['Albert']
S ['Steven']
names - becomes the list of keys grouped into (i.e. names is the generator)
firstLetter - the key that forms determines the groupings in names
'''
|
# Thenea Sun
# Dec. 18th
# A project about breakout game
import pygame, sys
from pygame.locals import *
import block
import random
pygame.init()
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 800
X_SPEED = 3
Y_SPEED = 4
main_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 32, 0)
pygame.display.set_caption("Break out game")
class Brick(pygame.sprite.Sprite):
def __init__(self, width, height, color):
# initialize sprite super class
# finish setting the class variables to the parameters
self.width = width
# Create a surface with the correct height and width
self.image =
# Get the rect coordinates
self.rect =
def main():
# Constants that will be used in the program
APPLICATION_WIDTH = 400
APPLICATION_HEIGHT = 600
PADDLE_Y_OFFSET = 30
BRICKS_PER_ROW = 10
BRICK_SEP = 4 # The space between each brick
BRICK_Y_OFFSET = 70
BRICK_WIDTH = (APPLICATION_WIDTH - (BRICKS_PER_ROW -1) * BRICK_SEP) / BRICKS_PER_ROW
BRICK_HEIGHT = 8
PADDLE_WIDTH = 60
PADDLE_HEIGHT = 10
RADIUS_OF_BALL = 10
NUM_TURNS = 3
# Sets up the colors
RED = (255, 0, 0)
ORANGE = (255, 165, 0)
YELLOW = (255, 255, 0)
GREEN =(0, 255, 0)
CYAN = (0, 255, 255)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Step 1: Use loops to draw the rows of bricks. The top row of bricks should be 70 pixels away from the top of
# the screen (BRICK_Y_OFFSET)
while True:
for event in pygame.event.get():
if event == QUIT:
pygame.quit()
sys.exit()
main()
|
# Softmax's goal is to give catagories to different classes that
# are non negative. It accomplishes this by using exponents
# the weights will be between 0 and 1 and add up to 1
import numpy as np
# Write a function that takes as input a list of numbers, and returns
# the list of values given by the softmax function.
def softmax(L):
expL = np.exp(L)
sum = 0
for index in expL:
sum += index
ans = []
for i in range(len(L)):
ans.append(expL[i]/sum)
return ans
# For an test run, the program uses L=[5,6,7]
print(softmax([5,6,7])) |
# We use variables to store data (int, string, ...,etc) in them
Fname= "Najeeb"
Anystring= "started to learn python with SaudiDevOrg."
# We use this character(+) to concatenate two or more strings
print(Fname +" "+ Anystring)
# Also we use this character(+) to add two or more numbers
num1=100
num2=500
print("The result of adding 100 with 500 is ",num1+num2)
# We can assign values to multiple variables in one line
str1, str2= "Success", "begins with a step forward!"
print(str1 +" "+ str2)
# We can assign the same value to multiple variables in one line
_var1 = _var2= "Progrmming with python is piece of cake!"
print(_var1)
print(_var2)
"""
We can't combine a number with a string
number, name= 20, "Ali"
print(number + name)
""" |
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around tha family",
"With a pocket full of shells"])
clarity_lyrics = ["You are the piece of me",
"I wish i didn't need",
"Chasing relentlessly",
"And I still don't know why"]
clarity = Song(clarity_lyrics)
# happy_bday.sing_me_a_song()
# bulls_on_parade.sing_me_a_song()
clarity.sing_me_a_song()
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import re
def register():
SpecialChar = ['$','@','#','%']
db = open('database.txt','r')
Username = input("Create username: ")
Password = input("Create password: ")
Password1 = input("Confirm password: ")
d = []
f = []
for i in db:
a,b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
#print(data)
if not re.search("@gmail.com$", Username):
print("Invalid,restart")
register()
else:
if Password != Password1:
print("Password don't match,restart")
register()
elif (len(Password)<5 or len(Password)>16):
print("length of Password should be greater than 5 and should be smaller than 16,restart")
register()
elif not any (char.isdigit() for char in Password):
print("Password should have at least one digit,restart")
register()
elif not any(char.isupper() for char in Password):
print("Password should have at least one uppercase letter,restart")
register()
elif not any(char.islower() for char in Password):
print("Password should have at least one lowercase letter,restart")
register()
elif not any(char in SpecialChar for char in Password):
print("Password should have at least one of the symbol $@#")
register()
#else:
#print("Password seems fine")
elif Username in d:
print("username exists")
register()
else:
db = open('database.txt','a')
db.write(Username+", "+Password+"\n")
print("Success!")
def access():
db = open('database.txt','r')
Username = input("Enter the username: ")
Password = input("Enter the password: ")
if not len(Username or Password)<1:
d = []
f = []
for i in db:
a,b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
try:
if data[Username]:
try:
if Password == data[Username]:
print("Login Success")
print("Hi,", Username)
else:
print("Password or Username is incorrect")
except:
print("Incorrect Password or Username")
else:
print("Username or Password dosen't Exist")
except:
print("Username or Password dosen't exist")
else:
print("Please Enter a value")
def ForgotPassword():
Username = input("Enter the Username:")
file1 = open('database.txt','r')
flag = 0
index = 0
for line in file1:
if Username in line:
flag = 1
break
if flag == 0:
print("Username doesn't Exist")
else:
print(line)
def home(option=None):
option = input("Login | Signup | ForgotPassword:")
if option == "Login":
access()
elif option == "Signup":
register()
elif option == "ForgotPassword":
ForgotPassword()
else:
print("Please enter an option")
home()
# In[ ]:
|
# Remember that Control+Alt+N will run code in Visual Studio Code
print "Hello"
print 'Hello'
# print Hello won't work because here Python sees Hello as a varible which we have not defined
hello = "Howdy"
print hello # this will work
# valid strings quiz
# Which are valid strings?
# My answer was "Ada" --> WRONG
#'"Ada' is also a valid string! (DUH!)
# If Ada was define it could be a valid string, but as written it is not
# Hello!!! quiz
# Define a variable, name, and assign to it a string that is your name.
name = "Joy" # correct
print hello + name
print "Hello " + name + "!!!" # this will add a space
|
# Greatest Quiz
# Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.
# My answer
def greatest2(list_of_numbers):
biggest = 0
for each in list_of_numbers:
if each > biggest:
biggest = each
return biggest
print greatest2([4,23,1])
#>>> 23
print greatest2([])
#>>> 0
# My answer with shortcuts...
def greatest(list_of_numbers):
if len(list_of_numbers) > 0:
return max(list_of_numbers)
else:
return 0
print greatest([4,23,1])
#>>> 23
print greatest([])
#>>> 0
# Video answer... the same as the first answer!
|
elements = {}
elements['H'] = {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794}
elements['He'] = {'name': 'Helium', 'number': 2, 'weight': 4.002602, 'noble gas': True}
print elements['H'] # print entire value associated with 'H'
print elements['H']['name'] # print one particular value from the 'H' dictionary
print elements['H']['weight']
# etc... |
# Udacify Quiz
# Define a procedure, udacify, that takes as
# input a string, and returns a string that
# is an uppercase 'U' followed by the input string.
# for example, when you enter
# print udacify('dacians')
# the output should be the string 'Udacians'
# MY ANSWER
def udacify(input):
return 'U' + input
# this worked
# Remove the hash, #, from infront of print to test your code.
print udacify('dacians')
#>>> Udacians
print udacify('turn')
#>>> Uturn
print udacify('boat')
#>>> Uboat
# Video answer:
def udacify(s):
return 'U' + s
# Print vs Return Quiz
# Which of the following will print?
def double1(x):
return 2 * x # this won't print
def double2(x):
print 2 * x # this will print
def double3(x):
return 2 * x
print 2 * x # this will print (APPARENTLY NOT, BECAUSE RETURN STATEMENT
# IS BEFORE PRINT STATEMENT, THE PRINT STATEMENT WILL NEVER BE EXECUTED!!)
def double4(x):
print 2 * x
return 2 * x # this will also print
# Video answer |
x=input("请输入累加值上限:")
while not str.isdecimal(x):
print("你是来搞笑的吧,输入数字呀!")
x = input("请输入累加值上限:")
t=int(x)
s=0
for i in range(1,t+1):
s+=i
print(s) |
from math import sqrt, pi, cos, sin, radians
from random import random, randint
from heapq import nlargest
from server.product import Product
def most_popular(products, n):
"""
Returns the `n` most popular products from `products`
"""
return nlargest(n, products, lambda p: p.popularity)
def gen_products(shop_id, count=10):
return sorted([gen_product(shop_id) for i in range(count)], key=lambda p: p.popularity * -1)
def gen_product(shop_id):
return Product(0, shop_id, 'title', random(), randint(1,100))
def flatten(list_of_lists):
"""
Flattens a list of lists.
"""
return [item for l in list_of_lists for item in l]
# A degree length at the equator equals ~ 111.111 km
km_per_degree = 111.111
def loc_in_range(location, r):
""" Computes a random GPS location within radius.
Due to west-east shrinking, a point can break the radius at high latitude.
For correct results, use within degrees: -75 < latitude < 75.
[more info](http://gis.stackexchange.com/questions/25877/how-to-generate-random-locations-nearby-my-location)
Parameters
----------
location : tuple of floats
The base location. Format: (latitude, longitude).
r : float
The limiting radius in km.
"""
r /= km_per_degree
u = random()
v = random()
w = r*sqrt(u)
t = 2*pi*v
x = w*cos(t)
y = w*sin(t)
x /= cos(radians(location[0]))
return location[0] + y, location[1] + x
def rand_loc():
""" Generates a random GPS location.
"""
lat = random() * 90 * 1 if randint(0, 1) % 2 == 0 else -1
lon = random() * 180 * 1 if randint(0, 1) % 2 == 0 else -1
return lat, lon
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 3 10:51:43 2021
@author: luciano
"""
def fatorial(n, show = False):
"""
Parameters
----------
n : int
DESCRIPTION: Número a ser calculado.
show : bool (opcional)
DESCRIPTION: Mostrar ou não a conta.
Returns
-------
f : int
DESCRIPTION: O valor do fatorial do número n
"""
f = 1
for c in range(n, 0, -1):
if show:
print(f'{c}', end = '')
if c > 1:
print(' x ', end = '')
else:
print(' = ', end = '')
f *= c
return f
print(fatorial(10, show = True)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 16 09:13:47 2021
@author: luciano
"""
num = []
while True:
n = int(input('Digite um valor: '))
if n not in num:
num.append(n)
print('Valor adicionado com sucesso...')
else:
print('Valor duplicado não vou adicionar ...')
r = str(input('Quer continuar ? [S/N] ')).upper()[0]
if r in 'N':
break
num.sort()
print(f'Os valores digitados foram: {num} ')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================
|| Created on Thu Sep 16 09:13:50 2021 ||
|| @author: luciano ||
=============================================
"""
lista = []
for i in range(0, 5):
n = int(input('Digite um valor: ') )
if i == 0 or n > lista[-1]:
lista.append(n)
print('Adcionado ao final da lista...')
else:
pos = 0
while pos < len(lista):
if n <= lista[pos]:
lista.insert(pos, n)
print(f'Adcionado na pos {pos} da lista.')
break
pos += 1
print('-=' * 30)
print(f'Os valores digitados em ordem foram {lista}') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 09:02:26 2020
@author: luciano
"""
a = input('Digite algo: ')
print('O tipo primitivo desse valor é: ', type(a))
print('So tem espaços ? ', a.isspace())
print('É um número ? ', a.isnumeric())
print('É alfabetico ? ', a.isalpha())
print('É alfanumérico ? ', a.isalnum())
print('Está em maiúsculas ? ', a.isupper())
print('Está e minusculas ? ', a.islower())
print('Está capitalizada ? ', a.istitle())
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 6 10:35:40 2021
@author: luciano
"""
def escreve(msg):
tam = len(msg) + 4
print('~'*tam)
print(f' {msg}')
print('~'*tam)
frase = str(input('Qual frase você quer escrever ? : '))
escreve(frase) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 7 21:50:49 2021
@author: luciano
"""
from datetime import date
ano = int(input('Que ano você quer analisar ? Digite 0 para analisar o ano atual.'))
if ano == 0:
ano = date.today().year
if ano % 4 == 0 and ano %100 !=0 or ano %400 == 0:
print('O ano {} é BISEXTO.'.format(ano))
else:
print('O ano {} não é BISEXTO.'.format(ano))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 16:07:42 2020
@author: luciano
"""
n = int(input('Entre com um número para ver sua tabuada: '))
print('-' * 12)
print('{} x 1 = {}'.format(n,n))
print('{} x 2 = {}'.format(n,2*n))
print('{} x 3 = {}'.format(n,3*n))
print('{} x 4 = {}'.format(n,4*n))
print('{} x 5 = {}'.format(n,5*n))
print('{} x 6 = {}'.format(n,6*n))
print('{} x 7 = {}'.format(n,7*n))
print('{} x 8 = {}'.format(n,8*n))
print('{} x 9 = {}'.format(n,9*n))
print('{} x 10 = {}'.format(n,10*n))
print('-' * 12) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 09:17:22 2021
@author: luciano
"""
from random import randint
computador = randint(0,10)
print('Sou seu computador... Acabei de pensar em um número entre 0 e 10.')
print('Será que você consegue adivinhar qual foi ?')
acertou = False
np = 0
while not acertou:
jogador = int(input('Qual seu palpite ? '))
np += 1
if jogador == computador:
acertou = True
else:
if jogador < computador:
print('Mais... tente mais uma vez.')
elif jogador > computador:
print('Menos... Tente mais uma vez.')
print('Acertou com {} tentativas. Parabéns !!'.format(np)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 15:53:42 2020
@author: luciano
"""
m = float(input('Um distancia em metros: '))
print('A medida de {}m corresponde a: '.format(m))
print('\n{}km'.format(m/1000))
print('\n{}hm'.format(m/100))
print('\n{}dam'.format(m/10))
print('\n{}dm'.format(10*m))
print('\n{}cm'.format(100*m))
print('\n{}mm'.format(1000*m))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 19:11:31 2021
@author: luciano
"""
from random import shuffle
n1 = str(input('Primeiro aluno: '))
n2 = str(input('Segundo aluno: '))
n3 = str(input('Terceiro aluno: '))
n4 = str(input('Quarto aluno: '))
alunos = [n1, n2, n3, n4]
shuffle(alunos)
print('A ordem de apresentação é: ')
print(alunos) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 29 13:17:53 2021
@author: luciano
"""
pessoa = {}
grupo = []
soma = media = 0.0
while True:
pessoa.clear()
pessoa['nome'] = str(input('Nome: ')).capitalize()
while True:
pessoa['sexo'] = str(input('Sexo [M/F]: ')).upper()[0]
if pessoa['sexo'] in 'MF':
break
print('ERRO ! Por favor, digite apenas M ou F.')
pessoa['idade'] = int(input('Idade: '))
soma += pessoa['idade']
grupo.append(pessoa.copy())
while True:
resp = str(input('Quer continuar ? [S/N] ')).upper()[0]
if resp in 'SN':
break
print('ERRO ! Por favor, digite apenas S ou N.')
if resp == 'N':
break
print(f'Ao todo temos {len(grupo)} pessoas cadastradas.')
media = soma/len(grupo)
print(f'A média de idade é de {media:5.2f} anos')
print(f'As mulheres cadastradas foram: ', end = '')
for p in grupo:
if p['sexo'] in 'F':
print(f'{p["nome"]}', end = ' ')
print()
print('Pessoas que estão com a idade acima da média: ', end = '')
for p in grupo:
if p['idade'] >= media:
print(' ', end = '')
for k, v in p.items():
print(f'{k} = {v}; ', end = ' ')
print()
|
from functools import reduce
def run():
my_list = [1,3,4,5,6,7,8,23,44,67,74]
# odd= [ i for i in my_list if i % 2 != 0]
odd = list(filter(lambda x : x%2 != 0, my_list)) # Funcion de orden superiro
#Recive dos parametros = Funcion and interable(Cualquer elemento que logre recorrerce)
print(odd)
odd2 = list(map(lambda x : x**2, my_list)) #
print(odd2)
all_multipied = reduce(lambda a,b: a * b, my_list)
print(all_multipied)
if __name__== "__main__":
run()
|
"""
3.3 Write a program to prompt for a score between 0.0 and 1.0. If
the score is out of range, print an error. If the score is between 0.0
and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
If the user enters a value out of range, print a suitable error message and exit.
For the test, enter a score of 0.85.
"""
score = input("Enter Score: ")
sc=float(score)
note=""
if sc>=0.0 and sc<=1.0:
if sc >=0.9:
note="A"
elif sc >=0.8:
note="B"
elif sc >=0.7:
note="C"
elif sc >=0.6:
note="D"
else:
note="F"
print(note)
else:
print("Error, out of range") |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
圣诞老人的礼物:
圣诞节来临了, 在城市A中圣诞老人准备分发糖果,现在有多箱不同的糖果
• 每箱糖果有自己的价值和重量
• 每箱糖果都可以拆分成任意散装组合带走
圣诞老人的驯鹿最多只能承受一定重量的糖果, 请问圣诞老人最多能带走 多大价值 的糖果
"""
class Solution(object):
def santa_gifts(self, W, boxes):
"""
:type W: int
:type boxes: List[tuple]
:rtype: void
"""
class Candy(object):
def __init__(self, v, w):
self.v = v
self.w = w
self.density = self.v / self.w
candies = []
for (v, w) in boxes: candies.append(Candy(v, w))
candies = sorted(candies, key=lambda c: c.density, reverse=True)
totalV = totalW = 0
for candy in candies:
if totalW + candy.w < W:
totalW += candy.w
totalV += candy.v
else:
totalV += (W - totalW) * candy.density
break
print('MAX_VALUE: %.1f' % totalV)
if __name__ == '__main__':
solution = Solution()
boxes = [
(100, 4), (412, 8), (266, 7), (591, 2)
]
solution.santa_gifts(15, boxes)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
寻路问题:
N个城市,编号1到N。城市间有R条单向道路。每条道路连接两个城市,有长度和过路费两个属性。
Bob只有K块钱,他想从城市1走到城市N。问最短共需要走多长的路。如果到不了N,输出-1
优化:
1) 如果当前已经找到的最优路径长度为L ,那么在继续搜索的过程中,总长度已经大于L的走法,就可以直接放弃。
2) 用midL[k][m] 表示:走到城市k时总过路费为m的条件下,最优路径的长度。若在后续的搜索中,再次走到k时,
如果总路费恰好为m,且此时的路径长度已经超过midL[k][m],则不必再走下去了。
"""
class Solution(object):
def roads_problem(self, N, K, roads):
"""
:type N: int
:type K: int
:type roads: List[tuple]
:rtype: int
"""
def dfs(start, totalLen, totalCost):
if start == N:
self.minLen = min(self.minLen, totalLen)
return
if start in roadsMap:
for (d, l, f) in roadsMap[start]:
if not visited[d]:
cost = totalCost + f
length = totalLen + l
if cost > K or length >= self.minLen: continue
if (d, cost) in midL and midL[(d, cost)] <= length: continue
midL[(d, cost)] = length
visited[d] = True
dfs(d, length, cost)
visited[d] = False
midL = {} # minL[(i, j)] 表示从1到i点的,花销为j的最短路径的长度
self.minLen = Infinite = 1 << 31 - 1
visited = [False] * (N + 1)
roadsMap = {}
for road in roads:
s = road[0]
if s in roadsMap:
roadsMap[s].append(road[1:])
else:
roadsMap[s] = [road[1:]]
visited[1] = True
dfs(1, 0, 0)
if self.minLen < Infinite: return self.minLen
return -1
if __name__ == '__main__':
solution = Solution()
roads = [
(1, 2, 10, 10),
(2, 3, 10, 10),
(2, 4, 15, 20),
(3, 4, 10, 10)
]
print(solution.roads_problem(4, 30, roads))
|
import os
import re
filename = os.path.join( "paragraph_2.txt")
# opening the text file and reading it
with open(filename, 'r') as file:
file_contents = file.read()
# finding the special character in the paragraph
p = re.compile('["?","!","(",")","=",">","+","."]')
# finding the letter/ character{A-Z, a-z, 0-9,-} in the paragraph
ty = re.compile('\w')
# counting the letter/ character{A-Z, a-z, 0-9,-} in the paragraph and special characters which results total number of letters
tot1 = (float(len(ty.findall(file_contents))))
tot= (float(tot1+(len(p.findall(file_contents)))))
print(file_contents)
# counting the ending punctiation marks
st= float((file_contents.count("?"))+ (file_contents.count("!")))
#Printing the analysis
print("Paragraph Analysis")
print("-----------------")
print("Approximate Word Count: "+ str(len(file_contents.split())+1))
print("Approximate Sentence Count: "+ str((file_contents.count(".")) + st))
print("Average Letter Count: "+ str(float(tot/len(file_contents.split()))))
print("Average Sentence Length: "+ str(float(len(file_contents.split())+1)/file_contents.count("."))) |
#!/usr/bin/env python3
from file_io import file_reader
from file_io import csv_writer
import sys
# Input and output file names
InFile = "examples/wikipedia.csv"
# InFile = sys.argv[1]
InFileName = InFile.split('\\').pop().split('/').pop().rsplit('.', 1)[0]
Data = file_reader.FileReader(InFile)
AllData = Data.extractdata(InFile)
#################################################################################################################################################
### Definition of useful functions to be used later
#################################################################################################################################################
# --------------------------------------------------------------- #
# Define a function to convert the csv data to nodes structure #
# --------------------------------------------------------------- #
# ---------------------- Start of Function ---------------------- #
def data_to_nodes(list_of_all_data):
node_list = []
for item in list_of_all_data:
if item[2] != "":
sublist = [item[0], item[1]] # Append the node id and timestamp to sublist if the identifiers is not empty
identifier_list = [] # This list will contain all the identifiers
identifiers = item[2].split(",")
for identifier in identifiers:
identifier_list.append(identifier)
sublist.append(identifier_list) # Append all the identifiers to sublist as a list
node_list.append(sublist)
return node_list
# ----------------------- End of Function ----------------------- #
# ------------------------------------------------------------------ #
# Define a function to convert the nodes list to csv desired format #
# ------------------------------------------------------------------ #
# ---------------------- Start of Function ---------------------- #
def nodes_to_formatted_nodes(list_of_nodes):
formatted_nodes = []
for item in list_of_nodes:
sublist = []
sublist.append(str(item[0]))
sublist.append(item[1])
sublist.append(','.join(map(str, item[2])))
formatted_nodes.append(sublist)
return formatted_nodes
# ----------------------- End of Function ----------------------- #
#################################################################################################################################################
###############################################################################
# #
# The Main Part of the Program Starts Here #
# #
###############################################################################
# =========================================================================== #
# Creation of nodes by calling the function defined above #
# =========================================================================== #
nodes = data_to_nodes(AllData)
# Formatting the nodes to make suitable for writing to desired csv file
nodes_formatted = nodes_to_formatted_nodes(nodes)
# Write nodes to a csv file
csv_writer.FileWriter.writeCSV(csv_writer,nodes_formatted,'output_files/'+InFileName+'-nodes.csv')
#for a in nodes_formatted:
# print(a)
#print('#################################################################################################################################################')
# =========================================================================== #
# Creation of Links between nodes. links is the list containing the links #
# =========================================================================== #
links = []
for ii, elem in enumerate(nodes[:-1]): # -1 is for keeping the elements to the second last sublist in nodes
for jj in range(ii + 1, len(nodes)):
common = set(elem[-1]).intersection(set(nodes[jj][-1])) # This -1 is for the identifiers, or to start looking at the list from backwards
if len(common) > 0 and common != {''}: # If you want to keep the empty identifiers then comment before the word "and"
links.append([elem[0], nodes[jj][0], ','.join(map(str, list(common)))]) # Append ID of node1 , ID of node2, and the common Identifiers\
# Common indetifiers are changed to list first and then to string
# Write links to a csv file
csv_writer.FileWriter.writeCSV(csv_writer,links,'output_files/'+InFileName+'-links.csv')
#for b in links:
# print(b)
print('#################################################################################################################################################')
# =========================================================================== #
# Creation of roots #
# =========================================================================== #
roots = []
unique = []
for elements in nodes:
for item in elements[2]:
if item not in unique:
roots.append([elements[0], item])
unique.append(item)
### Other way of doing it. Sets are more memory intensive that is why for bigger data I am not sure to use them. But one fact that they are fast for big data
'''unique = set() # This list is just for comparison of identifiers to avoid duplicates
for identity, _, identifiers in nodes:
for identifier in identifiers:
if identifier not in unique:
roots.append([identity, identifier])
unique.add(identifier)
print(roots)'''
# Write roots to a csv file
csv_writer.FileWriter.writeCSV(csv_writer,roots,'output_files/'+InFileName+'-roots.csv')
print(roots)
print('#################################################################################################################################################')
|
# Генерация целых чисел
def gen_prime(x):
multiples = []
results = []
for i in range(2, x+1):
if i not in multiples:
results.append(i)
for j in range(i*i, x+1, i):
multiples.append(j)
return results
import timeit
# Засекаем время
start_time = timeit.default_timer()
gen_prime(3000)
print(timeit.default_timer() - start_time)
print(timeit.timeit("gen_prime(3000)", setup="from __main__ import gen_prime", number=1)) |
from random import randint
import timeit
import copy
import random
def quickselect_median(arr, pivot_fn=random.choice):
if len(arr) % 2 == 1:
return quickselect(arr, len(arr) / 2, pivot_fn)
else:
return 0.5 * (quickselect(arr, len(arr) / 2 - 1, pivot_fn) +
quickselect(arr, len(arr) / 2, pivot_fn))
def quickselect(arr, k, pivot_fn):
"""
Выбираем k-тый элемент в списке arr (с нулевой базой)
:param arr: список числовых данных
:param k: индекс
:param pivot_fn: функция выбора pivot, по умолчанию выбирает случайно
:return: k-тый элемент arr
"""
if len(arr) == 1:
assert k == 0
return arr[0]
pivot = pivot_fn(arr)
lows = [el for el in arr if el < pivot]
highs = [el for el in arr if el > pivot]
pivots = [el for el in arr if el == pivot]
if k < len(lows):
return quickselect(lows, k, pivot_fn)
elif k < len(lows) + len(pivots):
# Нам повезло и мы угадали медиану
return pivots[0]
else:
return quickselect(highs, k - len(lows) - len(pivots), pivot_fn)
MIN_NUM = 1
MAX_NUM = 50
MIN_SIZE = 5
MAX_SIZE = 10
m = randint(MIN_SIZE, MAX_SIZE)
size = 2 * m + 1
array = [randint(MIN_NUM, MAX_NUM) for _ in range(size)]
arr1 = copy.copy(array)
print(f'Сгенерирован массив из 2*{m}+1 = {size} элементов:', array, sep='\n')
mediana = quickselect_median(array, pivot_fn=random.choice)
print(mediana)
print(f'test_2 (quickselect_median) {timeit.timeit("quickselect_median(arr1, pivot_fn=random.choice)", globals=globals(), number=100)} milliseconds') |
"""
Для шифрования строк предназначен модуль hashlib.
"""
import hashlib
'''
рара
рар
ра
р
а
ар
ара
'''
'''
Сохраняем хэши всех подстрок в множество.
Экономия на размере хранимых данных (для длинных строк) и
скорость доступа вместе с уникальностью элементов,
которые даёт множество, сделают решение коротким и эффективным.
'''
s = input("Введите строку из маленьких латинских букв: ")
r = set()
N = len(s)
for i in range(N):
if i == 0:
N = len(s) - 1
else:
N = len(s)
for j in range(N, i, -1):
print(s[i:j])
'''
возвращается как строковый объект двойной длины, содержащий только
шестнадцатеричные цифры. Это может использоваться для безопасного
обмена значениями в электронной почте или других недвоичных средах.
digest() - набор байтов
hexdigest() - строка
'''
r.add(hashlib.sha1(s[i:j].encode('utf-8')).hexdigest())
print(r)
print("Количество различных подстрок в строке '%s' равно %d" % (s, len(r)))
|
from collections import defaultdict
COUNT_ORG = int(input('Введите количество предприятий для расчета прибыли: '))
COUNTER = COUNT_ORG
ORGANISATION = defaultdict(list)
while COUNTER > 0:
NAME_ORG = input('Введите название предприятия: ')
PROFIT_ORG = input('через пробел введите прибыль данного '
'предприятия за каждый квартал(Всего 4 квартала): ').split(' ')
for el in PROFIT_ORG:
ORGANISATION[NAME_ORG].append(int(el))
COUNTER -= 1
NAMES_ORG = list(ORGANISATION.keys())
SUM_OF_ORG = 0
for el in NAMES_ORG:
ORGANISATION[el] = sum(ORGANISATION[el])
SUM_OF_ORG += ORGANISATION[el]
AVG_PROFIT = SUM_OF_ORG / COUNT_ORG
MAX_PROFIT = [el[0] for el in ORGANISATION.items() if AVG_PROFIT < el[1]]
MIN_PROFIT = [el[0] for el in ORGANISATION.items() if AVG_PROFIT > el[1]]
print(f'Средняя годовая прибыль всех предприятий: {AVG_PROFIT}')
print(f'Предприятия, с прибылью выше среднего значения: {", ".join(MAX_PROFIT)}')
print(f'Предприятия, с прибылью выше среднего значения: {", ".join(MIN_PROFIT)}') |
from tkinter import *
#set the settings of the window
window=Tk()
window.geometry('310x360') #set size
window.title('Calculator') #set title
window.config(background='coral') #set background
def quit() :
window.destroy()
exit()
#adding the exit buttom
exit=Button(window ,padx=78,pady=14,bd=4,bg="white",command=quit,text="Quit",font=("times",16,'bold')).place(x=50,y=300)
#adding a number or a sign to the screen(click operand)
def click (nbr) :
global nbr_on_screen
nbr_on_screen = nbr_on_screen + str(nbr)
entry.set(nbr_on_screen)
#clearing the screen
def clear() :
global nbr_on_screen
nbr_on_screen = ""
entry.set(nbr_on_screen)
#answering the operand :
def equal():
global nbr_on_screen
try:
nbr_on_screen=str(eval(nbr_on_screen))
entry.set(nbr_on_screen)
except :
nbr_on_screen = ""
entry.set(nbr_on_screen)
tkinter.messagebox.showerror("Error", "You\'ve made a false entry")
#set the screen
nbr_on_screen = ''
#set and show the screen :
entry=StringVar()
screen=Entry(window, font=("times",12,'bold'), textvariable=entry, width=30, bd=5, bg='white').place(x=50,y=15)
#set and show buttons of numbers :
#set and show nbr 1
button1=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(1),text="1",font=("times",16,'bold')).place(x=10,y=60)
#set and show nbr 2
button2=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(2),text="2",font=("times",16,'bold')).place(x=70,y=60)
#set and show nbr 3
button3=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(3),text="3",font=("times",16,'bold')).place(x=130,y=60)
#set and show nbr 4
button4=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(4),text="4",font=("times",16,'bold')).place(x=10,y=120)
#set and show nbr 5
button5=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(5),text="5",font=("times",16,'bold')).place(x=70,y=120)
#set and show nbr 6
button6=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(6),text="6",font=("times",16,'bold')).place(x=130,y=120)
#set and show nbr 7
button7=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(7),text="7",font=("times",16,'bold')).place(x=10,y=180)
#set and show nbr 8
button8=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(8),text="8",font=("times",16,'bold')).place(x=70,y=180)
#set and show nbr 9
button9=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click(9),text="9",font=("times",16,'bold')).place(x=130,y=180)
#set and show nbr 0
button0=Button(window ,padx=44,pady=14,bd=4,bg='white',command=lambda:click(0),text="0",font=("times",16,'bold')).place(x=10,y=240)
#set and show . :
button_dote=Button(window ,padx=16,pady=14,bd=4,bg='white',command=lambda:click("."),text=".",font=("times",16,'bold')).place(x=130,y=240)
#set and show buttons of signs :
#set and show +
button_plus=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click('+'),text="+",font=("times",16,'bold')).place(x=190,y=60)
#set and show
button_moins=Button(window ,padx=14,pady=14,bd=4,bg='white',command=lambda:click('-'),text="-",font=("times",16,'bold')).place(x=250,y=60)
#set and show *
button_multiplication=Button(window ,padx=15,pady=14,bd=4,bg='white',command=lambda:click('*'),text="X",font=("times",16,'bold')).place(x=190,y=120)
#set and show /
button_diviser=Button(window ,padx=15,pady=14,bd=4,bg='white',command=lambda:click('/'),text="/",font=("times",16,'bold')).place(x=250,y=120)
#set button for clear :
button_clear=Button(window ,padx=14,pady=44,bd=4,bg='white',command=clear,text="ce",font=("times",16,'bold')).place(x=190,y=180)
#set button for clear :
button_equal=Button(window ,padx=14,pady=44,bd=4,bg='white',command=equal,text="=",font=("times",16,'bold')).place(x=250,y=180)
def main() :
#show the window :
window.mainloop()
if __name__ == '__main__':
main() |
import turtle
turtle.setworldcoordinates(-600, -500, 600, 500)
turtle.speed(0)
for i in range(200):
turtle.left(90)
turtle.forward(i * 2)
turtle.exitonclick()
|
# read in data
def readInput(filename):
rawData = open(filename, "r").read().split("\n")
data = []
for value in rawData:
data.append(int(value))
return data
# Part 1
def solution_part1(data):
previous = {}
values = [-1, -1]
for value in data:
previous[2020 - value] = value
if (previous.get(value) != None):
values[0] = value
values[1] = previous[value]
result = values[0] * values[1]
print("Numbers: " + str(values))
return result
# Part 2
def solution_part2(data):
previous = {}
values = [-1, -1, -1]
for initialValue in data:
for value in data:
previous[2020 - initialValue - value] = value
if (previous.get(value) != None):
values[0] = value
values[1] = previous[value]
values[2] = initialValue
previous.clear()
result = values[0] * values[1] * values[2]
print("Numbers: " + str(values))
return result
data = readInput("inputs/Day1_input.txt")
print("2 Sum Result: " + str(solution_part1(data)))
print("3 Sum Result: " + str(solution_part2(data))) |
input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
word = ""
for character in input_quote:
if character.isalpha():
word += character
else:
if word and word[0].lower() >= "h":
print("\n", word.upper())
word = ""
else:
word = ""
if word.lower() >= "h":
print("\n", word.upper())
|
a =input('Enter the number :')
if int(a)%2==0:
print("even number")
elif int(a)%2!=0:
print('odd number')
else:
print('invalid input')
|
a=str(input("enter the word you want to append \n"))
b= ''
print(b + a)
|
a=int(input("Enter the size of array"))
count=[]
for i in range (0,a):
b=int(input("Enter the element:"))
count.append(b)
count.sort()
print(count)
|
a=int(input("Enter the number:"))
if a>=0:
for i in range (1,6):
print ("The number is :", i*a)
else:
print("Enter a positive number")
|
a = int (input('Enter the number you want to factorise'))
import math
print(math.factorial(a))
|
A = [int(x) for x in input("Enter elements: ").split(" ")]
# A.sort()
x = int(input("Enter no. to search: "))
def binarySearch(A, x, f, l):
mid = (f + l)//2
if l == f:
if A[mid] == x:
return mid
else:
return -1
else:
if A[mid] == x:
return mid
elif x < A[mid]:
return binarySearch(A, x, f, mid - 1)
else:
return binarySearch(A, x, mid+1, l)
print(binarySearch(A, x, 0, len(A)-1)) |
# nest_data_structures
crazy_landl_1 = {
'name': 'Boris',
'phone': '072423423',
'address_of_rent': 'Chelsea',
'age': 55
}
crazy_landl_2 = {
'name': 'Filipe',
'phone': '0646343434',
'address_of_rent': 'Comporta, Portugal',
'age': 28
}
nested_dictionary = {'boris': crazy_landl_1,
'filipe': crazy_landl_2
}
print(nested_dictionary.keys())
for key in nested_dictionary:
print(key)
for nest_key in nested_dictionary[key]:
print(nest_key, nested_dictionary[key][nest_key])
print(nested_dictionary[key])
for key in nested_dictionary
print(key)
data_nested = nested_dictionary[key]
print(data_nested)
print(data_nested['name'])
print(data_nested['address_of_rent'])
nest_list = [[1, 2, 3],[4, 5, 6]]
print(nest_list[0])
print(nest_list[1])
print(nest_list[1][0])
for data in nest_list:
print(data)
for num in data:
print(num * 20)
|
# Dictionaries
# Work with key and value paird
# Work like a real dictionary, you just lookup the information for the specific key
# The big difference with list is they are organised with index and here we use keys
# We just make a list of cringe_landlords, but we need more information like their phone numbers and address
# Syntax
dict_variable_name = {'key': 'value'}
boris_dict = {
'name': 'Boris',
'l_name': 'Johnson',
'phone': '07912333444',
'address': '10 Downing Street',
}
print(boris_dict)
print(type(boris_dict))
# Access one key value pair
# Follow the same principle of a list, but use keys not indexes
print(boris_dict['name'])
last_name = boris_dict['l_name']
print(last_name)
# Change the value of one key value paid
boris_dict['phone'] = '+7 34534543'
print(boris_dict)
# Assign a new key value pair
print(boris_dict)
boris_dict['home_phone'] = '+44 33534534534'
print(boris_dict)
boris_dict['budgets_passed'] = 0
print(boris_dict)
# The following lines do the same thing, but just increase the value by 1
boris_dict['budgets_passed'] += 1
boris_dict['budgets_passed'] += 1
print(boris_dict)
# Get all the keys
print(boris_dict.keys())
# Get all the values
print(boris_dict.values())
# Nested structures
|
# GETTING A NAME
def getting_name():
name = str(input("Name: "))
return name
def name_lenght(name):
tam = 0
for i in range(len(name)):
if name[i] != (""):
tam += 1
print(tam)
def main():
name = getting_name()
name_lenght(name)
main() |
"""
problem formalization:
you are given a list of strings. we say that 2 strings can be chained if the last letter of one of them is the first
letter of the next one ('hola', 'angle' -> 'holangle'). Check if the list of strings (in any order) can be chained in
a circle (every string can be chained to the next one, and the last string can be chained to the first one).
Create an EFFICIENT algorithm to solve the task.
-----------------------------------------------------------------------------------------------------------------------
Example:
input: ['banana', 'apple', 'egb']
output: True
input: ['sharon', 'itay', 'ziv']
output: False
-----------------------------------------------------------------------------------------------------------------------
Limitations:
time - 0.1 seconds
-----------------------------------------------------------------------------------------------------------------------
Testing:
After implementing your solution, test it with out given input by 'CheckSolution' file.
You have a total of 6 test:
- tests 1-3 are visible to you, and you can access it's input using 'get_input' method from utils.Test.
- test 4-6 is not visible to you, and need to pass it without knowing the input.
It is assured to you that all input is legal and fits the solution signature.
-----------------------------------------------------------------------------------------------------------------------
Documentation:
After passing all tests, write a doc in Confluence describing your solution.
In the doc, analyze the runtime of the algorithm you used.
"""
from typing import List
def string_chain_solution(lst: List[str]) -> bool:
""" Checks if the list of string can be chained
:param lst: list of lowercase no-spaces strings
:return: True if chaining is possible else False
"""
pass
|
"""
problem formalization:
you want to put an advertisement poster over a block of buildings. the block is made of several buildings with different
heights. you can use as many (consecutive) building as you would like, as long as the height of the poster doesn't
exceed the height of the buildings. find the largest possible area you can use for your poster.
note - the width of every building is 1.
Create an EFFICIENT algorithm to perform the given task.
-----------------------------------------------------------------------------------------------------------------------
Example:
input: heights = [1, 2, 3, 4]
output: 6
explanation - the poster will be hang from the second building to the last one (width 3) with height 2 (which is the
maximal possible height that does not exceed any of the building heights). notice that this is not the only way to
achieve this value, yet it's the maximal one.
-----------------------------------------------------------------------------------------------------------------------
Limitations:
time - 0.2 seconds
-----------------------------------------------------------------------------------------------------------------------
Testing:
After implementing your solution, test it with our given input by 'CheckSolution' file.
You have a total of 10 tests:
- tests 1-5 are visible to you, and you can access the input using 'get_input' method from utils.Test.
- tests 6-10 are not visible to you, and need to pass them without knowing the input.
It is assured to you that all input is legal and fits the solution signature.
-----------------------------------------------------------------------------------------------------------------------
Documentation:
After passing all tests, write a doc in Confluence describing your solution.
In the doc, analyze the runtime of the algorithm you used.
"""
from typing import List
def poster_solution(heights: List[float]) -> float:
""" Finds the biggest possible poster area
:param heights: the height of every building, according to their position
:return: the biggest possible poster area
"""
pass
|
"""
problem formalization:
you are trying to reach target from source, using some road system represented as directed graph. every road in this
system has a toll that has to be paid for using it. The company in charge of the toll values is now giving a special
discount - "for every trip on our roads, you get a discount for the next trip! the discount value equals to the toll
of the road with the highest toll you have been using!"
you currently have k dollars to use. you actually don't care to spend money now, and you are willing to drive in any
path from source to target as long as its total cost doesn't exceed k. yet, you know that tomorrow your son will be
using this road system, and you want to give him the highest discount you can achieve.
(Note - even if it means that you need to pay now more money that the discount will save you, find the biggest possible
discount. you didn't wake up in rational mood today..)
Find the biggest discount you can achieve for your son, without paying more than k dollars yourself.
Create an EFFICIENT algorithm to perform the given task.
-----------------------------------------------------------------------------------------------------------------------
Example:
input: roads and tolls shown in graph.jpg, source: 0, target: 3, k: 10
output: 8
-----------------------------------------------------------------------------------------------------------------------
Limitations:
time - 3.5 seconds
-----------------------------------------------------------------------------------------------------------------------
Testing:
After implementing your solution, test it with our given input by 'CheckSolution' file.
You have a total of 7 test:
- tests 1-4 are visible to you, and you can access the input using 'get_input' method from utils.Test.
- tests 5-7 are not visible to you, and need to pass them without knowing the input.
It is assured to you that all input is legal and fits the solution signature.
-----------------------------------------------------------------------------------------------------------------------
Documentation:
After passing all tests, write a doc in Confluence describing your solution.
In the doc, analyze the runtime of the algorithm you used.
"""
import networkx as nx
import os
import numpy as np
def discount_solution(path_to_graph: str, source: int, target: int, k: int) -> int:
""" Finds the biggest discount that can be achieved
:param path_to_graph: path to the road graph. tolls are edge-attributed under 'weight' label.
:param source: the desired source
:param target: the desired target
:param k: your maximal money bound
:return: value of the biggest discount.
"""
"""
idea:
we run dijkstra twice on the graph: one-source-multi-target, and multi-source-one-target.
now, we iterate all the edges. for any edge we can find the lowest-cost path passing through it by using the values
from dijkstra iterations above:
shortest path from source to u + weight of edge (u, v) + shortest path from v to target.
we start with 0 discount and whenever we find an edge with legal path passing through it and better discount, we
update it.
"""
g = nx.read_gpickle(os.path.join(os.getcwd(), path_to_graph))
from_source = nx.single_source_dijkstra_path_length(g, source)
reversed_graph = nx.DiGraph()
reversed_graph.add_weighted_edges_from([(v, u, w) for (u, v), w in nx.get_edge_attributes(g, 'weight').items()])
to_target = nx.single_source_dijkstra_path_length(reversed_graph, target)
tolls = nx.get_edge_attributes(g, 'weight')
discount = 0
for u, v in list(g.edges):
toll = tolls[(u, v)]
if u in from_source.keys() and v in to_target.keys():
if from_source[u] + toll + to_target[v] <= k:
discount = max(discount, toll)
return discount
|
"""
problem formalization:
In some sports league, teams are divided into divisions. Within each division, each team faces each rival several times.
At the end on the season, the top team in each division (the team with the highest amount of wins) proceeds to the
playoffs.
We are now sometime into the season, and you are given the current table in some division.
Fans of one of the teams want you to help them understand if their team can still make it to the playoffs.
Find out the teams that can still make it to the playoffs.
* For the exercise purpose, there is no tie-breaking rule. Every team that has the highest amount of wins makes it to
the playoffs.
Create an EFFICIENT algorithm to perform the given task.
-----------------------------------------------------------------------------------------------------------------------
Example:
Scenario:
3 teams: 0, 1, 2. state of wins is [3, 3, 0], state of loses is [1, 1, 4] (listed according to index).
We still have 2 games between every pair of teams. Can team 2 still make it?
Result:
Yes! If team 2 wins all of its games, and teams 0-1 beat each other exactly once each, team 2 will have the
highest amount of 4 wins.
Scenario:
6 teams: state of wins is [14, 14, 9, 5, 2, 1], state of loses is [1, 1, 6, 10, 13, 14].
We still have 1 game between every pair of teams. Can team 2 still make it?
Result:
No! even if team 2 we win all 5 of its games and reach 14 wins, in the 0-1 match one of the teams will proceed to 15
wins and team 2 cannot be the winner.
-----------------------------------------------------------------------------------------------------------------------
Limitations:
time - 3.5 seconds
-----------------------------------------------------------------------------------------------------------------------
Testing:
After implementing your solution, test it with our given input by 'CheckSolution' file.
You have a total of 6 test:
- tests 1-2 are visible to you, and you can access the input using 'get_input' method from utils.Test.
- tests 3-6 are not visible to you, and need to pass them without knowing the input.
It is assured to you that all input is legal and fits the solution signature.
-----------------------------------------------------------------------------------------------------------------------
Documentation:
After passing all tests, write a doc in Confluence describing your solution.
In the doc, analyze the runtime of the algorithm you used.
"""
from typing import List
def sport_elimination_solution(wins: List[int], losses: List[int], games_left: List[List[int]]) -> List[int]:
""" find the teams that can advance to the playoffs
:param wins: amount of current wins for each team
:param losses: amount of current losses for each team
:param games_left: amount of games left between every pair of teams. this matrix is symmetric and on the diagonal
all values are 0.
:return: list of the relevant teams
"""
pass
|
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next: return head
pre_node = ListNode(0)
pre_node.next = head
out = pre_node
next_node = head
i = 0
while next_node:
i += 1
if i % k == 0:
pre_node = self.reverse(pre_node, next_node.next)
next_node = pre_node.next
else:
next_node = next_node.next
return out.next
def reverse(self, pre_node, next_node): # pre_node:a
b = pre_node.next
c = b.next
while c != next_node:
b.next = c.next
c.next = pre_node.next
pre_node.next = c
c = b.next
return b
s = Solution()
list1 = ListNode(1)
list1.next = ListNode(4)
list1.next.next = ListNode(5)
list1.next.next.next = ListNode(6)
out = s.reverseKGroup(list1, 3)
while out:
print(out.val, end=" ")
out = out.next |
"""
验证给定的字符串是否为数字。
例如:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。
"""
class Solution:
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
sign_index = 0
exp_index = 0
dot_index = 0
num_index = 0
k_index = 0
for i in range(len(s)):
if s[i] == " ":
if dot_index or exp_index or sign_index or num_index:
k_index = 1
elif k_index == 1:
return False
elif s[i] == "e" or s[i] == "E":
if exp_index == 0 and num_index:
exp_index = 1
sign_index = 0
num_index = 0
dot_index = 0
else:
return False
elif s[i] == '+' or s[i] == "-":
if sign_index == 0 and dot_index == 0 and num_index == 0:
sign_index = 1
else:
return False
elif s[i] == '.':
if dot_index == 0 and exp_index == 0:
dot_index = 1
else:
return False
else:
if s[i].isdigit():
num_index = 1
sign_index = 1
else:
return False
if num_index:
return True
else:
return False
s = Solution()
print(s.isNumber(" -1.23e123")) |
# Definition for singly-linked list.
"""
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head: return None
n = 0
temp = head
while temp:
n += 1
temp = temp.next
k = k % n
if n == 1:
return head
pre_node = head
if k == 0:
return head
k = n - k - 1
while k > 0:
pre_node = pre_node.next
k -= 1
node = pre_node.next
pre_node.next = None
temp2 = node
while temp2.next:
temp2 = temp2.next
temp2.next = head
return node
link = ListNode(1)
link.next = ListNode(2)
# link.next.next = ListNode(3)
# link.next.next.next = ListNode(4)
# link.next.next.next.next = ListNode(5)
s = Solution()
res = s.rotateRight(link, 0)
while res:
print(res.val)
res = res.next
|
# -*- coding:utf-8 -*-
"""
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
"""
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 0 or len(nums) == 1: return True
i = 0
max_len = 0
start_point = 0
while i <= len(nums) - 1:
if nums[i] == 0:
return False
if i + nums[i] >= len(nums) - 1:
return True
for j in range(i + 1, i + nums[i] + 1):
if j + nums[j] >= len(nums) - 1:
return True
elif j + nums[j] > max_len:
max_len = j + nums[j]
start_point = j
i = max(i + 1, start_point + 1)
return False
s = Solution()
print(s.canJump([3, 2, 1, 0, 4])) |
from board import *
from tile import *
BOARD_SIZE = 5
def tile_value(player: Player, enemy_player: Player):
"""
The tiles in the middle have a higher value than those closer to edges.
"""
score = 0
tile_values = [[0, 1, 1, 1, 0],
[1, 2, 2, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 2, 2, 1],
[0, 1, 1, 1, 0]]
if player.first_piece:
score += tile_values[player.first_piece.tile.x][player.first_piece.tile.y]
if player.second_piece:
score += tile_values[player.second_piece.tile.x][player.second_piece.tile.y]
if enemy_player.first_piece:
score -= tile_values[enemy_player.first_piece.tile.x][enemy_player.first_piece.tile.y]
if enemy_player.second_piece:
score -= tile_values[enemy_player.second_piece.tile.x][enemy_player.second_piece.tile.y]
return score
def height_heuristic(game_state: Board, current_player: Player, enemy_player: Player):
score = game_state.get_height(current_player.first_piece.tile.x, current_player.first_piece.tile.y)
score += game_state.get_height(current_player.second_piece.tile.x, current_player.second_piece.tile.y)
score -= game_state.get_height(enemy_player.first_piece.tile.x, enemy_player.first_piece.tile.y)
score -= game_state.get_height(enemy_player.second_piece.tile.x, enemy_player.second_piece.tile.y)
return score
def available_adjacent_tiles(game_state: Board, current_player: Player, enemy_player: Player,
climbing_potential_factor: float = 1):
"""
Returns the amount of available tiles for a player to move minus the available tiles to move for the enemy player
"""
# get all possible move squares
current_player_legal_moves = game_state.get_legal_moves(current_player)
first_legal_move_tiles = {move.tile for move in current_player_legal_moves}
score = len(first_legal_move_tiles)
for move in current_player_legal_moves:
score += _get_climbing_potential(move.piece.tile, move.tile) * climbing_potential_factor
enemy_player_legal_tiles = game_state.get_legal_moves(enemy_player)
second_legal_move_tiles = {move.tile: move for move in enemy_player_legal_tiles}
score -= len(second_legal_move_tiles)
for move in current_player_legal_moves:
score -= _get_climbing_potential(move.piece.tile, move.tile) * climbing_potential_factor
return score
def _get_climbing_potential(from_tile: Tile, to_tile: Tile):
"""
Returns a factor of how much we can climb. From 0 to 1 -> 1 point, 1 to 2 -> 2 points etc
"""
if to_tile.height - from_tile.height == 1:
if to_tile.height == 3:
return 5
return to_tile.height
return 0
def _win_heuristic(game_state: Board, current_player: Player, enemy_player: Player):
if game_state.is_on_height_3(current_player):
return 100
if game_state.get_phase() == GamePhase.MOVE and not game_state.get_legal_moves(enemy_player):
return 100
return 0
def distance_heuristic(current_player: Player, enemy_player : Player):
player_score = 8
enemy_score = 8
cur_1 = current_player.first_piece.tile
cur_2 = current_player.second_piece.tile
enemy_1 = enemy_player.first_piece.tile
enemy_2 = enemy_player.second_piece.tile
player_score -= min(get_distance(cur_1, enemy_1), get_distance(cur_2, enemy_1))
player_score -= min(get_distance(cur_1, enemy_2), get_distance(cur_2, enemy_2))
enemy_score -= min(get_distance(cur_1, enemy_1), get_distance(cur_1, enemy_2))
enemy_score -= min(get_distance(cur_2, enemy_1), get_distance(cur_2, enemy_2))
return player_score - enemy_score
def get_distance(tile_1: Tile, tile_2: Tile):
counter = 0
while (tile_1.x != tile_2.x) and (tile_1.x != tile_2.y):
if tile_1.x > tile_2.x:
tile_1.x -= 1
if tile_1.y > tile_2.y:
tile_1.y -= 1
elif tile_1.y < tile_2.y:
tile_1.y += 1
elif tile_1.x < tile_2.x:
tile_1.x += 1
if tile_1.y > tile_2.y:
tile_1.y -= 1
elif tile_1.y < tile_2.y:
tile_1.y += 1
elif tile_1.x == tile_2.x:
if tile_1.y > tile_2.y:
tile_1.y -= 1
elif tile_1.y < tile_2.y:
tile_1.y += 1
counter += 1
return counter
def evaluation_function(game_state: Board, current_player: Player, enemy_player: Player):
score = 0
if game_state.get_phase() == GamePhase.SETUP:
return tile_value(current_player, enemy_player)
else:
score += 10 * tile_value(current_player, enemy_player)
score += 100 * height_heuristic(game_state, current_player, enemy_player)
climbing_potential_factor = 80
score += 20 * available_adjacent_tiles(game_state, current_player, enemy_player, climbing_potential_factor)
score += 200 * _win_heuristic(game_state, current_player, enemy_player)
score += 70 * distance_heuristic(current_player, enemy_player)
return score
|
def show_menu():
print('1.Citire date')
print('2.Cea mai lunga subsecventa cu prorpietatea ca toate numerele sunt pare')
print('3.Cea mai lunga subsecventa cu prorpietatea ca toate numerele au acelasi numar de divizori')
print ('4.Cea mai lunga subsecventa cu proprietatea ca toate numerele sunt prime')
print('5.Iesire')
def read_list():
lst=[]
lst_str=input('Dati numerele separate prin spatiu: ')
lst_str_split=lst_str.split(' ')
for num_str in lst_str_split:
lst.append(int(num_str))
return lst
def get_longest_all_even(lst:list[int]):
'''
Determina cea mai lunga subsecventa cu toate numerele pare
:param lst:lista in care se cauta subsecventa
:return:subsecventa gasita
'''
n=len(lst)
result=[]
for st in range(n):
for dr in range(st,n):
all_even=True
for num in lst[st:dr+1]:
if num % 2 != 0:
all_even=False
break
if all_even:
if dr-st+1>len(result):
result=lst[st:dr+1]
return result
def test_get_longest_all_even():
assert get_longest_all_even([1,2,3,4,6,8,5])==[4, 6, 8]
assert get_longest_all_even([1, 5, 3, 2, 6, 9, 5]) == [2, 6]
assert get_longest_all_even([1, 2, 3, 4, 6, 8, 5, 2, 4, 12, 20, 22]) == [2, 4, 12, 20, 22]
assert get_longest_all_even([1, 2, 4, 8, 3, 5, 7, 8, 5]) == [2, 4, 8]
def get_div_count(n):
'''
calculeaza numarul de divizori ai unui numar
:param n:numarul caruia vrem sa ii aflam divizorii
:return:numarul de divizori ai numarului n
'''
count=0
for i in range(1,n+1):
if n % i == 0:
count=count+1
return count
def get_longest_same_div_count(lst:list[int]):
'''
Determina cea mai lunga subsecventa cu acelasi numar de divizori
:param lst: lista in care se cauta subsecventa
:return: subsecventa ceruta
'''
n = len(lst)
result = []
div_count=get_div_count(lst[0])
for st in range(n):
for dr in range(st, n):
ok=True
for num in lst[st:dr + 1]:
if get_div_count(num)!=div_count:
div_count=get_div_count(num)
ok=False
break
if ok:
if dr - st + 1 > len(result):
result = lst[st:dr + 1]
return result
def test_get_longest_same_div_count():
assert get_longest_same_div_count([1, 2, 3, 5, 7, 8, 9])==[2, 3, 5, 7]
assert get_longest_same_div_count([1, 7, 4, 9]) == [4, 9]
assert get_longest_same_div_count([12, 4, 9, 1]) != [12]
assert get_longest_same_div_count([10, 2, 4, 9, 16, 1]) != [1]
def is_prime(n):
'''
Verifica daca un numar este prim
:param n: numarul care trebuie verificat
:return: True daca este prim si False in caz contrar
'''
if n<2:
return False
for i in range (2,n):
if n % i == 0:
return False
return True
def get_longest_all_prime(lst:list[int]):
'''
Determina cea mai lunga subsecventa cu toate numerele prime
:param lst: lista in care se cauta subsecventele
:return: cea mai lunga subsecventa cu proprietatea ceruta
'''
n = len(lst)
result = []
for st in range(n):
for dr in range(st, n):
all_prime = True
for num in lst[st:dr + 1]:
if is_prime(num)==False:
all_prime = False
break
if all_prime:
if dr - st + 1 > len(result):
result = lst[st:dr + 1]
return result
def test_get_longest_all_prime():
assert get_longest_all_prime([1, 2, 3, 5, 6, 9]) == [2, 3, 5]
assert get_longest_all_prime([10, 12, 23, 5, 7, 9]) == [23, 5, 7]
assert get_longest_all_prime([14, 22, 34, 5, 13, 90]) == [5, 13]
assert get_longest_all_prime([25, 2, 6, 55, 6, 9, 2, 3, 5]) == [2, 3, 5]
def main():
lst=[]
while True:
show_menu()
opt=input('Optiunea: ')
if opt=='1':
lst=read_list()
elif opt=='2':
print(get_longest_all_even(lst))
elif opt=='3':
print(get_longest_same_div_count(lst))
elif opt=='4':
print(get_longest_all_prime(lst))
elif opt=='5':
break
else:
print('Optiune invalida')
if __name__ == '__main__':
test_get_longest_all_even()
test_get_longest_same_div_count()
test_get_longest_all_prime()
main()
|
import sys
import commands
#get this of files that end with _pcm.csv
files = commands.getoutput("ls *.pcm.csv").split('\n')
if ("No such" in files[0]) or ("encontrado" in files[0]):
print "PANIC! I cannot find pcm.csv files!!!"
exit()
#get argument
time = float(sys.argv[1])
#open csv to write output
csv = open("parsed_pcm_output.csv", "w")
csv.write("operation;reqsize;cache;repetition;measurement;power_cpu;power_ram\n")
for filename in files:
#get test information from filename
lista = filename.split('.')[0].split('_')
operation = lista[0]
if "32" in lista[2]:
reqsize = 32
elif "4" in lista[2]:
reqsize = 4096
else:
print "PANIC! I dont understand whis filename"
print filename
exit()
if not ("cache" in lista[3]):
print "PANIC! I dont understand whis filename"
print filename
exit()
elif "comcache" in lista[3]:
cache = 1
else:
cache = 0
repetition = int(lista[4])
#read information from the file
arq = open(filename, "r")
cpu_index = -1
mem_index = -1
m=0
for linha in arq:
if ("System" in linha): #first line, just skip it
continue
elif "Date" in linha: #second line, well find out the position of what we are looking for
lista = linha.split(';')
if not ("Proc Energy (Joules)" in lista):
print "PANIC! I cannot find processor energy information here!"
print filename
arq.close()
exit()
cpu_index = lista.index("Proc Energy (Joules)")
mem_index = cpu_index+1
if not ("DRAM" in lista[mem_index]):
print "PANIC! Is this supposed to be about memory?",
print lista[mem_index]
print filename
arq.close()
csv.close()
exit()
else: #this line contains a measurement
lista = linha.split(';')
csv.write(operation+";"+str(reqsize)+";"+str(cache)+";"+str(repetition)+";"+str(m)+";"+str(float(lista[cpu_index])/time)+";"+str(float(lista[mem_index])/time)+"\n")
m+=1
arq.close()
csv.close()
|
#Problem 1725. Number Of Rectangles That Can Form The Largest Square
'''
You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.
You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4.
Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.
Return the number of rectangles that can make a square with a side length of maxLen.
Example 1:
Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]
Output: 3
Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
Example 2:
Input: rectangles = [[2,3],[3,7],[4,3],[3,7]]
Output: 3
Constraints:
1 <= rectangles.length <= 1000
rectangles[i].length == 2
1 <= li, wi <= 109
li != wi
'''
from collections import Counter
def countGoodRectangles(rec):
#bsae case:
if not rec:
return []
squares = []
#loop through each rectangle to find the k
for rectagle in rec:
squares.append(min(rectagle))
freq_of_each_dimension = Counter(squares)
return freq_of_each_dimension[max(squares)]
#Time complexity: O(n), we have to loop through the number of rectangles to find the k length.
#Space complexity: O(n), we have to store the the number of squares created
#Main function to run the test cases:
def main():
print("TESTING Number Of Rectangles That Can Form The Largest Square")
rec_1 = [[5,8],[3,9],[5,12],[16,5]]
rec_2 =[[2,3],[3,7],[4,3],[3,7]]
print(countGoodRectangles(rec_1))
print(countGoodRectangles(rec_2))
print("END OF TESTING...")
main()
|
#Leetcode 767. Reorganize String
'''
Problem statement:
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = "aab"
Output: "aba"
Example 2:
Input: S = "aaab"
Output: ""
Note:
S will consist of lowercase letters and have length in range [1, 500].
'''
import heapq
#Sort and extends method: linear search
def reorganizeString(S):
#base case:
if not S:
return None
N = len(S)
result = [None] * N
new_string = []
#sort the array based on the amount of times that they have
for word, frequency in sorted((S.count(x), x) for x in set(S)):
#base case:
if word > (N+1)/2:
return ""
#append the character with the most frequency into the new string
new_string.extend(word*frequency)
#interleave the contents into the array
result[::2], result[1::2] = new_string[N//2:], new_string[:N//2]
return "".join(result)
#time complexity: O(n)
#space complexity:O(n)
#Greedy and Heap approach:
def reorganizeString_GREEDY_HEAP(S):
#base case:
if not S:
return None
#create a queue that store all the character from the string into
#based on its frequency
queue = [(-S.count(x), x) for x in set(S)]
heapq.heapify(queue)
#base case: if the frequency of the charater is greater than half of the array then, return "" because it is impossible to produce an acurate answer
if any(-freq > (len(S)+1)/2 for freq, word in queue):
return ""
answer = []
while len(queue) >= 2:
#Pop out the current two most repeated elemenet from the array
freq_1, word_1 = heapq.heappop(queue)
freq_2, word_2 = heapq.heappop(queue)
answer.extend([word_1, word_2])
if freq_1+1:
heapq.heappush(queue, (freq_1+1, word_1))
if freq_2+1:
heapq.heappush(queue, (freq_2+1, word_2))
return "".join(answer) + (queue[0][1] if queue else "")
#main function to run the program
def main():
print("TESTING Reorganzing A String...")
S_1 = "aab"
S_2 = "aaab"
# print(reorganizeString(S_1))
# print(reorganizeString(S_2))
print(reorganizeString_GREEDY_HEAP(S_1))
print(reorganizeString_GREEDY_HEAP(S_2))
print("END OF TESTING...")
main() |
#1769. Minimum Number of Operations to Move All Balls to Each Box
'''
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.
In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.
Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.
Each answer[i] is calculated considering the initial state of the boxes.
Example 1:
Input: boxes = "110"
Output: [1,1,3]
Explanation: The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.
Example 2:
Input: boxes = "001011"
Output: [11,8,5,4,3,4]
Constraints:
n == boxes.length
1 <= n <= 2000
boxes[i] is either '0' or '1'.
'''
#Brainstorming:
'''
"110" => There are three box, and two box have one ball each and one box is empty
(1) (1)
a -> b -> c
(2)
"1": 1 ball
"0": no ball
[1, , ]
how to count the steps to get the ball from one bag to another?
- steps = abs(j-i)
To save time, we only want to perform the operations on the bags with ball and ignore bags with no balls.
How to only look at the bags with ball? And backtrack if the bags before the current bags has ball.
- Make a copy of the stirng but in an array form but only put in it the non-empty bags.
Example array = [1,1,NULL]
once we know where to look at, we can perform the search on the new array
just loop through the new search space and add the count together
=>GOALS: Return an array of answer with size n that contains the number of steps each operations would take to carray all the ball into that bag
'''
def minOperations(boxes):
n = len(boxes)
result = [0] * n
modified = [-1] * n
#loop through the original string and assign only the inde that containst the 1 value into the modified array
for i in range(n):
if boxes[i] == "1":
modified[i] = i
#loop through the modified array and count the steps it would take to move all the ball from other bags into it
for i in range(n):
result[i] = sum([abs(modified[j] - i) for j in modified if j != -1])
return result
#Main function to test the program:
def main():
print("TESTING Minimum Number of Operations to Move All Balls to Each Box...")
boxes = "110"
print(minOperations(boxes))
boxes = "001011"
print(minOperations(boxes))
print("END OF TESTING...")
main()
|
#Problem 1217. Minimum Cost to Move Chips to The Same Position
'''
We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:
position[i] + 2 or position[i] - 2 with cost = 0.
position[i] + 1 or position[i] - 1 with cost = 1.
Return the minimum cost needed to move all the chips to the same position.
Example 1:
Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.
Example 2:
Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.
Example 3:
Input: position = [1,1000000000]
Output: 1
Constraints:
1 <= position.length <= 100
1 <= position[i] <= 10^9
'''
def minCostToMoveChips(position):
#count the number of the odd and even chips
even_cnt = 0
odd_cnt = 0
for i in position:
#if the position is odd or even, we will add them to the counter
if i % 2 == 0:
even_cnt += 1
else:
odd_cnt += 1
return min(even_cnt, odd_cnt)
#Time complexity: O(N), where N is the number of i in position, because we just need to loop through them
#Space complexity: O(1), we only need to store even_cnt and odd_cnt
#main function to run the test case
def main():
print("TESTING MINIMUM COST TO MOVE CHIP INTO THE SAME POSITION")
p_01 = [1,2,3]
p_02 = [2,2,2,3,3]
p_03 = [1,1000000000]
print(minCostToMoveChips(p_01))
print(minCostToMoveChips(p_02))
print(minCostToMoveChips(p_03))
print("END OF TESTING...")
main() |
# 1. Factorial ****************************************************************************************
number = 6
product = 1
current = 1
while current <= number:
product *= current
current += 1
print(product)
# Solution:
while current <= number:
# multiply the product so far by the current number
product *= current
# increment current with each iteration until it reaches number
current += 1
# 2. Factorial with for *******************************************************************************
number = 6
product = 1
for index in range(1, number+1):
product *= index
print(product)
# Solution:
for num in range(2, number + 1):
product *= num
print(product)
# 3. Count by Check *************************************************************************************
start_num = 90 #provide some start number
end_num = 30 #provide some end number that you stop when you hit
count_by = 1 #provide some number to count by
if start_num < end_num:
while break_num <= end_num:
break_num += count_by
else:
result = "Oops! Looks like your start value is greater than the end value. Please try again."
print(result)
# Solution:
break_num = start_num
while break_num < end_num:
break_num += count_by
print(break_num)
# Solution 2:
if start_num > end_num:
result = "Oops! Looks like your start value is greater than the end value. Please try again."
else:
break_num = start_num
while break_num < end_num:
break_num += count_by
result = break_num
print(result)
# 4. Nearest Square *******************************************************************************
limit = 40
number = 1
while number**2 < limit:
nearest_square = number**2
number += 1
print(nearest_square)
# Solution:
limit = 40
num = 0
while (num+1)**2 < limit:
num += 1
nearest_square = num**2
print(nearest_square)
# 5. Your code should add up the odd numbers in the list, but only up to the first 5 odd numbers together
num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
num_list.sort()
index = 0
count = 0
total = 0
while count < 5 and index < len(num_list):
# print("Test print: {} ".format(num_list[index]))
if num_list[index] % 2 != 0:
total += num_list[index]
print(num_list[index])
count += 1
index += 1
else:
index += 1
print("Total: {}".format(total))
print(num_list[:10])
# Solution: it did not sort the list in order
num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
count_odd = 0
list_sum = 0
i = 0
len_num_list = len(num_list)
while (count_odd < 5) and (i < len_num_list):
if num_list[i] % 2 != 0:
list_sum += num_list[i]
count_odd += 1
i += 1
print ("The numbers of odd numbers added are: {}".format(count_odd))
print ("The sum of the odd numbers added is: {}".format(list_sum))
|
"""
Week 4 - Video 3 - Writing Files
"""
# to write in a file you first have to open it
# with the mode set for "write"...
openfile = open("some_file.txt", "wt")
"""
Modes for Writing
-------------------------------
w - write (erases the file first)
a - write (appends to the end of the file)
t - text (default)
b - binary
+ - open for read and write"""
print(type(openfile))
print(openfile)
openfile.close()
# now let's write to some files.
# but first...
def checkfile(filename):
"""
Read and print the contents of a file.
"""
datafile = open(filename, "rt")
data = datafile.read()
datafile.close()
print(data)
# write...
outputfile = open("some_file.txt", "wt")
# writelines() takes a list of strings and writes them to the file
outputfile.writelines(['first line\n', 'second line\n'])
# write() takes a single string and writes the entire sting to the file
outputfile.write('third line\nfourth line\n')
outputfile.close()
checkfile('some_file.txt')
# overwrite...
outputfile2 = open("some_file.txt", "wt")
outputfile2.write("overwriting the contents\n")
outputfile2.close()
checkfile("some_file.txt")
# append...
outputfile2 = open("some_file.txt", "at")
outputfile2.write("appending to contents\n")
outputfile2.close()
checkfile("some_file.txt")
|
"""
Course 3
Week 4 - Video 1 - Sorting
"""
# learn to use sorting routines that can be found
# in Python's library
import random
def double_space():
print('', '\n', '')
double_space()
print('normal list:')
data = list(range(1, 11))
print(data)
double_space()
random.shuffle(data) # randomly shuffles given data
print('shuffled list:')
print(data)
double_space()
data.sort()
print('sorted data:')
print(data)
double_space()
random.shuffle(data)
new_data = sorted(data) # sorted takes anything you can iterate over
print('reshuffled and resorted data using the sorted() function:')
print(new_data)
# now on to TUPLES!
double_space()
data_tup = tuple(data)
print('a tuple of my data:')
print(data_tup)
double_space()
data_tup_sort = sorted(data_tup) # returns the tuple as a sorted list
print('sorted tuple (now coverted into a list):')
print(data_tup_sort)
# and what about dictionaries??
double_space()
print('a dictionary:')
my_dict = {key: key ** 2 for key in data_tup}
print(my_dict)
double_space()
my_other_dict = sorted(my_dict)
print('the same dictionary ran with the sorted() function:')
print(my_other_dict) # returns a sorted list of the keys in a dictionary
print('hmmmmm....')
|
"""
Some more lesson examples for object oriented programming
"""
# INHERITANCE
class Animal():
def __init__(self):
print("Animal Created!")
def whoami(self):
print("Animal")
def eat(self):
print("Eating...")
class Dog(Animal):
def __init__(self):
# Animal.__init__(self)
print("Dog Created!")
def bark(self):
print("Woof!")
def fetch(self):
print("Fetching...")
freddy = Animal()
freddy.whoami()
freddy.eat()
print("")
bruce = Dog()
bruce.whoami()
bruce.eat()
bruce.bark()
bruce.fetch()
# SPECIAL METHODS
class Book():
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title : {}, Author: {}, Pages: {}".format(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print("Book burning! Oh no :()")
b = Book("Killer Bees", "Amanda", 250)
print(b)
print(len(b))
del b
|
"""
Week 2 - Video 1 - Lists
"""
# lists are created using []
empty = []
print(empty)
numbers = [1, 2, 3, 4, 5, 6]
print(numbers)
letters = ['a', 'b', 'c', 'd', 'e']
print(letters)
languages = ['python', 'javascript', 'c++', 'haskell', 'lisp']
print(languages)
# python allows you to mix types in a list,
# but you are STRONGLY advised NOT to do this.
mixed_list = ['hello', 10, True]
print(mixed_list)
print('')
# you can also create a list using the 'list' function
mylist = list()
print(mylist)
seq = range(5) # tells python to make a range of digits from 0 up to but not including 5
print(seq) # printing this out will tell you it's a range from what to what, but doesn't give all the digits
seq_list = list(seq) # but when you put this range into a list, all the digits show up
print(seq_list)
seq2 = range(7, 15)
print(seq2, list(seq2))
# you can also put 3 parameters to the range function
seq3 = range(4, 39, 5)
# this tells python to start at four and increase by 5 each time up to, but not
# including 39
print(list(seq3))
# furthermore, we can use negative numbers
seq4 = range(10, 2, -1)
print(list(seq4))
|
"""
Week 1 - Reading 1 - Formatting Strings
"""
print('')
# we can use the format function to add things into a string
first_name = 'Billy'
last_name = 'Joe'
print('My name is {} {}'.format(first_name, last_name))
print('')
# we can further make use of the format function to insert text out of order
# however, we still need to structure it.
spy1 = 'James'
spy2 = 'Bond'
print('My name is {1}, {0} {1}.'.format(spy1, spy2))
print('')
name1 = "Pierre"
age1 = 7
name2 = "May"
age2 = 13
line1 = "{0:^7} {1:>3}".format(name1, age1)
line2 = "{0:^7} {1:>3}".format(name2, age2)
print(line1)
print(line2)
print('')
num = 3.283663293
output = "{0:>10.3f} {0:>5.2f}".format(num)
print(output)
print('')
set1 = 'abc'
set2 = 'def'
set3 = 'ghi'
set4 = 'jkl'
set5 = 'mno'
set6 = 'pqr'
set7 = 'stu'
set8 = 'vwx'
set9 = 'y&z'
print("{0:>3} {8:>23}\n{1:>6} {7:>17}\n{2:>9} {6:>11}\n{3:>12} {5:>5}\n"
"{4:>15}\n{3:>12} {5:>5}\n{2:>9} {6:>11}\n{1:>6} {7:>17}\n{0:>3} {8:>23}"
.format(set1, set2, set3, set4, set5, set6, set7, set8, set9))
|
"""
Split strings such as emails using re
"""
import re
split_term = '@'
email = '[email protected]'
match = re.split(split_term, email)
print(match)
# alternative one liner
split_mail = '[email protected]'.split('@')
print(split_mail)
# find all instances!!
teacup = 'i\'m a little teacup, short and stout. here is my handle. here is my spout.'
print(re.findall('a', teacup))
count_a = len(re.findall('a', teacup))
print('there are {} a\'s in teacup'.format(count_a))
|
"""
Course 3
Week 1 - Reading 1 - Examples
"""
def space():
print('')
contact_list = {
'John Doe': '1-101-233-4567',
'Abe Froman': '1-800-728-7243',
'Betty Bean Ross': '1-888-123-4567'
}
print(
"""
\rLOOKUP A KEY
\r------------
"""
)
def lookup(contacts, name):
"""
Lookup name in contacts and return the phone number
or a message if name not in contacts.
"""
if name in contacts:
return contacts[name]
else:
return "Name Not In Contacts"
print(lookup(contact_list, "Abe Froman"))
print(lookup(contact_list, "Jose Virano"))
space()
# we can make this function even simpler using the GET function
def lookup2(contacts, name):
"""
Lookup name in contacts and return the phone number
or a message if name not in contacts.
"""
return contacts.get(name, "Name Not In Contacts")
print(lookup2(contact_list, 'John Doe'))
print(lookup2(contact_list, 'Henry John Frankfurt'))
space()
print(
"""
\rITERATE OVER DICTIONARY
\r-----------------------
"""
)
# we can iterate over a dictionary directly
def print_contacts(contacts):
"""
Prints the keys of a given contact list
"""
for name in contacts:
print(name)
print_contacts(contact_list)
space()
def print_contact_list(contacts):
"""
prints the keys and values of a given contact list
"""
for name in contacts:
print(name, ':', contacts[name])
print_contact_list(contact_list)
space()
print(
"""
\rORDER DICTIONARIES
\r------------------
"""
)
def ordered_contacts(contacts):
"""
Print the keys and values of a given contact list
in alphabetical order.
"""
keys = contacts.keys() # assigns a list of the keys in a dictionary to variable keys
names = sorted(keys)
for name in names:
print(name, ':', contacts[name])
ordered_contacts(contact_list)
space()
print(
"""
\rUPDATE A DICTIONARY
\r-------------------
"""
)
def add_contact(contacts, name, number):
"""
Adds a contact to an existing contact list
"""
if name in contacts:
print("Contact Already Exists")
else:
contacts[name] = number
add_contact(contact_list, 'Abe Froman', '1-800-728-7243')
add_contact(contact_list, 'Suzy Onli', '1-777-321-7654')
ordered_contacts(contact_list)
space()
def update_contact(contacts, name, newnumber):
"""
Updates an existing contacts number in given contact list
"""
if name in contacts:
contacts[name] = newnumber
else:
print('%s does not exist in contact list' % name)
update_contact(contact_list, 'Suzy Onli', '1-899-154-6433')
update_contact(contact_list, 'Henry Ford', '1-800-NEW-CARS')
ordered_contacts(contact_list)
# OR, if we wanted to add a contact that's not that or update an existing,
# we could do this...
def add_update_contact(contacts, name, number):
"""
Updates an existing contact and adds a new contact if contact doesn't
already exist
"""
contacts[name] = number
|
class Car(object):
def __init__(self, name, price, speed, fuel, mileage):
# creates new instance and defines all arguments except tax
self.name = name
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
# define tax requirements
if self.price >= 10000:
self.tax = 15
else:
self.tax = 12
# calls display method as soon as a new instance is created
self.display_all()
def display_all(self):
# displays info for each instance of class Car
print "-"*50
print "{}\n Price: ${}\n Speed: {}\n Fuel: {}\n Mileage: {}\n Tax: {}%".format(self.name, self.price, self.speed, self.fuel, self.mileage, self.tax)
# define 6 instances of Car class
car1 = Car('Red Car', 17000, '140mph', 'Full', '28mpg')
car2 = Car('Orange Car', 7000, '85mph', 'Empty', '36mpg')
car3 = Car('Yellow Car', 4000, '55mph', '3/4 Full', '22mpg')
car4 = Car('Green Car', 3600, '50mph', '1/2 Full', '18mpg')
car5 = Car('Blue Car', 11500, '120mph', 'Full', '34mpg')
car6 = Car('Purple Car', 2500, '60mph', '1/4 Full', '33mpg')
|
import random
"""Create a class called Car. In the__init__(), allow the user to specify the
following attributes: price, speed, fuel, mileage. If the price is greater than
10,000, set the tax to be 15%. Otherwise, set the tax to be 12%.
Create five different instances of the class Car. In the class have a method
called display_all() that returns all information about the car as a string.
In your __init__(), call this display_all() method to display information about
the car once the attributes have been defined.
A sample output would be like this:
Price: 2000
Speed: 35mph
Fuel: Full
Mileage: 15mpg
Tax: 0.12
"""
class Car(object):
def __init__(self, name, price, speed, fuel, mileage):
#init requires new isntance to define all arguments except tax
#if statement determines tax rate based on price
self.name = name
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price < 10000:
self.tax = 0.12
else:
self.tax = 0.15
self.display_all()
#calls display_all function with the creation of new instances
def display_all(self):
#displays specs for each instance in a single string;
#new line for each spec, all arguments inserted with {}.format()
print "{}\nPrice: ${}\nSpeed: {}\nFuel: {}\nMileage: {}\nTax: {}\n".format(self.name,self.price,self.speed,self.fuel,self.mileage,self.tax)
#creation of 5 new cars in class Car
car1 = Car('Red Car', 6000, '65mph', 'Full', '24mpg')
car2 = Car('Orange Car', 2000, '35mph', 'Half-Full', '15mpg')
car3 = Car('Yellow Car', 8000, '85mph', 'Half-Empty', '22mpg')
car4 = Car('Green Car', 4000, '50mph', 'Empty', '36mpg')
car5 = Car('Blue Car', 20000, '120mph', 'Full', '8mpg')
|
# parent class
class Animal(object):
def __init__(self, name):
self.name = name
self.health = 100
def walk(self, w=1):
self.health -= 1 * w
return self
def run(self, r=1):
self.health -= 5 * r
return self
def displayHealth(self):
print "\n{}'s current health is {}.".format(self.name, self.health)
class Dog(Animal):
def __init__(self, name):
super(Dog, self).__init__(name)
self.name = name
self.health = 150
def getPets(self, p=1):
self.health += 5 * p
return self
class Dragon(Animal):
def __init__(self, name):
super(Dragon, self).__init__(name)
self.name = name
self.health = 170
def displayHP(self):
print "I'M A FREAKING DRAGON!!!"
self.displayHealth()
def fly(self, f=1):
self.health -= 10 * f
return self
# created instances separately and then created commands - example:
# animal = Animal('Harold the Cat')
# animal.walk(3).run(2).displayHealth()
# but also wanted to show how you can chain the instantiation with the commands:
animal = Animal('Harold the Cat').walk(3).run(2).displayHealth()
dog = Dog('Pickles the Dog').walk(3).run(2).getPets(1).displayHealth()
dragon = Dragon('Rupert the Dragon').walk(3).run(2).fly(2).displayHP()
|
a = input("Enter the string : ")
l = list(a)
l.reverse()
l = "".join(l)
if l==a:
print("Palindrome")
else:
print("Nott palindrome") |
class person:
def __init__(self,name):
self.name = name
def dis(self):
print("Name : %s"%(self.name))
class teacher(person):
def __init__(self,name,exp):
super().__init__(name)
self.exp = exp
def display(self):
self.dis()
print("exp : %s"%(self.exp))
class hod(teacher):
def __init__(self,name,exp,sub):
super().__init__(name,exp)
self.sub = sub
def d(self):
self.display()
print("Sub is : %s"%(self.sub))
h = hod("Andrew","5","ML")
h.d() |
def avg(a,b):
return (a+b)/2
a,b = input("Enter two numbers : ").split(" ")
a,b = float(a),float(b)
print("Avg of %d & %d is %.f"%(a,b,avg(a,b))) |
print('''
3-Capitalize it
(48 Lines)
Many people do not use capital letters correctly, especially when typing on small devices like smart phones.
In this exercise, you will write a function that capitalizes the appropriate characters in a string. A lowercase
“i” should be replaced with an uppercase “I” if it is both preceded and followed by a space. The first
character in the string should also be capitalized, as well as the first non-space character after a “.”, “!” or
“?”. For example, if the function is provided with the string “what time do i have to be there? what’s the
address?” then it should return the string “What time do I have to be there? What’s the address?”. Include a
main program that reads a string from the user, capitalizes it using your function, and displays the result.''')
print('###############################################################################')
print('\n'*3)
minhaStr = input("Escreva a sua string: ")
inter = '?'
excl = '!'
point = '.'
nextCapitalize = False
Capitalized = ''
first = True
for letter in minhaStr:
if first:
myLet = letter.upper()
Capitalized += myLet
first = False
continue
if(letter == ' '):
Capitalized += ' '
continue
if(letter == inter or letter == excl or letter == point):
nextCapitalize = True
Capitalized += letter
continue
if(nextCapitalize):
myLet = letter.upper()
Capitalized += myLet
else:
myLet = letter.lower()
Capitalized += myLet
nextCapitalize = False
print(f"{Capitalized}")
#what time do i have to be there? what’s the address?
#What time do I have to be there? What’s the address? |
import random
Actual = random.randrange(1,100)
Guess = 0
while(Actual != Guess):
x = abs(Actual - Guess)
Guess = int(input())
if Guess < 0 or Guess > 100 :
print ("OUT OF RANGE")
elif Actual==Guess:
print("you make it")
break
elif abs(Actual - Guess) < x :
print(' you are closer to target ')
else :
print(' you are far from the target ') |
import time
from bstclass import BSTNode
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = [] # Return the list of duplicates in this data structure
# Populate a binary search tree containing the 'names_2' list's contents
bst_names_2 = BSTNode(names_2[0])
for nme in names_2:
bst_names_2.insert(nme)
# Iterate through the 'names_1' list and see if a duplicate exists
for nme in names_1:
# Does the BST structure contain the name being processed?
if bst_names_2.contains(nme):
# Match found -> add to our duplicates list
duplicates.append(nme)
end_time = time.time()
print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print (f"runtime: {end_time - start_time} seconds")
# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish? Thare are no restrictions on techniques or data
# structures, but you may not import any additional libraries that you did not write yourself.
|
from src.base.solution import Solution
from src.tests.part1.q207_test_course_schedule import CourseScheduleTestCases
"""
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1.
So it is impossible.
"""
class CourseSchedule(Solution):
def verify_output(self, test_output, output):
return test_output == output
def print_output(self, output):
super(CourseSchedule, self).print_output(output)
def gen_test_cases(self):
return CourseScheduleTestCases()
def run_test(self, input):
return self.canFinish(input[0], input[1])
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
WHITE = 0
GRAY = 1
BLACK = 2
class Node:
def __init__(self, val):
self.val = val
self.color = WHITE
self.children = []
stack = []
graph = dict()
for i in range(numCourses):
graph[i] = Node(i)
for pre in prerequisites:
graph[pre[0]].children.append(pre[1])
for node in graph.values():
# print(type(node))
if node.color == WHITE:
stack.append(node)
while stack:
# print(len(stack))
cur_node = stack[-1]
if cur_node.color == GRAY:
cur_node.color = BLACK
stack.pop()
else:
"""print(cur_node.val)
for node in graph.values():
print((node.val, node.is_visited, node.children))"""
cur_node.color = GRAY
for child in cur_node.children:
if graph[child].color == WHITE:
stack.append(graph[child])
elif graph[child].color == GRAY:
return False
return True
if __name__ == '__main__':
sol = CourseSchedule()
sol.run_tests() |
import sys
from src.base.solution import Solution
from src.tests.part1.q209_test_min_size_sub_sum import MinSizeSubSumTestCases
"""
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ? s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
"""
class MinSizeSubSum(Solution):
def print_output(self, output):
super(MinSizeSubSum, self).print_output(output)
def run_test(self, input):
return self.minSubArrayLen(input[0], input[1])
def gen_test_cases(self):
return MinSizeSubSumTestCases()
def verify_output(self, test_output, output):
return test_output == output
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
nlen = len(nums)
minlen = sys.maxint
ssum = 0
si = ei = 0
while ei <= nlen:
print(("before",ssum, si, ei))
if ssum < s:
if ei < nlen: ssum += nums[ei - 1]
ei += 1
else:
minlen = min(minlen, ei - si)
ssum -= nums[si]
si += 1
print(("after", ssum, si, ei))
if minlen == sys.maxint: minlen = 0
return minlen
if __name__ == '__main__':
sol = MinSizeSubSum()
sol.run_tests() |
import sys
def get_max(lst):
# Don't use the max function
max_val = -sys.maxint
for val in lst:
if val > max_val: max_val = val
return max_val
def get_median(lst):
lst.sort()
n = len(lst)
print(lst)
if n % 2 == 0:
return (lst[n/2-1] + lst[n/2]) / 2.0
else:
return (lst[n/2])
def get_first_uniq(lst):
first_uniq = None
flagger = set()
for val in lst[::-1]:
if val not in flagger:
flagger.add(val)
first_uniq = val
return first_uniq
def get_most_freq(lst):
most_freq_num, max_freq = None, 0
counter = dict()
for val in lst:
counter[val] = counter.get(val, 0) + 1
if counter[val] > max_freq:
most_freq_num = val
max_freq = counter[val]
return most_freq_num
if __name__ == '__main__':
# print get_max([4,5,2,1,6,8,9,10,3,2,1,2,6])
# print get_median([4,5,2,1,6,8,9,10,3,2,1,2,6])
# print get_median([4, 5, 2, 1, 6, 8, 9, 10, 3, 2, 1, 2, 6, 7])
# print get_first_uniq([4,5,2,1,6,8,9,10,3,2,1,5,4,2,6])
print get_most_freq([4,5,2,1,6,8,9,10,3,2,1,5,4,2,6]) |
from src.structures.treenode import TreeNode
import math
def to_complete_binary_tree(lst):
"""
Complete Binary Tree
:param lst: a list of tree nodes
:return:
"""
n = len(lst)
if n < 1: return None
tree = [TreeNode(lst[0])]
for i in xrange(1,n):
pidx = int(math.floor((i-1) / 2))
tree.append(TreeNode(lst[i]))
if tree[pidx].val == None or lst[i] == None:
continue
if i % 2 == 1:
tree[pidx].left = tree[i]
else:
tree[pidx].right = tree[i]
return tree[0]
def to_binary_tree_distinct_vals(lst):
"""
To build a binary tree
:param lst: list of list
[[root, left, right], [root, left, right]]
:return: head
"""
tree_dict = dict() # val : TreeNode(val)
for node in lst:
tree_dict[node[0]] = tree_dict.get(node[0], TreeNode(node[0]))
left_child = None
if node[1] is not None:
tree_dict[node[1]] = tree_dict.get(node[1], TreeNode(node[1]))
left_child = tree_dict[node[1]]
right_child = None
if node[2] is not None:
tree_dict[node[2]] = tree_dict.get(node[2], TreeNode(node[2]))
right_child = tree_dict[node[2]]
tree_dict[node[0]].left = left_child
tree_dict[node[0]].right = right_child
return tree_dict[lst[0][0]]
|
from src.base.solution import Solution
from src.tests.part1.q151_test_reverse_words import ReverseWordsTestCases
"""
https://leetcode.com/problems/reverse-words-in-a-string/#/description
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
click to show clarification.
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
"""
class ReverseWords(Solution):
def verify_output(self, test_output, output):
return test_output == output
def run_test(self, input):
return self.reverseWords(input)
def gen_test_cases(self):
return ReverseWordsTestCases()
def print_output(self, output):
super(ReverseWords, self).print_output(output)
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
res = ""
words = s.split(' ')
for word in words:
if len(word) == 0:
continue
res = word + " " + res
return res[:-1]
if __name__ == '__main__':
solution = ReverseWords()
solution.run_tests() |
from src.base.solution import Solution
from src.tests.part1.q139_test_word_break import WordBreakTestCases
"""
https://leetcode.com/problems/word-break/#/description
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
"""
class WordBreak(Solution):
def gen_test_cases(self):
return WordBreakTestCases()
def run_test(self, input):
return self.wordBreak(input[0], input[1])
def verify_output(self, test_output, output):
return test_output == output
def print_output(self, output):
print(output)
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
wd = set(wordDict)
n = len(s)
lkp = [False for _ in xrange(n + 1)]
lkp[0] = True
for k in xrange(1, n + 1):
i = 0
while i < k and not lkp[k]:
lkp[k] = lkp[i] and s[i:k] in wd
i += 1
# print(lkp)
return lkp[-1]
if __name__ == '__main__':
sol = WordBreak()
sol.run_tests()
|
class ColumnDataType(object):
"""
Superclass for defining a data type of a column
"""
def __init__(self, postgres_name):
self.postgres_name = postgres_name
class IntegerColumn(ColumnDataType):
def __init__(self):
ColumnDataType.__init__(self, postgres_name='INT')
class TextColumn(ColumnDataType):
def __init__(self):
ColumnDataType.__init__(self, postgres_name='TEXT')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.