text stringlengths 37 1.41M |
|---|
"""
operation_data.py
读写文件 csv/Excel表格
使用pandas
"""
import os
import xlrd
import pandas
import random
from xlutils.copy import copy
class OperationFile:
def __init__(self,filename:str):
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"\\data" # 相当于"../data"
self.filepath = os.path.join(base_path, filename) # 文件路径
if filename.split(".")[-1] == "csv":
self.file = pandas.read_csv(os.path.join(base_path,filename)) # 读取csv格式的文件
else:
self.file = pandas.read_excel(os.path.join(base_path,filename))
def get_data_to_list(self):
"""
将数据读取成列表嵌套列表格式
:return:
"""
return self.file.values.tolist()
def get_data_to_dict(self):
"""
将数据读取成列表嵌套字典格式
:return:
"""
return [self.file.loc[i].to_dict() for i in self.file.index.values]
def write_data_to_excel(self,data:list):
"""
更新表格
1.读取表格元数据
2.将新数据插入在第一行位置
3.将源数据追加在第一行之后
"""
# 读取源数据
old_data = self.get_data_to_list()
# 添加新数据在第一行
self.file.loc[0] = data # 指定插入行行号
# 将老数据追在在第一行之后
for i in range(1,len(old_data)+1):
self.file.loc[i] = old_data[i-1]
self.file.to_excel(self.filepath,index=None) # 保存数据
def write_data_col(self):
"""更新某一列数据"""
filepath = self.filepath
table = xlrd.open_workbook(filepath) # 打开表
new_table = copy(table) # 复制数据出来
new_sheet = new_table.get_sheet(0)
for i in range(1, 6): # 预计更新的数据个数,忽略首行
num = random.randint(1000000, 9999999) # 随机生成货号
new_sheet.write(i, 21, num) # 将货号写入excel表中对应的列中,i:表示行,22:代表货号所在列
new_table.save(filepath) # 保存跟新后的记录
def read_data(self):
self.write_data_col()
return self.get_data_to_dict()
if __name__ == '__main__':
oper = OperationFile("userdata.xls")
data = oper.get_data_to_list()
# data = oper.get_data_to_dict()
print(data) |
import numpy as np # to deal with array and matrix calculation easily
from sklearn.datasets.samples_generator import make_blobs # generate data
import matplotlib.pyplot as plt # to plot
import matplotlib.animation as animation # to animate the plot
import matplotlib.patches as mpatches # to add legends easily
# region variables
# K-means variables
X = None # features matrix
N_SAMPLES = 500 # number of sample to create artificially
K = 5 # value of k for the k-means algorithm
centroids = None # will be the centroids array
last_centroids = None # will keep in memory the previous array of centroids
# elbow method variables
ELBOW_METHOD = False # to choose to launch and see the elbow method for the current dataset
K_MAX = 20 # max value of k to test with the elbow method ( will test k from 1 to K_MAX)
# plot variables
INTERVAL = 500 # speed of the animation frame (ms)
fig = plt.figure(1, figsize=(8, 4.5)) # to plot
ax = fig.add_subplot(1, 1, 1) # the axes
ani = None # to animate the plot
started = False # indicates if the program is started
first_frame = -1 # indicates the first frame number to know the current iteration value
# choose the color respectively to the centroids (add color to have more than K = 10)
colors = {0: '#FF00FF', 1: '#999999', 2: '#2F9599', 3: 'red', 4: 'blue',
5: 'yellow', 6: 'pink', 7: 'orange', 8: 'brown', 9: 'purple'}
# endregion
# region load dataset
def load_dataset():
"""
Make an artificial dataset with random centered values
:return: the dataset with point of coordinates (x, y) in [0, 30]x[0, 30]
"""
X, _ = make_blobs(n_samples=N_SAMPLES, centers=25, n_features=2, cluster_std=2)
return X + 15 # + 15 to have positive values (not needed of course)
# endregion
# region K-means
def euclidean_distance(X, centroid):
"""
Calculate the euclidean distance between the samples and a given centroid
:param X: matrix of sample coordinates
:param centroid: given centroid from which the distance is calculated
:return: array of each distance between the samples a the centroid
"""
# Calculation of the distance of each coordinate's dimension to the centroid coordinate value associated
coord_difference_to_square = (X - np.full(X.shape[1], centroid, dtype=np.ndarray))**2
# Return the euclidean distance value
return coord_difference_to_square.sum(axis=1, keepdims=True)**0.5
def nearest_centroid(X, centroids):
"""
Indicates the associated centroid (index of the centroid in the array) for each sample of X
:param X: matrix of sample coordinates
:param centroids: array of centroids
:return: index array of the associated centroid for each sample
"""
# Create an array
# (used to be stacked with arrays of euclidean distances from each sample to each centroid)
dist_to_centroids = np.full((X.shape[0], 1), float('inf'))
# Calculate for each centroid the euclidean distance from each sample
for i, centroid in enumerate(centroids):
# Stack the distance arrays to form a matrix
dist_to_centroids = np.hstack((dist_to_centroids, euclidean_distance(X, centroid)))
# Return the index of the nearest centroid for each sample
return np.argmin(dist_to_centroids, axis=1) - 1 # - 1 as the first index if the unused fulled-'inf' array
def adjust_centroid(X, nearest_centroid_array, current_centroids):
"""
Calculate the mean coordinates of the associated samples for each centroid
:param X: matrix of sample coordinates
:param nearest_centroid_array: array of index of the nearest centroid for each sample
:param current_centroids: current centroid coordinates
:return: the updated coordinates for each centroid as an array
"""
# Calculation of the updated coordinate for each centroid
for i, centroid in enumerate(np.unique(nearest_centroid_array)): # for each centroid
# pick up the indexes of nearest samples
nearest_samples_index = np.where(nearest_centroid_array == centroid)
# pick up their coordinates
nearest_samples_coord = X[:][nearest_samples_index]
# Calculate the mean coordinate for new coordinate of centroid
new_coord = np.mean(nearest_samples_coord, axis=0)
# change the centroid
current_centroids[i] = new_coord
return current_centroids
def calculate_cost(X, current_centroids):
"""
Calculation the cost with the current centroids
:param X: matrix of sample coordinates
:param current_centroids: current centroids
:return: cost of the k_means step
"""
# Work as the the nearest_centroid() method
# but return the sum of min values of euclidean distances for each samples to the centroids
# (not the array of indexes of nearest centroid for each sample )
# Create an array
# (used to be stacked with arrays of euclidean distances from each sample to each centroid)
dist_to_centroids = np.full((X.shape[0], 1), float('inf'))
for i, centroid in enumerate(current_centroids):
# Stack the distance arrays to form a matrix
dist_to_centroids = np.hstack((dist_to_centroids, euclidean_distance(X, centroid)))
# Return the sum of min values of euclidean distances for each samples to the centroids
return sum(np.amin(dist_to_centroids, axis=1))
def k_means(frame_number):
"""
K-means algorithm (main function)
:param frame_number: frame number of the matplotlib.animation
"""
global centroids, first_frame, last_centroids
# Wait for the program to start
if started:
# To know if it is the first time the k_means() function is called
if first_frame == -1: # keep the first frame value
first_frame = frame_number # indicates the first frame value
centroids = np.random.rand(K, 2) * np.array([0, 30]) # create random centroids on the x2-axis
last_centroids = centroids[:] / 2 # to make sure to have different values
# If an update is necessary (or while not converging)
if not np.array_equal(centroids, last_centroids):
# display the current centroid and associated sampels
display(frame_number - first_frame)
# keep the current centroid before the adjustments to know if there is a convergence
last_centroids = np.array(centroids)
# pick up the nearest centroid indexes of each samples
nearest = nearest_centroid(X, centroids)
# adjust the current centroids
centroids = adjust_centroid(X, nearest, centroids)
# endregion
# region Elbow method
def elbow_method(k_max=K_MAX):
"""
Elbow method : calculate the cost at the convergence of k_means algo for a range of k values
:param k_max: indicate the range of k values to test (from 1 to k_max)
"""
# Initialize the cost array
cost_array = np.full(k_max, 0)
# calculation the cost at the convergence of k_means algo for each k value
for k, cost in enumerate(range(1, k_max + 1)):
k_centroids = np.random.rand(k + 1, 2) * np.array([0, 30]) # create random centroids on the x2-axis
# Initialize an array to keep the last centroid values to know when there is a convergence
last_centroids = np.array([])
# Update the centroid while not convergence
while not np.array_equal(k_centroids, last_centroids):
# keep the current centroid before the adjustments to know if there is a convergence
last_centroids = np.array(k_centroids)
# pick up the nearest centroid indexes of each samples
nearest = nearest_centroid(X, k_centroids)
# adjust the current centroids
k_centroids = adjust_centroid(X, nearest, k_centroids)
# calculation of the current cost
cost = calculate_cost(X, k_centroids)
# keep the cost at the convergence
cost_array[k] = cost
# display the elbow method curve
display_elbow(cost_array)
# endregion
# region display
def display(iteration=0):
"""
Display the k_means algorithm
:param iteration: number of current iteration/step
"""
global centroids
# clear the plot
ax.clear()
# set the labels to describe the plot
ax.set_xlabel("x1") # first feature
ax.set_ylabel("x2") # second feature
ax.set_xlim(0, 30) # fix the x1 axis
ax.set_ylim(0, 30) # fix the x2 axis
# wait for the program to start
if started:
# add a big legend to describe the state of the k_means algorithm
label = 'K-means :\n'
label += 'K : {0}\n'.format(K)
label += 'Iteration : {0}\n'.format(iteration)
label += 'Cost : {0}\n'.format(round(calculate_cost(X, centroids), 3))
# add the created legend
plt.legend(handles=[mpatches.Patch(label=label)])
# pick up the nearest centroid to have the respective color of each sample
nearest = nearest_centroid(X, centroids)
# plot each sample
for i, sample in enumerate(X):
ax.scatter(sample[0], sample[1], c=colors[nearest[i]])
# plot each centroid
for i, centroid in enumerate(centroids):
ax.scatter(centroid[0], centroid[1], c=colors[i], edgecolors='black')
else: # if the program is not started
# plot each sample as black points (no centroid yet)
for i, sample in enumerate(X):
ax.scatter(sample[0], sample[1], c='black')
def display_elbow(cost_array):
"""
Display the elbow method algorithm
:param cost_array: array of cost for each k
"""
fig_elbow = plt.figure(2) # to plot the elbow method
ax_elbow = fig_elbow.add_subplot(1, 1, 1) # the axes of the elbow method graph
# set the labels to describe the plot
ax_elbow.set_title('Elbow method for k to 1 to' + str(K_MAX))
ax_elbow.set_xlabel('k')
ax_elbow.set_ylabel('cost')
ax_elbow.set_ylim(0, np.max(cost_array)*1.1) # fix the cost axis
# plot the elbow curve
ax_elbow.plot(range(1, len(cost_array) + 1), cost_array) # the axes
def key_pressed(event):
"""
To start to run the programme by enter key
:param event: key_press_event
"""
if event.key == 'enter':
global started
started = not started
# endregion
if __name__ == '__main__':
X = load_dataset() # load artificial dataset
if ELBOW_METHOD: # launch the elbow method if it is chosen
elbow_method()
# connect to the key press event to start the program
fig.canvas.mpl_connect('key_press_event', key_pressed)
# to animate the plot and launch the gradient descent update
ani = animation.FuncAnimation(fig, k_means, interval=INTERVAL)
display() # first plot
plt.show() # show the plot
|
class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def delete(self):
self.items = []
OPTR = Stack()
OPND = Stack()
intNumber = []
for n in range(10):
intNumber.append(str(n))
def isInt(x):
for n in intNumber:
if(x == n): return 1
return 0
def LISPadd(str):
sum = 0
i = 0
s = list(str)
while(True):
if(s[i] != ')'):
OPTR.push(s[i])
#print(OPTR.items)
else:
OPND = Stack()
while(OPTR.peek() != '+'):
OPND.push(OPTR.pop())
for t in OPND.items:
sum += int(t)
OPTR.pop()
OPTR.pop()
if(OPTR.is_empty() == True):
break
i += 1
return sum
a = "(+(+(+12)(+34))(+(+56)(+78)))"
b = "(+45)"
print(LISPadd(a)) |
'''
per ricaricare lo script usa
import importlib
importlib.reload(module)
or
from importlib import reload
reload(module)
https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module
'''
import numpy as np
from random import randint
def fun():
print("hello world from the function")
def sigmoid(x):
'''
the function return the sigmoid of the given argument
x = single value or array
y = single value or array
'''
y = 1 / (1 + np.exp(-x) )
return y
def prediction(w, x):
'''
w = weight vector (1 x d)
x = feature vector (1 x d)
y = output value, product of the two vectors above (scalar)
'''
#x = np.array([[1], x])
print("w dim:", w.shape)
print("x dim:", x.shape)
y = np.dot(w, x.T)
return y
def error(Y_hat, Y):
'''
Y_hat: predicted value (1 x M array)
Y: real value (1 x M array)
error : computed error (1 x M array)
'''
print("y_hat dim:", Y_hat.shape)
print("y_hat dim:", Y.shape)
if(Y_hat.shape != Y.shape):
return -1
error = np.dot( (Y_hat - Y), (Y_hat - Y).T )
return error
def normalize(x):
'''
x = vector to normalize (1 x m)
y = normalized vector (1 x m)
'''
tot = np.sum(x)
y = x / tot
return y
def computePower(x, exp):
'''
x = value to be considered (scalar)
exp = exponential to be considered
y = returned value (1 x exp)
with
y = [x, x^2, x^3, ..., x^exp]
'''
y = np.zeros((1, exp))
print(y.shape)
for i in range(1, exp+1):
y[0, i-1] = x ** i
return y
def computeVectorPower(x, exp):
'''
x = value to be considered (1 x m)
exp = exponential to be considered
y = returned value (1 x (m x exp) )
with
y = [x[0], x[0]^2, x[0]^3, ..., x[0]^exp, x[1], x[1]^2, x[1]^3, ..., x[1]^exp, ..., x[m]^exp]
'''
print(x.shape)
a, b = x.shape
y = computePower(x[0, 0], exp)
for i in range(1, b):
#y = [y, computePower(x[0, i], exp)]
local = computePower(x[0, i], exp)
y = np.append(y, local)
return y
def addOne(x):
'''
add "1" as first entry of the vector
x = inpute vector (1 x m)
y = output vector (1 x (m+1) )
'''
y = x
y = np.append(1, y)
return y
def writingTest():
end = False
lastWord = ""
correct = 0
wrong = 0
dictionary = ["siege","niederlage","grenzen","wahnsinn", "guck mal","hohenflieger",
"enttauscht","entdecken","streiten","gewicht","gewalt","himmel","ho:lle",
"zwar","zufall","bleastigung","nun","zuverla:ssig","krigen"]
while(end == False):
i = randint(0, len(dictionary)-1)
while(lastWord == dictionary[i]):
i = randint(0, len(dictionary)-1)
correct_string=dictionary[i]
#print(correct_string + ": ")
local = input(correct_string + ": ")
if(local != correct_string and local != 'q'):
print("ERROR")
wrong = wrong + 1
elif (local == correct_string):
correct = correct + 1
if local == 'q':
print("correct = ", correct)
print("wrong = ", wrong)
end = True
lastWord = correct_string
def isFull(x):
for i in range(1,len(x)):
if(x[i] == 0):
return False
return True
def printString(word, found):
'''
word = string to be printed
found = array used to print the string (1 = letter has been found, 0 = no)
'''
print(word[0], end="", flush=True)
for i in range(1, len(word)):
if(found[i] == 1):
print(" " + word[i], end="", flush=True)
else:
print(" _", end="", flush=True)
print();
def hangedMan():
word = "test"
found = [0]
guessed = ""
end = False
for i in range(1, len(word)):
found.append(0)
#print(len(found))
printString(word, found)
while (end == False):
guessed = input()
#check if guessed word is presend in the word
for i in range(1, len(word)):
if (word[i] == guessed):
found[i] = 1
printString(word, found)
end = isFull(found)
print("gg ez")
def isCharOrNumber(x):
if(x >= 'a' and x <= 'z'):
return True
if(x >= 'A' and x <= 'Z'):
return True
if(x >= '0' and x <= '9'):
return True
def wordCounter():
'''
conta le parola nella stringa passata
'''
inword = False
wordNumber = 0
string = input()
for i in range(0, len(string)):
if(isCharOrNumber(string[i]) and inword == False):
inword = True
wordNumber = wordNumber + 1
if(string[i] == ' '):
inword = False
print("total w c is : " + str(wordNumber))
wordCounter()
#hangedMan()
#writingTest()
#x = np.array([[1,2,3]])
#print(addOne(x))
#print(computeVectorPower(x, 4))
#a = np.loadtxt("file.txt")
|
COVERAGE = 400
length = float(input("Enter the length of the room in feet: "))
width = float(input("Enter the width of the room in feet: "))
height = float(input("Enter the height of the room in feet: "))
coats = float(input("Enter the number of coats in the room: "))
surface_area = (length * width) + (2 * length * height) + (2 * width * height)
coverage_needed = surface_area * coats
cans_of_paint_required = coverage_needed / COVERAGE
print("The number of paint cans you require: ",cans_of_paint_required)
|
import doctest
"""
We cannot implement code to determine vector length because of the fact that zeroes
are not shown in the sparse vectors. We could determine all the zeroes in between and
before known values (e.g. {2:5, 6:3} would have a total of 5 zeroes). However, we could have
many trailing zeroes, so first we must ask the team if any exist.
If the highest key in a sparse vector is assumed to be the highest, only then could
we determine length.
"""
def sparse_add(vector_one, vector_two):
"""
Add the common key values of two dictionaries and store the sum in a new dictionary.
:param vector_one: dictionary with integers
:param vector_two: dictionary with integers
:return: a dictionary with all common vectors added
>>> sparse_add({}, {})
{}
>>> sparse_add({0: 4, 1: 5, 2: 7}, {0: 3, 1: 4, 3: 9})
{0: 7, 1: 9, 2: 7, 3: 9}
>>> sparse_add({0: -5, 4: -3}, {0: 5, 4: 3})
{}
>>> sparse_add({2: 4, 6: 8, 3: 5}, {})
{2: 4, 6: 8, 3: 5}
>>> sparse_add({0: -5, 4: -3}, {0: 5, 4: 3})
{}
"""
vector_sum = {}
for key in vector_one.keys():
if key not in vector_two.keys():
vector_sum[key] = vector_one[key]
else:
vector_sum[key] = vector_one[key] + vector_two[key]
for key in vector_two.keys():
if key not in vector_one.keys():
vector_sum[key] = vector_two[key]
for key in list(vector_sum):
if vector_sum[key] == 0:
del vector_sum[key]
return vector_sum
def main():
doctest.testmod()
print(sparse_add({0: 1, 3: 4, 6: 5}, {2: 1, 4: 7, 10: 4}))
if __name__ == "__main__":
main()
|
import random
import time
#👌 -> rock, ✌ -> scissors, 🙌 -> Scissors
moves = ['✌','🙌','👌']
user = input('hi user.Whats your name?\n')
def play():
time.sleep(2)
print('ready.....')
time.sleep(2)
print(random.choice(moves))
points = 1
while points <= 3:
play()
print('Score is ',points,sep=' ')
point_claim = input("Did you win/lose the move? If Yes press True else False:\t")
if point_claim == 'True':
points += 1
elif point_claim == 'False': points -= 1
else:
pass
print('You Win',user,'!',sep=' ')
|
# Scraping Numbers from HTML using BeautifulSoup In this assignment you will write
# a Python program similar to http://www.py4e.com/code3/urllink2.py. The program will
# use urllib to read the HTML from the data files below, and parse the data, extracting numbers
# and compute the sum of the numbers in the file.
# We provide two files for this assignment. One is a sample file where we give you
# the sum for your testing and the other is the actual data you need to process for the assignment.
# Sample data: http://py4e-data.dr-chuck.net/comments_42.html (Sum=2553)
# Actual data: http://py4e-data.dr-chuck.net/comments_691289.html (Sum ends with 46)
# To run this, download the BeautifulSoup zip file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
suma=0
# Retrieve all of the anchor tags
tags = soup('span')
for tag in tags:
# Look at the parts of a tag
print('TAG:', tag)
#print('URL:', tag.get('href', None))
print('Contents:', tag.contents[0])
#print('Attrs:', tag.attrs)
suma=suma+int(tag.contents[0])
print('la suma de los comentarios es:',suma) |
import math
n = int(input("Digite um número inteiro: "))
fator = math.factorial(n)
print(fator) |
def conta_letras(frase, contar="vogais"):
if contar == "vogais":
return conta_vogais(frase)
else:
return conta_consoantes(frase)
def conta_vogais(frase):
vogal = 0
frase = frase.lower()
for i in frase:
if ord(i) == 97 or ord(i) == 101 or ord(i) == 105 or ord(i) == 111 or ord(i) == 117:
vogal += 1
return vogal
def conta_consoantes(frase):
consoante = 0
frase = frase.lower()
for i in frase:
if ord(i) != 97 and ord(i) != 101 and ord(i) != 105 and ord(i) != 111 and ord(i) != 117 and ord(i) != 32:
consoante += 1
return consoante
|
import math
x1 = float(input("Digite a 1ª coordenada x: "))
y1 = float(input("Digite a 1ª coordenada y: "))
x2 = float(input("Digite a 2ª coordenada x: "))
y2 = float(input("Digite a 2ª coordenada y: "))
x = (x1 - x2) ** 2
y = (y1 - y2) ** 2
d = math.sqrt(x + y)
if d >= 10:
print("longe")
else:
print("perto") |
valor = int(input("Digite um número inteiro: "))
resto1 = valor % 3
resto2 = valor % 5
if resto1 == 0 and resto2 == 0:
print("FizzBuzz")
else:
print(valor) |
class Robot:
"""repersents a robot, with a name."""
population = 0
def __init__(self,name):
"""initializes the data"""
self.name = name
print(f'initializing {self.name}')
Robot.population += 1
def die(self):
"""i amd dying"""
print(f'{self.name} is being destroyed!')
Robot.population -= 1
if Robot.population == 0:
print(f'{self.name} was the last one')
else:
print(f'there are still {Robot.population} robots working')
def say_hi(self):
"""greeting by the robot. Yeah"""
print(f'hi my master call me {self.name}')
@classmethod
def how_many(cls):
print(f'we have {cls.population} robots')
droid = Robot('알파고1')
droid.say_hi()
droid2 = Robot('알파고2')
droid2.say_hi()
droid3 = Robot('알파고3')
droid3.say_hi()
Robot.how_many()
droid3.die()
droid2.die()
droid.die()
Robot.how_many() |
# # 계산기
# import os
#
# while True:
# os.system('cls')
# s = input('계산식 입력>')
# print(f'결과 : {eval(s)}')
# os.system('pause')
# 앞에 나오는 연산자부터 계산하기
import os
operator = ["+","-","*","/","="]
def string_calculator(user_input):
lop = 0
string_list = []
if user_input[-1] not in operator:
user_input += "="
for i,s in enumerate(user_input):
if s in operator:
if user_input[lop:i].strip() != "":
string_list.append(user_input[lop:i])
string_list.append(s)
lop= i+1
string_list = string_list[:-1]
pos = 0
while True:
if pos +1 > len(string_list):
break
if len(string_list) > pos +1 and string_list[pos] in operator:
temp = string_list[pos-1] + string_list[pos] + string_list[pos+1]
del string_list[0:3]
string_list.insert(0,str(eval(temp)))
pos = 0
pos +=1
print(string_list)
if len(string_list) > 0:
result = float(string_list[0])
return round(result, 4)
while True:
os.system('cls')
user_input = input('계산식을 입력하세여')
if user_input == "/exit":
break
result = string_calculator(user_input)
print(f'결과: {result}')
os.system('pause') |
# Exe065 - Digite varios números, pergunte [S/N] para continuar e tenha:
# Media, maior e menor.
num = soma = cont = media = 0
parada = ''
maior = 0
menor = 0
while parada != 'N':
num = int(input('Digite um número: '))
soma += num
cont += 1
media = soma / cont
if cont == 1:
maior = menor = num
else:
if num > maior:
maior = num
if num < menor:
menor = num
parada = str(input('Deseja Continuar? [ S/N ]: ').upper().strip()[0])
while parada != 'S' and parada != 'N':
print('Opção invalida')
parada = str(input('Deseja Continuar? [ S/N ]: ').upper())
print('Foram digitados {} números.\nA soma é: {}\nA média é: {}\nO maior é: {}\nO menor é: {}'
.format(cont, soma, media, maior, menor))
|
# Exe011 - Digite dois valores em metros e descubra quantos litros de tinta é nescessario.
# (1m^2 = 2L)
l = float(input('Digite a largura em (m): '))
h = float(input('Digite a altura em (m): '))
a = l * h
L = a / 2
print('Numa parede de {}m por {}m tem uma área de {}m'.format(l, h, a))
print('Numa área de {}m utilizará {}L de tinta'.format(a, L))
|
# Exe053 - Digite uma frase e descubra se é um palindromo.
frase = str(input('Digite uma frase: ').replace(' ', '').lower())
# .strip
# palavras = frase.split
# junto = ''.join(palavras)
inverso = ''
# inverso = frase[::-1]
print(inverso)
for c in range(len(frase) - 1, -1, -1):
inverso += frase[c]
print(frase, inverso)
if frase == inverso:
print('É um Palindromo')
else:
print('Não é um palindromo')
|
# Exe093 - Coloque num dicionário e mostre: nome, partidas e quantidade de gols.
Ficha = {}
gols_partida = []
tot_gols = 0
Ficha['Nome'] = str(input('Nome do jogador: '))
Ficha['Jogos'] = int(input('Quantas partidas jogadas?: '))
for g in range(Ficha['Jogos']):
gols_partida.append(int(input(f' Quantos gols no {g+1}ª jogo?: ')))
tot_gols += gols_partida[g]
Ficha['Gols'] = gols_partida
Ficha['Total'] = tot_gols
print(f'{" EXE 093 ":=^50}')
print(Ficha)
print(f'{" EXE 093 ":=^50}')
for k, v in Ficha.items():
print(f'{k}: {v}')
print(f'{" EXE 093 ":=^50}')
print(f'O jogador {Ficha["Nome"]} jogou {Ficha["Jogos"]} partidas:')
count = 0
for v in Ficha['Gols']:
count += 1
print(f' => Na partida {count}, fez \033[32m{v}\033[m gols.')
print(f'Total de gols {Ficha["Total"]}')
print(f'{" EXE 093 ":=^50}')
|
# Exe089 - Crie uma lista com os nome e notas e media dos alunos,
# depois mostre suas notas
boletins = []
aluno = []
while True:
aluno.append(str(input('Nome do aluno: ')))
aluno.append(float(input('Nota da P1: ')))
aluno.append(float(input('Nota da P2: ')))
boletins.append(aluno[:])
aluno.clear()
parada = str(input('Continuar? [S/N]: '))
if parada in 'Nn':
break
print('-='*15)
print(f'{"Nº.": <5}{"Nome do Aluno(a)":<20}{"MÉDIA":<3}')
print('-'*30)
for i, p in enumerate(boletins):
media = (boletins[i][1] + boletins[i][2]) / 2
print(f'{i:<5}{boletins[i][0]:<20}{media:<3.1f}')
print('-='*30)
while True:
opção = int(input('Deseja saber as notas de qual aluno(a)? [999 Encerra]: '))
if opção == 999:
break
print(f'A as notas do Aluno, {boletins[opção][0]}, são, '
f'{boletins[opção][1]} e {boletins[opção][2]}')
print('-'*60)
print('-='*30)
|
# Exe007 - Digite duas notas e tenha a media.
nota1 = float(input('Qual é a primeira nota? '))
nota2 = float(input('Qual é a segunda nota? '))
media = (nota1 + nota2) / 2
print('A media é: ', media)
|
# Exe074 - Gere 5 números numa tupla e tenha o maior e menor.
from random import randint
números = (randint(0, 9), randint(0, 9), randint(0, 9),
randint(0, 9), randint(0, 9))
print('Os números sorteados foram: ')
for n in números:
print(n, end=' ')
print(f'\nO maior número foi {max(números)}')
print(f'O menor número foi {min(números)}')
|
# Exe081 - Digite varios números colocando numa lista, mostre:
# Quantos números foram digitados; Em ordem decrescente e se tem 5.
números = list()
c = 0
while True:
n = int(input('Digite um número: ')) # números.append(input...)
números.append(n)
parada = input('Continuar? [S/N]: ')
c += 1
print('-='*10)
if parada in 'Nn':
break
print(c) # print(len(números))
números.sort(reverse=True)
print(números)
if números.count(5) >= 1: # if 5 in números:
print('Tem 5')
else:
print('N Tem 5')
|
# Exe017 - Digite o valor dos catetos e calcule a hipotenusa.
Co = float(input('Digite o valor do Cateto oposto: '))
Ca = float(input('Digite o valor do Cateto adjacente: '))
Hi = (Ca**2 + Co**2) ** (1/2)
print()
print('O valor de hipotenusa é {:.2f}'.format(Hi))
# import math
# Hip = math.hypot(Co, Ca)
|
# Exe061 - Refaça o exe 51 para calcular PA com while.
print('Calculadora de PA')
primeiro = int(input('Digite o primeiro termo: '))
razão = int(input('Digite a razão da PA: '))
termo = primeiro
contador = 1
print('{}'.format(primeiro), end=' > ')
while contador <= 10:
termo += razão
contador += 1
print('{}'.format(termo), end=' > ')
print('...')
|
# Exe072 - Digite um número de 0 a 20 e tenha o número por extenso.
números = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete',
'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze',
'Quinze', 'Dezeseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte')
while True:
digitado = int(input('Digite um número de 0 a 20: ').strip())
while True:
if digitado > 20 or digitado < 0:
print('ERROR: Opção Invalida!')
digitado = int(input('Digite um número de 0 a 20: ').strip())
else:
break
print(f'Foi digitado o número {números[digitado]}')
parada = str(input('Deseja Repetir? [S/N]: ').strip().upper()[0])
while True:
if parada not in 'SN':
print('ERROR: Opção Invalida!')
parada = str(input('Deseja Repetir? [S/N]: ').strip().upper()[0])
else:
break
if parada == 'N':
break
print('ENCERRANDO...') |
# 1)Create a file with the User classs... + Add a make_withdrawal method
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
def make_withdrawal(self, amount):
self.account_balance -= amount
# def display_user_balance(self):
# print(f"{self.name} has {self.account_balance} in their account.")
# def transfer_money(self, other_user, amount):
daniel = User("Daniel", "email@fake.com")
daniel.make_deposit(100)
print(daniel.account_balance)
daniel.make_withdrawal(50)
print(daniel.account_balance)
# 2)Add a display_user_balance method to the User class.
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
def make_withdrawal(self, amount):
self.account_balance -= amount
def display_user_balance(self):
print(f"{self.name} has {self.account_balance} in their account.")
# def transfer_money(self, other_user, amount):
daniel = User("Daniel", "email@fake.com")
daniel.make_deposit(100)
daniel.display_user_balance()
daniel.make_withdrawal(50)
daniel.display_user_balance()
# 3)Create 3 instances of the User class + Have the first user make 3 deposits and 1 withdrawal and then display their balance + Have the second user make 2 deposits and 2 withdrawals and then display their balance + Have the third user make 1 deposits and 3 withdrawals and then display their balance.
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
return self
def display_user_balance(self):
print(f"{self.name} has {self.account_balance} in their account.")
return self
# def transfer_money(self, other_user, amount):
daniel = User("Daniel", "email@fake.com")
pepper = User("Pepper", "dog@fake.com")
rachel = User("Rachel", "fake@email.com")
daniel.make_deposit(100).make_deposit(1000).make_deposit(200).make_withdrawal(50).display_user_balance()
pepper.make_deposit(50).make_deposit(25).make_withdrawal(10).make_withdrawal(40).display_user_balance()
rachel.make_deposit(1000).make_withdrawal(10).make_withdrawal(100).make_withdrawal(500).display_user_balance()
# Bonus) Add a transfer_money method; have the first user transfer money to the third user, and then print both user's balances
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
return self
def display_user_balance(self):
print(f"{self.name} has {self.account_balance} in their account.")
return self
def transfer_money(self, other_user, amount):
self.make_withdrawal(amount)
other_user.make_deposit(amount)
return self
daniel = User("Daniel", "email@fake.com")
pepper = User("Pepper", "dog@fake.com")
rachel = User("Rachel", "fake@email.com")
daniel.make_deposit(100).make_deposit(100).make_withdrawal(50).display_user_balance().transfer_money(rachel, 10)
print('Daniel and Rachel balance below!')
daniel.display_user_balance()
rachel.display_user_balance()
|
Notes: 10/27/2020
# Attributes!!
class User:
# Attributes
def __init__(self):
self.username = "awesome_pants"
self.email = "fake@email.com"
self.password = "123qweasd"
# Methods
john = User()
print(john.username)
print(john.email)
print(john.password)
mary = User()
class User:
# Attributes
def __init__(self, username_from_user):
self.username = username_from_user
self.email = "fake@email.com"
self.password = "123qweasd"
# Methods
john = User('mypinkponies')
print(john.username)
mary = User('littlelamgsaretasty')
print(mary.username)
# When you have specified attributes
class User:
# Attributes
def __init__(self, username_from_user, email_from_user, password_from_user):
self.username = username_from_user
self.email = email_from_user
self.password = password_from_user
# Methods
john = User('john', 'john@hotmail.com', 'alligator87')
print(john.username)
mary = User('mary', 'littlelamb@shopity.com', 'fuzzywuzzywasabear')
print(mary.username)
# Setting default parameters
# Once u start a default, you have to add defaults for all items after (to the right)
class User:
# Attributes
def __init__(self, username_from_user = "general_username", email_from_user = "place@holder.net", password_from_user = "passy_password"):
self.username = username_from_user
self.email = email_from_user
self.password = password_from_user
# Methods
john = User('john', 'john@hotmail.com', 'alligator87')
print(john.username)
print(john.email)
print(john.password)
mary = User('mary')
print(mary.username)
print(john.email)
print(john.password)
class User:
# Attributes
def __init__(self, username_from_user = "general_username", email_from_user = "place@holder.net", password_from_user = "passy_password"):
self.username = username_from_user
self.email = email_from_user
self.password = password_from_user
# Methods
john = User('john', 'john@hotmail.com', 'alligator87')
# print(john.username)
# print(john.email)
# print(john.password)
print(john.__dict__) # This will print out the information as a dictionary!
mary = User('mary')
# print(mary.username)
# print(john.email)
# print(john.password)
# Methods!!!
class User:
# Attributes
def __init__(self, username_from_user = "general_username", email_from_user = "place@holder.net", password_from_user = "passy_password"):
self.username = username_from_user
self.email = email_from_user
self.password = password_from_user
# Methods
def say_hi(self):
print("Hi, my name is", self.username)
john = User('john', 'john@hotmail.com', 'alligator87')
john.say_hi()
mary = User('mary')
mary.say_hi()
class User:
# Attributes
def __init__(self, username_from_user = "general_username", email_from_user = "place@holder.net", password_from_user = "passy_password"):
self.username = username_from_user
self.email = email_from_user
self.password = password_from_user
# Methods
def say_hi(self, person):
print(f"Hi, {person} my name is, {self.username}")
john = User('John', 'john@hotmail.com', 'alligator87')
mary = User('Mary')
john.say_hi("Mary")
mary.say_hi("John")
class User:
# Attributes
def __init__(self, username_from_user = "general_username", email_from_user = "place@holder.net", password_from_user = "passy_password"):
self.username = username_from_user
self.email = email_from_user
self.password = password_from_user
# Methods
def say_hi(self, person):
print(f"Hi, {person} my name is, {self.username}")
def wave(self, person):
print()
john = User('John', 'john@hotmail.com', 'alligator87')
mary = User('Mary')
john.say_hi("Mary")
mary.say_hi("John") |
import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
"""A class to represent a single alien in the fleet"""
def __init__(self,first_play):
"""Initialize alien and set its starting position"""
super().__init__()
self.screen = first_play.screen
self.settings = first_play.settings
# Load image and set rect attribute
self.image = pygame.image.load("game_pics/space_ship.png")
self.rect = self.image.get_rect()
# Start each image near the top left screen corner
self.rect.x = self.rect.width
self.rect.y = self.rect.height
# Store the aliens exact vertical position
self.y = float(self.rect.y)
def check_edges(self):
"""Return True if alien is at the edge of screen"""
screen_rect = self.screen.get_rect()
if self.rect.bottom >= screen_rect.bottom or self.rect.top <= screen_rect.top:
return True
def update(self):
"""Move the alien to the up or down."""
self.y += (self.settings.alien_speed * self.settings.fleet_direction)
self.rect.y = self.y
|
# input
with open('input.txt') as f:
data = [int(l.strip()) for l in f]
def calc_fuel(mass):
if mass <= 0:
return 0
return mass + calc_fuel(mass // 3 - 2)
# Part one
print(sum([mass // 3 - 2 for mass in data]))
# Part two
print(sum([calc_fuel(mass) - mass for mass in data]))
|
############ UTILS ###############""
import math
##Factorial##
def factorial(x):
if x<0 :
print("x is less than 0") ### raise ERROR
if x == 0 :
return 1
return x*factorial(x-1)
####################
######## DISCRETE FUNCTION ############
class Bernoulli:
def __init__(self, prob = 0.5):
if 0.0 <= prob and prob <= 1.0 :
self.p = prob
self.mean = self.mean()
self.variance = self.variance()
else :
print("invalid bernoulli value")
def pmf(self, x):
if x == 0:
return 0
elif x == 1:
return 1
else:
raise Exception("x value is not contained within bernoulli range of {0,1}")
def mean(self):
return self.p
def variance(self):
return self.p * (1.0 - self.p)
class Binomial:
def __init__(self,n=30,prob = 0.5):
if 0.0 <= prob and prob <= 1.0 :
self.p = prob
self.n = n
self.mean = self.mean()
self.variance = self.var()
else :
raise Exception("invalid bernoulli value")
def pmf(self, x):
if int(x)== x and x >=0 and x <= self.n :
k = self.n-x
coef = factorial(self.n)/(factorial(x) * factorial(k))
return coef * (self.p**x)*((1-self.p)**k)
else:
raise Exception("x value is not contained within binomial range of {0,n={}} or is not an integer".format(self.n))
def mean(self):
return self.n*self.p
def variance(self):
return self.n*self.p * (1.0 - self.p)
class Poisson:
def __init__(self,theta = 0.5):
if 0.0 < theta :
self.theta = theta
self.mean = self.esperance()
self.variance = self.var()
else :
raise Exception("invalid Poisson theta value")
def pmf(self, x):
if int(x)==x :
pr = math.exp(-self.theta) * ((self.theta)**x) / factorial(x)
return pr
else:
raise Exception("x = {} is not an integer ".format(x))
def esperance(self):
return self.theta
def var(self):
return self.theta
class Geometry:
def __init__(self,p = 0.5):
if 0.0 < p and p < 1 :
self.p = p
self.mean = self.esperance()
self.variance = self.var()
else :
raise Exception("invalid Geometry p value")
def pmf(self, x):
if int(x)==x and x>0:
pr = self.p * ((1-self.p) ** (x-1))
return pr
else:
raise Exception("x = {} is not an integer or x is 0 ".format(x))
def esperance(self):
return 1/self.p
def var(self):
return (1-self.p)/self.p**2
class Uniform:
def __init__(self,n):
if 0.0 < n and int(n)==n :
self.n = n
self.mean = self.esperance()
self.variance = self.var()
else :
raise Exception("invalid n value")
def pmf(self, x):
if int(x)==x and x>0 and x <=self.n:
pr = 1/self.n
return pr
else:
raise Exception("x = {} is not an integer or x is 0 ".format(x))
def esperance(self):
return (self.n+1)/2
def var(self):
return (self.n**2 - 1)/12
class HyperGeometry:
def __init__(self,N,n,p):
if 0.0 < n and int(n)==n and int(N)==N and 0.0<N and n<=N and 0.0 < p and p < 1 :
self.n = n
self.N = N
self.p = p
self.mean = self.esperance()
self.variance = self.var()
else :
raise Exception("invalid N or n or p value")
def pmf(self, x):
if int(x)==x and x<= min(self.N*self.p,self.n) and x >= max(0,self.n-self.N+self.N*self.p) :
coef1 = factorial(self.N*self.p) / (factorial(self.N*self.p-x) * factorial(x))
coef2 = factorial(self.N-self.N*self.p) / (factorial(self.N-self.N*self.p-(self.n-x)) * factorial(self.n-x))
coef3 = factorial(self.N) / (factorial(self.N-self.n) * factorial(self.n))
return coef1*coef2/coef3
else:
raise Exception("x = {} is not an integer or x is not valid ".format(x))
def esperance(self):
return self.n*self.p
def var(self):
return self.n*self.p*(self.N-self.N*self.p)*(self.N-self.n)/(self.N*(self.N-1))
#### Continiuos Probablity ########
class Normal:
def __init__(self,mu,sigma):
self.mu = mu
self.sigma = sigma
self.mean = self.esperance()
self.variance = self.var()
def pmf(self, x):
coef1 = 1/(self.sigma * math.sqrt(2*math.pi))
coef2 = (x-self.mu / self.sigma) **2
return coef1* math.exp(-(1/2) *coef2)
def cdf(self, x):
z = (x-self.mu)/(self.sigma*math.sqrt(2))
return (1/2)* (1+math.erf(z))
def esperance(self):
return self.mu
def var(self):
return self.sigma**2
class Exponential:
def __init__(self,theta):
if theta > 0 :
self.theta = theta
self.mean = self.esperance()
self.variance = self.var()
else:
print("Not a valid Theta = {}".format(theta) )
def pmf(self, x):
if x<0:
return 0
else:
return self.theta * math.exp(-self.theta*x)
def cdf(self, x):
if x<0:
return 0
else:
return 1- math.exp(-self.theta*x)
def esperance(self):
return 1/self.theta
def var(self):
return 1/(self.theta**2)
class UniformC:
def __init__(self,a,b):
if a <= b :
self.a = a
self.b = b
else:
self.a = b
self.b = a
self.mean = self.esperance()
self.variance = self.var()
def pmf(self, x):
if x<=self.b and x>= self.a:
return 1/(self.b-self.a)
else:
return 0
def cdf(self, x):
if x<=self.b and x>= self.a:
return (x-self.a)/(b-self.a)
elif x<=a:
return 0
else:
return 1
def esperance(self):
return (self.a + self.b)/2
def var(self):
return (self.b - self.a)**2 / 12
class ChiSquare:
def __init__(self,k):
if k==int(k) and k>0 :
self.k = k
else:
raise Exception("k = {} must be an integer > 0".format(k))
self.mean = self.esperance()
self.variance = self.var()
def pmf(self, x):
if x>0:
k=self.k
coef1 = 2**(k/2)* (math.gamma(k/2))
coef2 = x**((k/2) - 1) * math.exp(-x/2)
return coef2 /coef1
else:
return 0
def cdf(self, x):
if x>0:
k=self.k
coef1 = special.gammainc(k/2,x/2)
coef2 = math.gamma(k/2)
return coef1 / coef2
else:
return 0
def esperance(self):
return self.k
def var(self):
return 2*self.k
|
# Add two number
def two_num(lis1, lis2):
# reverse the order of both lists
# print()
lis1 =lis1[::-1]
lis2 = lis1[::-1]
#convert into single digit
string=(str(int) for int in lis1)
string2=(str(int) for int in lis2)
int1=int("".join(string))
int2 = int("".join(string2))
output=int1+int2
output= list(map(int, str(output)))
# reverse and return output
return print(output[::-1])
two_num([1,2,3],[1,4,2]) |
from dataclasses import dataclass
from psycopg2.extensions import register_adapter, adapt, AsIs
@dataclass(repr=True)
class Location:
"""
A simple structure for geo location information
"""
longitude: float
latitude: float
altitude: float
def adapt_location(location):
"""
Adapts a :class:Location object to be parameterized as part of a psycopg2 query. It is
converted to a PostGIS geometry(Point) object.
Please refer to `PostGIS <https://postgis.net/docs/ST_MakePoint.html>`_ for more information.
:param Location location: the location to be parameterized
:return: None
"""
lon = adapt(location.longitude).getquoted().decode('utf-8')
lat = adapt(location.latitude).getquoted().decode('utf-8')
return AsIs('ST_MakePoint(%s, %s)' % (lon, lat))
# Register the adapter when the location.py file is loaded.
register_adapter(Location, adapt_location)
|
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def remove_duplicates(head):
slow = pre = ListNode(0)
pre.next = slow.next = None
if not slow:
return head
fast = head
if not fast:
return head
v = None
while fast.next:
if v != fast.val:
if fast.val != fast.next.val:
slow.next = fast
slow = fast
v = fast.val
fast = fast.next
if fast.val != v:
slow.next = fast
slow = fast
slow.next = None
return pre.next
a1 = ListNode(1)
a2 = ListNode(2)
a3 = ListNode(2)
a1.next = a2
a2.next = a3
res = remove_duplicates(a1)
while res:
print(res.val)
res = res.next
|
def letterCombinations(digits):
letters = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
def recursive_combinations(s, n, res=[]):
if n == len(digits):
if s:
res.append(s)
else:
for l in letters[int(digits[n])]:
recursive_combinations(s + l, n + 1)
return res
return recursive_combinations('', 0)
|
class Solution(object):
def is_palindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
for i in range(int(len(str(x)) / 2)):
if int(x / pow(10, len(str(x)) - i - 1)) % 10 != int(x / pow(10, i) % 10):
return False
return True
|
# File: Kumar_Shani_DSC540_Assignment_4_2_PDF.py
# Name: Shani Kumar
# Date: 12/22/2019
# Course: DSC-540 - Data Preparation
# Desc: Setup a local database with Python and load in a dataset (can be any dataset). You can choose what back-end
# to use, if you have never done this before, the book recommends SQLite and to follow along with the book,
# you can find that at: SQLite.
# 1. Create a Python dictionary of the data.
# 2. Create a new table.
# 3. Insert the data into that table.
# Usage: This program is to complete assignment 4.2 requirements
import dataset
db = dataset.connect('sqlite:///collage.db')
student1 = {
'name': 'Shani Kumar',
'Address': 'Omaha Nebraska',
'idnumber': '12345'
}
table = db['student_info']
table.insert(student1)
student2 = {
'name': 'Rahul Suthar',
'Address': 'Omaha Nebraska',
'idnumber': '3456'
}
table.insert(student2)
sources = db['data_sources'].all()
print sources
|
# File: Assignment_8_2_Beautiful_Soup.py
# Name: Shani Kumar
# Date: 02/03/2020
# Course: DSC-540 - Data Preparation
# Desc: Beautiful Soup –
# Reading a Web Page with Beautiful Soup – following the example starting on page 300-304 of
# Data Wrangling with Python, use the Beautiful Soup Python library to scrap a web page.
# The result should be data and output in an organized format. Each of the data entries should be in its
# own dictionary with matching keys.
# Note: This code uses Python 3.7 so it have code little be different then whats there in textbook.
# Usage: This program is to complete assignment 8.2 requirements
# Also web-page layout got changed to solution is little bit different from text book.
# Import required packages
from bs4 import BeautifulSoup
import requests
page = requests.get('https://www.moneycontrol.com/mutual-funds/find-fund/returns?&amc=BIRMUTF,AXMF,BOBMUF,ABNAMF,'
'BAXMF,CANMUTF,DSPMLMF,EDELWMF,PEERMF,TEMMUFT,HDFCMUTF,HSBCMUTF,PRUICM,IDBIMF,ANZGRMUTF,IDFMF,'
'IIFLMF,ILFSMF,INDIABMF,LIMF,ITIMF,JMMTFN,KMFLAMC,CHCAMUF,LICAMCL,MAHMF,MIRAEMF,MOMF,RELCAPM,PMF'
',PPFMF,IDBIMUT,ESCOMUF,QMF,FIINMUFD,SBIMUTF,SHMF,SUNMUTF,TATMUTF,TAUMUTF,UKBCMF,UTIMUTFD,YESMF&'
'invtype=Equity%2CHybrid%2CDebt%2CSolution%20Oriented%2COthers&category=Multi%20Cap%20Fund,'
'Large%20Cap%20Fund,Large%20%26%20Mid%20Cap%20Fund,Mid%20Cap%20Fund,Small%20Cap%20Fund,ELSS,'
'Dividend%20Yield%20Fund,Sectoral%2FThematic,Contra%20Fund,Focused%20Fund,Value%20Fund,RGESS,'
'Aggressive%20Hybrid%20Fund,Conservative%20Hybrid%20Fund,Arbitrage%20Fund,Capital%20Protection'
'%20Funds,Equity%20Savings,Dynamic%20Asset%20Allocation%20or%20Balanced%20Advantage,Multi%20Asset'
'%20Allocation,Fixed%20Maturity%20Plans%20-%20Hybrid,Low%20Duration%20Fund,Short%20Duration%20'
'Fund,Medium%20Duration%20Fund,Medium%20to%20Long%20Duration%20Fund,Long%20Duration%20Fund,'
'Dynamic%20Bond%20Fund,Gilt%20Fund,Gilt%20Fund%20with%2010%20year%20constant%20duration,'
'Corporate%20Bond%20Fund,Credit%20Risk%20Fund,Floater%20Fund,Banking%20and%20PSU%20Fund'
',Fixed%20Maturity%20Plans%20-%20Debt,Interval%20Plans,Ultra%20Short%20Duration%20Fund,Liquid%2'
'0Fund,Money%20Market%20Fund,Overnight%20Fund,Childrens%20Fund,Retirement%20Fund,Investment%20cum%'
'20Insurance,Fund%20of%20Funds,Index%20Funds%2FETFs&rank=1,2&MATURITY_TYPE=OPEN%20ENDED&SHOWAUM='
'Y&ASSETSIZE=100') # setup url get request
# print(page.content)
bs = BeautifulSoup(page.content, 'html.parser') # Start parsing with BS
ta_divs = bs.find_all("div", class_="wpb_text_column wpb_content_element") # list to div required
# Initialize required fields
all_data = []
index = 1
for header in bs.find_all('h6'): # loop through all headers
data_dict = {'title': header.text, # setup title text
'link': header.a.get('href'), # setup title url
'about': ta_divs[index].find_next('p').get_text()} # setup title description
all_data.append(data_dict) # Append to dictionary
index += 1
for dict in all_data: # loop through all element
print(dict) # print data
|
# File: Assignment_9_2_Multiple_Queries.py
# Name: Shani Kumar
# Date: 02/09/2020
# Course: DSC-540 - Data Preparation
# Desc: Practice pulling data from Twitter publicly available API
# -> Create a Twitter API Key and Access Token
# -> Do a single data pull from Twitter REST API
# -> Execute multiple queries at a time from Twitter REST API
# -> Do a data pull from Twitter Streaming API
# Usage: This program is to complete assignment 9.2 requirements
# Also web-page layout got changed to solution is little bit different from text book.
# Import required packages
from rauth.service import OAuth1Service, OAuth1Session
# Get a real consumer key & secret from: https://www.goodreads.com/api/keys
CONSUMER_KEY = 'acZeISLRqqbq2Bhdwoumw'
CONSUMER_SECRET = 'PNqu1dsKLHwps0FBgdKFuASMOKOwVMoNHgOSFurDs'
goodreads = OAuth1Service(
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
name='goodreads',
request_token_url='https://www.goodreads.com/oauth/request_token',
authorize_url='https://www.goodreads.com/oauth/authorize',
access_token_url='https://www.goodreads.com/oauth/access_token',
base_url='https://www.goodreads.com/'
)
request_token, request_token_secret = goodreads.get_request_token(header_auth=True)
print('Visit this URL in your browser: ', request_token, request_token_secret)
authorize_url = goodreads.get_authorize_url(request_token)
print('Visit this URL in your browser: ' + authorize_url)
accepted = 'n'
while accepted.lower() == 'n':
# you need to access the authorize_link via a browser,
# and proceed to manually authorize the consumer
accepted = input('Have you authorized me? (y/n) ')
session = goodreads.get_auth_session(request_token, request_token_secret)
data = {'Python'}
response = session.get('Python')
print('Visit this URL in your browser: ', response.content)
|
"""
l=[]
for i in range(2000, 3201):
if (i%7==0) and (i%5!=0):
l.append(str(i))
print ','.join(l)
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
x = int(raw_input())
print fact(x)
import math
dict_number = {}
input_number = int(raw_input("Input your #:"))
for i in range(1, input_number+1):
dict_number[i] = i*i
print(dict_number)
class input_String():
def __init__(self):
self.value = ""
def getString(self):
self.value = raw_input("Nhap 1 tu:")
return self.value
def printString(self):
print(self.value.upper())
a = input_String()
b = a.getString()
a.printString()
import math
list_number = []
input_number = raw_input("Nhap 1 day so, cach bang ',' :")
list_number = input_number.split(',')
result = []
for i in list_number:
i = int(i)
result.append(math.sqrt((2*50*i)/30))
print(result)
row_index = 7
col_index = 4
list_number = [[0 for col in range(col_index)] for row in range(row_index)]
print(list_number)
for index_i in range(0,row_index):
print '\n'
for index_j in range(0,col_index):
list_number[index_i][index_j] = index_i*index_j
print index_i,'*',index_j,' = ',list_number[index_i][index_j]
raw_input()
input_string = "New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3"
normalize_word = input_string.split(' ')
list_word = []
dict_word = {}
for word in normalize_word:
if word not in list_word:
list_word.append(word)
dict_word[word] = 1
else: dict_word[word] += 1
print dict_word
"""
x = '5' + 'D'
print x
|
def minHeightBst(array):
return constructMinHeightBst(array, 0, len(array) - 1)
def constructMinHeightBst(array, startId, endId):
if endId < startId:
return None
midId = (startId + endId) // 2
bst = BST(array[midId])
bst.left = constructMinHeightBst(array, startId, midId)
bst.right = constructMinHeightBst(array, midId + 1, endId)
return bst
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left is None:
self.left = BST(value)
else:
self.left.insert(value)
else:
if self.right is None:
self.right = BST(value)
else:
self.right.insert(value)
return self |
def isMonotonic(array):
if len(array) <= 2:
return True
isNonDecreasing = True
isNonIncreasing = True
for i in range(len(array)-1):
if array[i] > array[i + 1]:
isNonDecreasing = False
if array[i] < array[i + 1]:
isNonIncreasing = False
return isNonDecreasing or isNonIncreasing
array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]
print isMonotonic(array) |
import pygame
from pygame.locals import *
import sys
import wave_class
import os.path
"""
Main file for wave generation code
"""
OUTPUT_FILENAME = "new-sound"
LENGTH_OF_FILE_IN_SECONDS = 5
CHANNEL_COUNT = 1
SAMPLE_WIDTH = 2
SAMPLE_RATE = 44100 # How many time we sample per second
SAMPLE_LENGTH = SAMPLE_RATE * LENGTH_OF_FILE_IN_SECONDS
COMPRESSION_TYPE = 'NONE'
COMPRESSION_NAME = 'not compressed'
MAX_VOLUME = 32767 # How high/low the crest/trough will be. How loud the sound will be AMPLITUDE
FREQUENCY = 261 # Hz How tightly packed each wave is.
wave_types = {0: "sine", 1: "square", 2: "saw"}
def new_sound_gen(sound_class, wave_type):
"""
Function for generating a new sound from the class.
:param sound_class: Class for generating waves
:param wave_type: Type of wave to be generated
:return: Latest file generated
"""
output_file_name = str(sound_class.output_filename + str(sound_class.id) + ".wav")
# New file name generated so many files can be created
created_sound = sound_class.open_file(output_file_name)
created_sound.setparams((CHANNEL_COUNT, SAMPLE_WIDTH, SAMPLE_RATE,
SAMPLE_LENGTH, COMPRESSION_TYPE, COMPRESSION_NAME))
values = []
for i in range(0, int(sound_class.sample_length)):
if wave_type == "sine":
created_wave = sound_class.sine_wave(sound_class.frequency, i, sound_class.sample_rate, sound_class.volume)
elif wave_type == "square":
created_wave = sound_class.square_wave(sound_class.frequency, i, sound_class.sample_rate)
elif wave_type == "saw":
created_wave = sound_class.saw_wave(sound_class.frequency, i, sound_class.sample_rate, sound_class.volume, 6
)
# Allows program to generate different types of waves
for j in range(0, sound_class.channels):
values.append(created_wave)
created_sound.writeframes(b''.join(values))
sound_class.close_file(created_sound)
return output_file_name
def main():
"""
Main function for the program to run.
:return: Nothing
"""
pygame.init()
pygame.display.set_mode((250, 250), 0, 32)
current_file_to_play = ""
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_p:
if os.path.isfile(current_file_to_play):
current_sound = pygame.mixer.Sound(current_file_to_play)
current_sound.play()
if event.key == K_w:
current_file_to_play = new_sound_gen(
wave_class.WaveClass("new-sound", LENGTH_OF_FILE_IN_SECONDS, CHANNEL_COUNT, SAMPLE_WIDTH,
SAMPLE_RATE, MAX_VOLUME, FREQUENCY), wave_types[0])
print(current_file_to_play)
if event.key == K_a:
current_file_to_play = new_sound_gen(
wave_class.WaveClass("new-sound", LENGTH_OF_FILE_IN_SECONDS, CHANNEL_COUNT, SAMPLE_WIDTH,
SAMPLE_RATE, MAX_VOLUME, FREQUENCY), wave_types[1])
if event.key == K_d:
current_file_to_play = new_sound_gen(
wave_class.WaveClass("new-sound", LENGTH_OF_FILE_IN_SECONDS, CHANNEL_COUNT, SAMPLE_WIDTH,
SAMPLE_RATE, MAX_VOLUME, FREQUENCY), wave_types[2])
if __name__ == "__main__":
main()
|
class DoublyLinkedList(object):
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRU_Cache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.head = DoublyLinkedList(-1, -1)
self.tail = self.head
self.hash = {}
self.capacity = capacity
self.length = 0
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self.hash:
return print(-1)
node = self.hash[key]
val = node.val
while node.next:
node.prev.next = node.next
node.next.prev = node.prev
self.tail.next = node
node.prev = self.tail
node.next = None
self.tail = node
return print(val)
def set(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if key in self.hash:
node = self.hash[key]
node.val = value
while node.next:
node.prev.next = node.next
node.next.prev = node.prev
self.tail.next = node
node.prev = self.tail
node.next = None
self.tail = node
else:
node = DoublyLinkedList(key, value)
self.hash[key] = node
self.tail.next = node
node.prev = self.tail
self.tail = node
self.length += 1
if self.length > self.capacity:
remove = self.head.next
self.head.next = self.head.next.next
self.head.next.prev = self.head
del self.hash[remove.key]
self.length -= 1
our_cache = LRU_Cache(5)
our_cache.set(1, 1)
our_cache.set(2, 2)
our_cache.set(3, 3)
our_cache.set(4, 4)
our_cache.get(1) # returns 1
our_cache.get(2) # returns 2
our_cache.get(9) # returns -1 because 9 is not present in the cache
our_cache.set(5, 5)
our_cache.set(6, 6)
# returns -1 because the cache reached it's capacity and 3 was the least recently used entry
our_cache.get(3)
|
#!/usr/bin/python3
# Resources used: https://pythonprogramming.net/python-port-scanner-sockets/
# https://www.pythonforbeginners.com/code-snippets-source-code/port-scanner-in-python
import socket
import sys
ip = sys.argv[1]
fp = int(sys.argv[2])
lp = int(sys.argv[3])
def scan(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
try:
sock.connect((ip,port))
return True
except:
return False
for x in range(int(fp),(int(lp)+1)):
if scan(x):
print("Port ", x, " on ", ip, " is open.")
else:
print("Port ", x, " on ", ip, " is closed.") |
class Mine:
def __init__(self, element, index, x, y, quantity):
self.x = x
self.y = y
self.index = index
self.element = element
self.quantity = quantity
self.nearest_factories = []
def mine(self):
if self.quantity < 1:
print("You'r taking away too much at this mine -> ", str(self))
self.quantity = 0
else:
self.quantity -= 1
# if self.quantity == 0:
# print("NOTE:Mine empty -> ", str(self))
def __str__(self):
out = "{} mine [index = {}] at ({},{}) with quant: {}".format(
self.element, self.index, self.x, self.y, self.quantity
)
return out
class Factory:
def __init__(self, element, index, x, y):
self.x = x
self.y = y
self.index = index
self.element = element
self.nearest_mines = []
self.quantity = 0
def deposit(self):
self.quantity += 1
def __str__(self):
out = "{} factory [index = {}] at {},{}".format(
self.element, self.index, self.x, self.y
)
return out
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 3 12:41:21 2020
@author: JC
"""
import networkx as nx #该库用于网络图的创建与绘制
import matplotlib.pyplot as plt
G = nx.DiGraph()#创建有向图
G.add_node(1)
G.add_node(2)
G.add_nodes_from([3, 4, 5, 6])
G.add_cycle([1, 2, 3, 4])
G.add_edge(1, 3)
G.add_edges_from([(3, 5), (3, 6), (6, 7)])
print("输出全部节点:{}".format(G.nodes()))
print("输出全部边:{}".format(G.edges()))
print("输出全部边的数量:{}".format(G.number_of_edges()))
nx.draw(G)
plt.show() |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 00:02:03 2020
@author: JC
"""
import calendar
# 输入指定年月
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))
# 显示日历
print(calendar.month(yy,mm)) |
"""
train_agent.py: This is the source code to train the agent.
@author: Rohith Banka.
Initial code has been provided by the team by Udacity Deep Reinforcement Learning Team, 2021.
Unity ML agents have Academy and brains.
Academy: This element in Unity ML, orchestrates agents and their decision-making process.
Brain: We train the agent by optimizing the policy called "Brain". We control this brain using Python API.
For further information, Please refer to the following Medium article:
https://towardsdatascience.com/an-introduction-to-unity-ml-agents-6238452fcf4c
"""
# Import the required modules.
import torch
import time
import random
import numpy as np
from collections import deque
from dqn_agent import *
from model import *
from unityagents import UnityEnvironment
import sys
import argparse
# training hyperparameters
num_episodes=2000
epsilon=1.0
epsilon_min=0.05
epsilon_decay=0.99
scores = []
scores_average_window=100
required_score = 14
def get_environment_info(location):
'''To get the information about the environment from the given location of Unity ML agent'''
env = UnityEnvironment(location)
# We check for the first brain available, and set it as the default brain, we will be controlling using Python API.
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# action size is the total number of distinct actions.
action_size = brain.vector_action_space_size
# state size is the total number of dimensions of the each state in the environment. In our case, it's 37.
state_size = brain.vector_observation_space_size
return (env, brain_name, brain, action_size, state_size)
def get_agent(state_size, action_size, dqn_type):
'''Initializes and returns the agent'''
agent = Agent(state_size=state_size, action_size=action_size, dqn_type=dqn_type)
print(f"Agent has been initialized with dqn_type as {dqn_type}...")
return agent
def train_agent(env, brain_name, brain, action_size, state_size, agent, epsilon, dqn_type,num_episodes):
'''Trains the agent
Input parameters:
brain_name: the name of the first brain available.
brain: The policy that we train.
action_size: Total number of actions that an agent can take.
state_size: 37 dimension (in this navigation case)
epsilon: This is used for epsilon-greedy action selection.
num_episodes: Total number of episodes to train the agent.
'''
print(brain_name)
'''
1. Reset the training environment at the beginning of each episode.
2. Get the current state i.e., s
3. Use Epsilon-greedy policy to perform and action(a), in the environment in the given state (s)
4. Get the reward and next_state of the environment for action (a)
5. Calcuate the error between actual and expeted Q values for s(t), a(t), r(t), s(t+1), in turn this is used to train Neural Networks
6. Update the total reward received and set s(t) <- s(t+1)
7. Steps 1 to 3 will be repeated until the episode is done.
However, in the case below the training process stops even if the total score of agent > 14.
'''
for i_episode in range(1, num_episodes+1):
# print(f"training episode: {i_episode}")
env_info = env.reset(train_mode=True)[brain_name]
# initial state
state = env_info.vector_observations[0]
# Initial score for each episode is 0.
score = 0
while True:
# get the action.
action = agent.act(state, epsilon)
# take the action in the environment
env_info = env.step(action)[brain_name]
# now get the next state of the environment, post taking the action.
next_state = env_info.vector_observations[0]
# reward from the environment after action (a)
reward = env_info.rewards[0]
done = env_info.local_done[0]
agent.step(state, action, reward, next_state, done)
state = next_state
score += reward
if done:
break
# After every episode, append score to the scores list, calculate the mean.
scores.append(score)
# mean score is calcuated over present episode until i_episode > 100.
# (so past 100 scores will be taken for average if they available, else all the existing score will be used for mean)
average_score = np.mean(scores[i_episode - min(i_episode, scores_average_window): i_episode+1])
# epsilon value is being reduced as the agent is learning and action space can exploited.
epsilon = max(epsilon_min, epsilon_decay*epsilon)
print(f"Episode: {i_episode} , Average Score: {round(average_score, 4)}")
# Print average score every scores_average_window episodes
if i_episode % scores_average_window == 0:
print(f"Average score after {i_episode} episode is {round(average_score, 4)}")
print('------------------------------------------------------------')
# Check to see if the task is solved (i.e,. avearge_score > required_score).
# If yes, save the network weights and scores and end training.
if average_score >= required_score:
print('\n{} Agent has learnt to solve the environment in {:d} episodes!\tAverage Score: {:.2f}'.format(dqn_type,i_episode, average_score))
# To save the weights of the Neural network
start_time = time.strftime("%Y%m%d-%H%M%S")
dqn_model_weights = "saved_models/"+dqn_type+"model_weights_"+start_time + ".pth"
torch.save(agent.network.state_dict(), dqn_model_weights)
print(f"Saved the {dqn_type} model weights at {dqn_model_weights}")
# To save the recorded Scores data.
scores_filename = "scores/"+dqn_type+"_agent_scores_"+start_time + ".csv"
np.savetxt(scores_filename, scores, delimiter=",")
print(f"Scores of the training process for {dqn_type} model has been stored at {scores_filename}")
break
# close the environment after all the episodes.
env.close()
print("Closed the environment")
def main():
'''Main function that takes the location/path of the environment'''
parser = argparse.ArgumentParser(description="Train DQN Agent sample cmd: python train_agent.py <path to Banana.exe> DQN")
parser.add_argument('location', type=str, help='Input dir for Banana.exe location')
parser.add_argument('dqn_type', type=str, help='type of DQN agent to train: DQN or DDQN')
# get the namespace
namespace = parser.parse_args()
# get the args
location = namespace.location
dqn_type = namespace.dqn_type
# gets the environment information.
env, brain_name, brain, action_size, state_size = get_environment_info(location)
print(f"The type of Deep Q Network chosen in {dqn_type}")
# Initializes the agent with state_size, and action_size of the environment.
agent = get_agent(state_size, action_size, dqn_type)
# Train the agent.
train_agent(env, brain_name, brain, action_size, state_size, agent, epsilon, dqn_type, num_episodes)
if __name__ == "__main__":
main()
|
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict1=defaultdict(list)
def helper(str1):
hasharr=[0]*26
for i in str1:
index=ord(i)-97
hasharr[index]+=1
return "".join(map(str,hasharr))
for i in strs:
dict1[helper(i)].append(i)
return dict1.values()
time Complexity is O(sn) where s is the length of string.
Space complexity is O(n)
|
#Le juste prix
# import random
# n = random.randint(0,100)
# commentaire = "?"
# while True:
# var = input("Entrez un nombre")
# var = int(var)
# if var < n :
# commentaire = "trop bas"
# print(var, commentaire)
# else :
# commentaire = "trop haut"
# print(var, commentaire)
# if var == n:
# commentaire = "bravo !"
# print(var, commentaire)
# break
# Le juste prix
from random import randint
nbr_essais_max = 6
essais = 1
borneSup = 100
mon_prix = randint(1,borneSup)
ton_prix = 0
print("J'ai choisi un prix entre 1 et",borneSup)
print("Vous avez",essais_max,"tentatives !")
while ton_prix != mon_prix and nbr_essais <= essais_max:
print("Essai numero : ",essais)
ton_prix = int(input("Votre proposition : "))
if ton_prix < mon_prix:
print("Trop petit")
elif ton_prix > mon_prix:
print("Trop grand")
else:
print("Bravo ! Vous avez trouvé",mon_prix,"en",nbr_essais,"essai(s)")
nbr_essais += 1
if essais>essais_max and ton_prix != mon_prix :
print("Désolé, vous avez utilisé vos",essais_max,"essais.")
print("J'avais choisi le prix",mon_prix,".") |
my_int = int(input('Give me an int >= 0: '))
# Fill in the missing code
bstr= ""
if my_int < 0:
print("Number should be 0 or higher. Try again")
my_int = int(input('Give me an int >= 0: '))
else:
numb = my_int
while numb > 0:
#bstr = '{0:b}'.format(my_int)
n = numb % 2
bstr += str(n)
numb //= 2
if bstr == "":
bstr = "0"
print("The binary of", my_int, "is", bstr[::-1])
|
n = int(input("Input an int: ")) # Do not change this line
# Fill in the missing code below
factor_int = 1
while factor_int <= n:
if n % factor_int == 0:
print(factor_int)
factor_int += 1 |
num = int(input("Input an int: ")) # Do not change this line
oddatala = 1
for i in (range(num*2)):
if i % 2 == 1:
print(i)
# Fill in the missing code below |
#number = 0x9b
#isOdd = number & 0x01
#if isOdd:
# print(str(number) + " is odd number")
#else:
# print(str(number) + " is even number")
number = 0x7d9a
print(number)
# 0x7d9a == 0111 1101 1001 1010
# qqq q
# aa
#qqqq = 1100
#aa = 11
# 0111 1101 1001 1010
# 0000-0001-1000-0000
# 0000 0000 0000 1100
#0x0180
# 0111 1101 1001 1010
# 0000 1100 0000 0000
#0x0C00
#0x7d9a =
0x0C00 >> 10 |
n = int(input("Enter the length of the sequence: ")) # Do not change this line
teljari = 0
num1 = 1
num2 = 2
num3 = 3
num2temp = 0
num3temp = 0
while n > teljari:
print(num1)
num3temp = num3
num2temp = num2
num3 = num1 + num2 + num3
num2 = num3temp
num1 = num2temp
teljari += 1
|
import pandas as pd
df_upper = pd.read_excel('data/alphabet.xlsx', sheet_name='large', header=None)
df_lower = pd.read_excel('data/alphabet.xlsx', sheet_name='small', header=None)
def convert_alphabet(txt):
num = 15
convert = [''] * num
for i in txt:
if i.isalpha():
if i.isupper():
row = ord(i) - ord('A')
for j in range(num):
# pass
convert[j]+=df_upper[j].values[row]
if j == num - 1:
convert[j] += ' '
if i.islower():
row = ord(i) - ord('a')
for j in range(num):
convert[j]+=df_lower[j].values[row]
if j == num-1:
convert[j]+=' '
# convert[i].append(df_upper.iloc[j, ''])
else:
for j in range(num):
convert[j] += i
re_str = '\n'.join(i for i in convert)
return re_str |
'''题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。
问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。
问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?'''
def age(n):
if n==1:
c = 10
else:
c = age(n-1)+2
return c
print(age(5)) |
import numpy as np
class KNN:
def train_knn(self, k, data, data_class, inputs):
"""
K Nearest Neighbor from the book
:param k: how many neighbors to check
:param data: the data to process
:param data_class: the standardized instance of the class
:param inputs: what to check
:return: the closest neighbor
"""
num_inputs = np.shape(inputs)[0]
closest_neighbor = np.zeros(num_inputs)
for n in range(num_inputs):
# Compute distances
distances = np.sum((data - inputs[n, :]) ** 2, axis=1)
# Identify the nearest neighbors
indices = np.argsort(distances, axis=0)
classes = np.unique(data_class[indices[:k]])
if len(classes) == 1:
closest_neighbor[n] = np.unique(classes)
else:
counts = np.zeros(max(classes) + 1)
for i in range(k):
counts[data_class[indices[i]]] += 1
closest_neighbor[n] = np.max(counts)
return closest_neighbor
|
print("Challenge 3.1: Debug code snippets")
print()
print("Code Snippet 1:")
u = 5
v = 2
# '=' is the assignment operator; '==' is the comparison operator
if u * v == 10:
print(f"The product of u ({u}) and v ({v}) is 10")
else:
print(f"The product of u ({u}) and v ({v}) is not 10")
print()
print("Code Snippet 2:")
x = 15
y = 25
z = 30
if z < x:
print(f"z ({z}) is less than x ({x})")
# Missing the semicolon after the elif condition
elif z > x and z < y:
print(f"z ({z}) is between x ({x}) and y ({y})")
# Missing the semicolon after else
else:
print(f"z ({z}) is greater than y ({y})")
print()
print("Code Snippet 3:")
a = 1
b = 1
c = (a >= b)
# 1 is not greater than 1 hence modifying the comparison operator and print statement
print(f"The value of c ({c}) is True since a ({a}) is greater than or equal to b ({b}).")
assert(c == True) #Do not change this line
print()
print("Code Snippet 4:")
d = (5 < 7) and not (8 < 20)
# Change second 'or' to 'and' to make d evaluate to false
print("The value of d is False when we add an and operator between a False and True expression")
assert(d == False) #Do not change this line
print()
print("Code Snippet 5:")
m = "GOAT"
n = "goat"
o = (m != n)
# Python is case-sensitive so m and n are not equal
print (f"The value of o ({o}) is True since Python is case-sensitive.")
assert(o == True) #Do not change this line
print()
print("CHALLENGE COMPLETE!") |
'''
Planning & pseudocode challenge!
For each piece here, write out the pseudocode as comments FIRST, then write your code!
At many points, you'll have to choose between using a list vs. dictionary. Justify your choices!
'''
'''
1. Shipping
You are building a system to handle shipping orders. Each order should have 3 pieces of information:
-destination (string) (for the purposes of this challenge this can be any place, no need to make a full address)
-date_shipped (string)
-weight (float) (how many pounds the package is)
Will you choose to make each shipping order as a dictionary or list? Why?
Assign 3 separate orders to 3 separate variables
'''
print('\nPART 1')
# using a dictionary to include all 3 variables
order_1 = {'destination': 'Philly', 'date shipped': '2/15/21', 'weight': 20}
order_2 = {'destination': 'NYC', 'date shipped': '2/28/21', 'weight': 15}
order_3 = {'destination': 'Boston', 'date shipped': '3/1/21', 'weight': 10}
print(order_1)
print()
print(order_2)
print()
print(order_3)
print()
'''
2. Building the database
Now, let's put the orders all into a database togther (all the orders are stored in 1 variable).
Your database as a whole can either be a dictionary or a list (hint, you'll want nesting!).
Print out the database to make sure all the info is in there.
'''
print('\nPART 2')
# this puts all of the orders into one list
order_database = [order_1, order_2, order_3]
print(order_database)
print()
'''
3. Define a function called add_order() that adds one more order to your database, and make sure it works!
Any new orders should be in the same format as your existing ones.
'''
print('\nPART 3')
# creating the two additional orders
order_4 = {'destination': 'Baltimore', 'date shipped': '3/15/21', 'weight': 25}
order_5 = {'destination': 'Chicago', 'date shipped': '1/15/21', 'weight': 20}
# defined the function that has two variables - order & database
def add_order_list(database, order):
database.append(order) #appending the order to the database
# using the new function with the two variables - the database variable defined earlier & the 2x new orders I just made
add_order_list(order_database, order_4)
add_order_list(order_database, order_5)
print(order_database)
'''
4. Define a function called complete_order() to mark a specific order in your database complete
This means you'll need a new piece of data inside the order that is True when the order is complete.
Test this out and print out your database to make sure it works!
HINT: Think about how your choice of list/dictionary in part 2 informs how someone would reference an order in the database
'''
print('\nPART 4')
def complete_order(database, order_num):
database[order_num]['complete'] = True
# test it out
complete_order(order_database, 1)
complete_order(order_database, 3)
# print out to check it
print(order_database) |
print("hello world")
#convert 100 degrees farenheit to celsius
celsius_100= (100-32)*(5/9)
print (celsius_100)
#convert 0 degrees farenheit to celsius
celsius_0= (0-32)*(5/9)
print(celsius_0)
#convert 34.2 farenheit to celsius
print((34.2-32)*(5/9))
#convert 5 degrees celsius to farenheit
print((5*9/5)+32)
print(30.2 is hotter than 85.1 degrees farenheit)
|
#first I am going to create two variables
#then set them equal to the information from the user
print("~~~~~~~~~~Tip Calculator~~~~~~~~~~")
price = int(input('Please, enter total price:\n'))
percent = input('Please, enter tip percent amount :\n')
numOfPpl=int(input('Please, enther the total number of people in your party:\n'))
#Added this for loop to check if the user types in a percentage sign. if so then we remove the % sign
for i in range(len(percent)):
if '%' in percent[i]:
percent = percent[:i]
#calculate how much 10% is out of the price of bill
percentFromPrice = price * (int(percent)/100)
#add the ten percent to orginal bill
totalPrice = price + percentFromPrice
#divied the total price per person
totalPircePerPerson = round(totalPrice,2)/numOfPpl
#get the total tip person calculation
totalTipPerPerson = percentFromPrice/numOfPpl
#list out all the calculations for the user to see
print("~~~~~~~~~~Bill~~~~~~~~~~~~~~~~")
print(f'${price}')
print(f"~~~~~~Tip per person~~~~~~~~~~~~")
print(f'${round(totalTipPerPerson,2)}')
print(f"~~~~~~~Total per person~~~~~~~~~~")
print(f'${round(totalPircePerPerson,2)}')
|
# MSPA 400 Session 7 Python Module #2.
# Reading assignment:
# "Think Python" 2nd Edition Chapter 8 (8.3-8.11)
# "Think Python" 3td Editon (pages 85-93)
# Module #2 objective: demonstrate some of the unique capabilities of numpy
# and scipy. (Using the poly1d software from numpy, it is possible to
# differentiate, # integrate, and find the roots of polynomials. Plotting the
# results illustrates the connection between the different functions.)
import matplotlib.pyplot
from matplotlib.pyplot import *
import numpy
from numpy import poly1d, linspace
# The first example shows how to generate and print a second degree
# polynomial with coefficients, 1, -3 and 2. The software is not limited
# to second degree polynomials. Higher order can be generated. The critical
# thing is to have all the coefficients in the right sequence.
p=poly1d([(25/8.0),-250,5000])
h= p.deriv(m=1) # First derivative with m=1.
#t= p.deriv(m=2) # Second derivative with m=2.
print('\nEquation')
print p
print('\nEquation Roots of polynomial')
print p.roots
print('\nEquation y value of roots')
print p(p.roots)
print('\n\nDerivative')
print h
print('\nDerivative Roots of polynomial')
print h.roots
print('\nDerivative y value of roots')
print p(h.roots)
#second derivation
#print p.deriv(m=2)
#print p.deriv(m=2)(0)
#print p.deriv(m=2)(8)
#second derivative
print('\nSecond Derivative Roots of polynomial')
print p.deriv(m=2).roots
print('\nSecond Derivative y value of roots')
print p(p.deriv(m=2).roots)
x=linspace(-8,6.1,101)
y=p(x)
yd=h(x)
ydd= p.deriv(m=2)(x)
print max(p(x))
plot (x,y,label ='y=p(x)')
plot (x,yd,label ='First Derivative')
plot (x,ydd,label ='Second Derivative')
legend(loc='best')
xlabel('x-axis')
ylabel('y-axis')
title ('Plot Showing Function and First Derivative')
show()
## Exercise: Refer to Lial Section 14.1 Example 2. Duplicate the results
## showing plots of the function and derivatives. Compare to the answer sheet.
#figure()
#p=poly1d([3,-4,-12,0,2])
#print ('\nFourth Degree Polynomial')
#print p
#print ('\nFirst Derivative')
#g= p.deriv(m=1) # First derivative with m=1.
#print g
#print ('\nSecond Derivative')
#q= p.deriv(m=2) # Second derivative with m=2.
#print q
#x=linspace(-2,3,101)
#y=p(x)
#yg=g(x) # These statements define points for plotting.
#yq=q(x)
#y0=0*x # This statement defines the y axis for plotting.
#plot (x,y,label ='y=p(x)')
#plot (x,yg,label ='First Derivative')
#plot (x,yq,label ='Second Derivative')
#legend(loc='best')
#plot (x,y0)
#xlabel('x-axis')
#ylabel('y-axis')
#title ('Plot Showing Function, First and Second Derivatives')
#show() |
# MSPA 400 Session #2 Python Module #3
# Reading assignment "Think Python" either 2nd or 3rd edition:
# 2nd Edition Chapter 3 (3.4-3.9) and Chapter 10 (10.1-10.12)
# 3rd Edition Chapter 3 (pages 24-29) and Chapter 10 (pages 105-115)
# Module #3 objective: demonstrate numpy matrix calculations. For
# matrix calculations, arrays must be converted into numpy matrices.
import numpy
from numpy import *
from numpy.linalg import *
# With numpy matrices, you can add, subtract, multiply, find the transpose
# find the inverse, solve systems of linear equations and much more.
# Solve a system of consistent linear equations. Refer to Lial Section 2.5
# Example 7 Cryptography for the calculation
# Right hand side of system of equations has data entered as a list
# and converted to 3x1 matrix and then a 1x3 matrix using the transpose
# function. Similar steps are taken for the matrix A.
rhs= [10, 6, 5, 7]
rhs=matrix(rhs)
rhs=transpose(rhs)
print ('\nRight Hand Side of Equation')
print rhs
A =[[2,90,2,0], [1,80,2,3],[1,20,3,7],[2,30,0,7]]
A= matrix(A)
print ('\nMatrix A')
print A
# Numpy has various functions to perform matrix calculations. The inverse
# function inv() is one of those.
# Find inverse of A.
print ('\nInverse of A')
IA= inv(A)
print IA
# In what follows, I am converting matrices with floating point numbers to
# matrices with integer numbers. This is optional and being done to show
# that it is possible to do so with numpy matrices.
# Note that the function dot() performs matrix multiplication.
# Verify inverse by multiplying matrix A and its inverse IA.
print ('\nIdentity Matrix')
I= dot(IA,A)
I= (I) # This converts floating point to integer.
print I
# Solve the system of equations and convert to integer values.
# With numpy it is necessary to use dot() for the product.
result = dot(IA,rhs)
#result = int_(result) # This converts floating point to integer.
#result = rint(result).astype(int)
print ('\nSolution to Problem')
print result
# There is a more efficient way to do this with the linalg.solve() function.
print ('\nIllustration of solution with linalg.solve(,) function')
result2= linalg.solve(float_(A),float_(rhs))
print result2 # This converts floating point to integer.
eq1=result[0,0]*2+result[1,0]*90+2*result[2,0]
eq2=result[0,0]+result[1,0]*80+2*result[2,0]+3*result[3,0]
eq3=result[0,0]+result[1,0]*20+3*result[2,0]+7*result[3,0]
eq4=result[0,0]*2+result[1,0]*30+7*result[3,0]
print '\n'
print ('\n equation 1 output: %d') %eq1
print ('\n equation 2 output: %d') %eq2
print ('\n equation 3 output: %d') %eq3
print ('\n equation 4 output: %d') %eq4 |
"""
Main module of the game
"""
__author__ = 'Bojan Keca'
import sys
import timeit
from random import randint
from snake import Snake
from constants import *
sys.path.append(r'c:\pydev')
import pygame as pg
def secure_screen_size():
"""
Ensures that screen size to snake width ratio is correct,
increments the screen size until ratio is good
"""
global FRAME_SIZE
while FRAME_SIZE % FRAME_WIDTH_TO_SNAKE_WIDTH != 0:
FRAME_SIZE += 1
class SnakeGame(object):
"""
Represents game object, handles snake's movement and drawing,
mice creating, score count, draws everything.
"""
def __init__(self):
secure_screen_size()
pg.init() # initialize pygame module
pg.display.set_caption('PySnake Game')
# height of upper bound line of the drawing frame
self._snake_width = FRAME_SIZE/FRAME_WIDTH_TO_SNAKE_WIDTH
# make main screen surface a little bit higher (for score text)
self._screen = pg.display.set_mode((FRAME_SIZE, FRAME_SIZE + self._snake_width * 2))
# make a subsurface from screen surface. It will be rectangle where snake will move
self._frame = self._screen.subsurface([0, self._snake_width*2, FRAME_SIZE, FRAME_SIZE])
# set of all grid fields: range for x and y go from 0 to SCREEN_WIDTH_TO_SNAKE_WIDTH - 1
# it will be used to pick a place for draw mouse for snake to chase
self._grid_field_list = [(x, y) for x in xrange(FRAME_WIDTH_TO_SNAKE_WIDTH) for y in xrange(FRAME_WIDTH_TO_SNAKE_WIDTH)]
self._grid_field_size = self._screen.get_width() / FRAME_WIDTH_TO_SNAKE_WIDTH # in pixels
# initialize font
self._font = pg.font.SysFont("monospace", self._snake_width*2 - 3)
# create snake
self._snake = Snake(self._frame, self._snake_width)
# Clock object is used to slow down and main loop, it ensures the FPS
self._clock = pg.time.Clock()
# default speed of the game
self._speed = 10
# default speed increment when snake catches mouse
self._speed_inc = 3
# increment score when snake catches the mouse
self._score = 0
def run(self):
# draw the white background onto the surface
self._frame.fill(BLACK)
# draw frame for the game
self._draw_frame_line()
self._draw_score()
self._snake.draw(draw_everything=True)
mouse_pos = self._draw_mouse()
pg.display.update()
running = True
direction = DIR_RIGHT # initial movement direction
while self._snake.move(direction) and running:
self._snake.draw()
self._draw_frame_line()
# check if snake's head is on the mouse field
if self._snake.head() == mouse_pos:
self._delete_score()
self._score += 1
self._snake.grow()
self._delete_mouse(mouse_pos) # snake eats mouse -> remove it from field
mouse_pos = self._draw_mouse() # re-draw mouse again
self._speed += self._speed_inc # increase play speed
self._draw_score()
pg.display.flip()
self._clock.tick(self._speed) # ensure frame rate of the game: higher the FPS -> snake will be faster
for event in pg.event.get():
if event.type is pg.QUIT:
running = False
elif event.type is pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
running = False
elif event.key == pg.K_LEFT:
direction = DIR_LEFT
elif event.key == pg.K_RIGHT:
direction = DIR_RIGHT
elif event.key == pg.K_UP:
direction = DIR_UP
elif event.key == pg.K_DOWN:
direction = DIR_DOWN
def _draw_mouse(self):
"""
Picks random location and draws mouse
:return: mouse location -> tuple (x,y)
"""
pos = self._snake.grid_occupied[0]
while pos in self._snake.grid_occupied:
pos = (randint(0, FRAME_WIDTH_TO_SNAKE_WIDTH-1), randint(0, FRAME_WIDTH_TO_SNAKE_WIDTH-1))
# draw a pink circle onto the surface
center = (pos[0] * self._grid_field_size + self._grid_field_size / 2,
pos[1] * self._grid_field_size + self._grid_field_size / 2)
pg.draw.circle(self._frame, PINK, center, self._grid_field_size / 2, 0)
return pos
def _delete_mouse(self, pos):
"""
Removes mouse from given position
"""
center = (pos[0] * self._grid_field_size + self._grid_field_size / 2,
pos[1] * self._grid_field_size + self._grid_field_size / 2)
pg.draw.circle(self._frame, BLACK, center, self._grid_field_size / 2, 0)
def _draw_frame_line(self):
"""
Draws the gaming frame
"""
pg.draw.rect(self._frame, GREEN, [0, 0, self._frame.get_width(), self._frame.get_height()], 2)
def _draw_score(self):
"""
Draws the score on top left corner of the screen
"""
label_surface = self._font.render("SCORE: {0}".format(self._score), 0, PINK)
# use SCREEN surface (not FRAME surface) and blit label
self._screen.blit(label_surface, (self._snake_width, 2))
def _delete_score(self):
"""
Delete the score on top left corner of the screen by blitting BLACK label
"""
#pg.draw.rect(self._screen, BLACK, [0, 3, 50, self._snake_width], 0)
label_surface = self._font.render("SCORE: {0}".format(self._score), 0, BLACK)
# use SCREEN surface (not FRAME surface) and blit label
self._screen.blit(label_surface, (self._snake_width, 2))
def main():
SnakeGame().run()
if __name__ == "__main__":
main() |
############DEBUGGING#####################
# Describe Problem
# Play Computer
year = int(input("What's your year of birth?: "))
if year > 1980 and year < 1994:
print("You are a millenial.")
elif year >= 1994:
print("You are a Gen Z.")
#Solution: The indentation was wrong! In Python there should be indentation
#Also, when you run 1994 it didn't run, that's because of the parameters, we have to put '>=' sign
|
# -*- coding: utf-8 -*-
# @createTime : 2019/6/1 20:30
# @author : Huanglg
# @fileName: 3_有效的字母异位词.py
# @email: luguang.huang@mabotech.com
"""Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?"""
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s = sorted(s)
t = sorted(t)
for i in range(len(s)):
if s[i] != t[i]:
return False
return True
if __name__ == '__main__':
s = "anagram"
t = "nagaram"
S = Solution()
res = S.isAnagram(s, t)
print(res)
|
# -*- coding: utf-8 -*-
# @createTime : 2019/6/14 14:31
# @author : Huanglg
# @fileName: 6_判断是否有环.py
# @email: luguang.huang@mabotech.com
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# class Solution(object):
# def hasCycle(self, head):
# """
# :type head: ListNode
# :rtype: bool
# """
# temp = set()
# while head:
# if head in temp:
# return True
# temp.add(head)
# head=head.next
# return False
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
temp = 'huanglg'
while head:
if head.val == temp:
return True
else:
head.val = temp
head = head.next
return False
|
import re
from bs4 import BeautifulSoup
from nltk.corpus import stopwords
def tweet_to_words(raw_tweets):
# Function to convert a raw tweet to a string of words
# The input is a single string (a raw tweet), and
# the output is a single string (a preprocessed tweet)
#
# 1. Remove HTML
tweet_text = BeautifulSoup(raw_tweets,"lxml").get_text()
# 2. Remove non-letters
letters_only = re.sub("[^a-zA-Z]", " ", tweet_text)
# 3. Convert to lower case, split into individual words
words = letters_only.lower().split()
# 4. In Python, searching a set is much faster than searching a list, so convert the stop words to a set
stops = set(stopwords.words("english"))
# 5. Remove stop words
meaningful_words = [w for w in words if not w in stops]
# 6. Join the words back into one string separated by space and return the result.
return( " ".join( meaningful_words )) |
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
'''
class Solution(object):
def addBinary(self, a, b):
if max(a.len(), b.len()) == a.len():
b.zfill(a.len())
else:
a.zfill(b.len())
length = a.len() # length of the binary strings
index = a.len() - 1 # the last index of the binary strings
'''
There should be X cases:
carry=0, a=1, b=0 --> 1
'''
for index in length:
carry = "0"
if a[index] == "0" and b[index] == "1" and carry=="0":
index = index - 1
elif a[index]=="1" and b[index]=="1":
index = 0
# TODO: adding two binary from right to left |
"""
matematika.py
práce s knihovnou math
zaokrouhlování a mocniny
round, ceil, floor, pow, sqrt
"""
import math
#import random #modul pro generování náhodných čísel
#cislo=math.pi
cislo=float(input("Zadej číslo:"))
#cislo2=float(random.random())
mocnina=float(input("Zadej mocninu:"))
print(cislo)
print("funkce round", round(cislo,3)) #round - matematické zaokrouhlování
print("funkce ceil", math.ceil(cislo)) #ceil - zaokrouhlí na celé číslo nahoru
print("funkce floor", math.floor(cislo)) #floor - zaokrouhlí na celé číslo dolů
print("cislo:",cislo,"\n","mocnina:",mocnina)
cislo2=pow(cislo,mocnina) #pow - umocňování
print("funkce pow(umocňování)", cislo2)
print("funkce sqrt(druhá odmocnina z proměnné cislo)", math.sqrt(cislo)) #sqrt - druhá odmocnina
print("odmocnina:", cislo2**(1/mocnina)) #pomocí ** a převrácené hodnoty mocniny lze libovolně odmocňovat
|
"""
nakup.py
program načte názvy zboží, jejich cenu a nakoupené množství a vypíše do tabulky
"""
zbozi = "mléko", "brambory", "pivo"
cena = "15", "30", "12"
mnozstvi = "2", "1.5", "3"
pocet = len(zbozi)
for i in range(0,pocet):
print(f"{zbozi[i]:>10}\t {mnozstvi[i]:>3} * {float(cena[i]):>5.2f} = {(float(mnozstvi[i])*float(cena[i])):>5.2f} Kč" )
pass
|
"""
palindrom.py
program vyhodnotí, zda je dané slovo palindrom (slovo, které je zapředu a zezadu stejné)
"""
slovo = str(input("Zadej slovo: "))
slovo = slovo.lower()
delka = len(slovo)
zacatek = -1
konec = delka - 1
krok = -1
slovo_pozpatku = ""
for i in range(konec, zacatek, krok):
slovo_pozpatku = slovo_pozpatku + slovo[i]
if slovo == slovo_pozpatku:
print (f"Slovo {slovo} je palindrom (stejné při čtení zepředu i zezadu)")
else:
print (f"Slovo {slovo} palindrom není. ")
|
"""
vazenyPrumer.py
Vytvoř program, který na vstupu získá dvě
stejně velká pole -- hodnoty a k nim
odpovídající váhy. Na výstupu vypíše
hodnotu váženého průměru.
"""
import random
def vytvorPole(pocet):
pole = []
for i in range(0, pocet):
cislo = random.randint(1, 255)
pole.append(cislo)
return pole
def VazenyPrumerPole(pole, vaha):
suma = 0
for i in range(0, len(pole)):
suma = suma + (pole[i] * vaha[i])
prumer = suma / sum(vaha)
return prumer
hodnoty = []
vahy = []
pocetPrvkuPole = int(input("Zadej počet prvků pole hodnot: "))
hodnoty = vytvorPole(pocetPrvkuPole)
vahy = vytvorPole(pocetPrvkuPole)
prumerVazeny = VazenyPrumerPole(hodnoty, vahy)
prumerAritmeticky = sum(hodnoty)/len(hodnoty)
print(f"Pole {hodnoty}, váhy {vahy} vážený průměr {prumerVazeny}, aritmetický průměr je {prumerAritmeticky} ")
|
"""
trojuhelnik.py
Vytvoř program, který na vstupu získá
přirozené číslo, a na výstupu vykreslí
tvar rovnostranného trojúhelníku.
Př.: vstup = 4
výstup:
o
o o
o o o
o o o o
"""
def trojuhelnik(cislo):
for i in range(1, cislo+1):
print(" "*(cislo - i) + "o " * i)
pass
vstup = int(input("Zadej číslo: "))
trojuhelnik(vstup) |
def print_menu(menu):
print ("")
for key in menu:
print(f"\t\t {key}.-" + menu[key]["title"])
print("\t\t Pick a number from the list and an [option] if neccesary\n")
print ("\t\t Menu|Quit") |
rupee=int(input())
euro=rupee/80
print(euro) |
def compare_lists(list0, list1):
if len(list0) != len(list1):
print "The lists are not the same."
else:
for i in range(0, len(list0)):
if list0[i] != list1[i]:
print "the lists are not the same."
return
print "The lists are the same."
l1_a = [1,2,5,6,2]
l1_b = [1,2,5,6,2]
l2_a = [1,2,5,6,5]
l2_b = [1,2,5,6,5,3]
l3_a = [1,2,5,6,5,16]
l3_b = [1,2,5,6,5]
l4_a = ['celery','carrots','bread','milk']
l4_b = ['celery','carrots','bread','cream']
compare_lists(l1_a, l1_b)
compare_lists(l2_a, l2_b)
compare_lists(l3_a, l3_b)
compare_lists(l4_a, l4_b)
|
import random
import cmath
import decimal
from decimal import Decimal , ROUND_HALF_UP, localcontext
class Qualean:
'''
This is a Qualean Class.
'''
def __init__(self, user_input):
self.user_input = user_input
if (user_input in [-1, 0, 1]):
with localcontext() as ctx:
ctx.rounding = ROUND_HALF_UP
ctx.prec = 10
self.input_value = Decimal(user_input) * Decimal(random.uniform(-1, 1))
else:
raise ValueError("input value must be either 1 or 0 or -1")
def __round__(self):
return self.input_value
def __and__(self, other):
if not isinstance(other, Qualean):
return False
else:
return bool(self.input_value) and bool(other.input_value)
def __or__(self, other):
return bool(self.input_value) or bool(other.input_value)
def __ge__(self, other):
if not isinstance(other, Qualean):
return self.input_value >= other
else:
return self.input_value >= other.input_value
def __gt__(self, other):
if not isinstance(other, Qualean):
return self.input_value > other
else:
return self.input_value > other.input_value
def __invertsign__(self):
return self.input_value*-1
def __le__(self, other):
if not isinstance(other, Qualean):
return self.input_value <= other
else:
return self.input_value <= other.input_value
def __lt__(self, other):
if not isinstance(other, Qualean):
return self.input_value < other
else:
return self.input_value < other.input_value
def __mul__(self, other):
if not isinstance(other, Qualean):
return self.input_value * other
else:
with localcontext() as ctx:
ctx.rounding = ROUND_HALF_UP
ctx.prec = 10
return self.input_value * other.input_value
def __eq__(self, other):
if not isinstance(other, Qualean):
return self.input_value == other
else:
return self.input_value == other.input_value
def __add__(self, other):
if not isinstance(other, Qualean):
return self.input_value + other
else:
return self.input_value + other.input_value
def __str__(self):
return 'Qualean_value[{0}] = {1}'.format(self.user_input, self.input_value)
def __repr__(self):
return 'Qualean_value[{0}] = {1}'.format(self.user_input, self.input_value)
def __bool__(self):
return bool(self.input_value)
def __float__(self):
return float(self.input_value)
def __sqrt__(self):
return cmath.sqrt(self.input_value)
|
# -*- coding: utf-8 -*-
"""
Simulate voting behavior.
Convert voter preferences into preferences & rankings for candidates.
Typical function inputs
------------------------
voters : array shape (a, n)
Voter preferences; a-dimensional voter preferences for n issues.
- Each row of the array represents a voter's preferences
- Each column represents a difference issue.
candidates : array shape (b, n)
Candidate preferences for n-dimensional issues.
- Each row represents a candidate's preference
- Each column represents a difference issue.
Types of voting behavior to simulate
-----------------------------------
Preference Tolerance
====================
Assume that voters have a threshold of preference distance, at which if a
candidate exceeds the tolerance threshold, they will give zero score or
refuse to rank the candidate.
Preference Tolerance -- Last Hope
=================================
Assume that for some voters, if all candidates exceed their threshold of
preference tolerance, they might decide still vote for the single closet candidate.
Memory limitation
==================
Assume that voters might only rate/rank so many candidates, for example,
up to a limit of about 7.
Preference Error
================
Voters might miscalculate their preference distance from a candidate.
"""
import numpy as np
import logging
logger = logging.getLogger(__name__)
from votesim import votemethods
from votesim import utilities
def voter_distances(voters, candidates, weights=None, order=1):
"""Calculate preference distance of voters away from candidates.
Parameters
----------
voters : array shape (a, n)
Voter preferences; `a` number of voters, cardinal preferences for `n` issues.
candidates : array shape (b, n)
`b`-number of Candidate preferences for `n`-dimensional issues.
weights : None or array shape (a, n)
Dimensional weightings of each voter for each dimension.
Only relevant if n > 1
order : int
Order of norm
* 1 = taxi-cab norm; preferences for each issue add up
* 2 = euclidean norm; take the sqrt of squares.
Returns
-------
distances : array shaped (a, b)
Candidate `b` preference distance away from voter, for each voter `a`
"""
# diff shape = (voternum, n, 1) - (1, candnum, n)
# diff shape => (voternum, candnum, n)
diff = voters[:, None] - candidates[None, :]
if diff.ndim == 2:
distances = np.abs(diff)
elif diff.ndim == 3:
# Apply weights to each candidate via loop
if weights is not None:
for ii in range(voters.shape[1]):
diff = diff[:, :, ii] * weights[:, ii]
distances = np.linalg.norm(diff, ord=order, axis=2)
else:
s = 'Wrong number of dimensions input for voters %s or candidate %s'
s = s % (voters.shape, candidates.shape)
raise ValueError(s)
return distances
def distance2rank(distances):
"""Convert preference distance to candidate ranking.
Parameters
----------
distances : array shaped (a, b)
Candidate `b` preference distance away from voter, for each voter `a`
Returns
-------
rank : array shaped (a, b)
Election rankings of each voter for each candidate
- a : voters dimension
- b : candidates dimension
"""
ii = np.argsort(np.argsort(distances, axis=1), axis=1) + 1
return ii
def voter_distance_error(distances, error_std, rstate=None):
"""Add error to voter distances from candidates.
Parameters
----------
distances : array shape (a,b)
Distances generated by function `voter_distances`
error_std : array shape (a,)
standard deviation of distance error for each voter.
Each voter has an accuracy represented by this.
Returns
---------
distances : array shape (a,b)
New voter distances including voter error.
"""
if rstate is None:
rstate = np.random.RandomState
error_std = np.atleast_1d(error_std)
enorm = rstate.normal(0.0, scale=1.0, size=distances.shape)
error = enorm * error_std[:, None]
return distances + error
def __voter_rankings111(voters, candidates, cnum=None, distances=None):
"""
Create rankings of voter for candidates, by considering only
a top `cnum` of candidates and ignoring the rest. The last candidate
is rated 0. The closest candidate is rated 1. Others are linearly scaled in between.
Parameters
-------
---
voters : array shape (a, n)
Voter preferences; `a` number of voter cardinal preferences for `n` issues.
candidates : array shape (b, n)
Candidate preferences for n-dimensional issues.
cnum : None (default), int, or int array shaped (a,)
Max number of candidates that will be ranked. Can be set for each voter.
Returns
------
rankings : array shaped (a, b)
Voter rankings for each candidate
"""
# Create preference differences for every issue.
# diff = shape of (a, n, b) or (a, b)
# distances = shape of (a, b)
if distances is not None:
vnum = len(distances)
else:
vnum = len(voters)
distances = voter_distances(voters, candidates)
# ranking of candidate preferences
i_rank = np.argsort(distances, axis=1) + 1
if cnum is None:
return i_rank
else:
cnum = np.array(cnum)
if cnum.size == 1:
cnum = np.ones(vnum) * cnum
logger.debug('i_rank =\n %s', i_rank)
logger.debug('cnum = %s', cnum)
# get ranks to zero out
i_kill = (i_rank > cnum[:, None])
i_rank[i_kill] = 0
return i_rank
def voter_tolerance(voters, distances, tol, weights=None, strategy='abs'):
"""Construct voter tolerance.
Parameters
----------
voters : (a, n) array
Preferences for `a` voters
distances (a, b) array
Voter preference distances from `b` candidates
tol : (a,) array or float
Voter base tolerance parameter
weights : (a, n) array or None (optional)
Voter weighting for each preference dimension
strategy : str
Voter tolerance strategy
- "voter" -- set `tol` as factor of the average voter distance from the centroid.
- At tol=1, candidates farther than 1 x avg voter distance are rated zero
- At tol=2, candidates farther than 2 x avg voter distance are rated zero.
- "candidate" -- set `tol` relative to farthest distance of candidate to voter.
- At tol=1, the max distance candidate is rated zero.
- At tol=0.5, candidates at half of the max distance are rated zero
Returns
-------
out : (a, 1) array
Voter tolerance where distances greater than tolerance will
be assigned zero rating.
"""
if strategy == 'abs':
dtol = tol
elif strategy == 'voter':
v_mean = np.mean(voters, axis=0)
v_dist = voter_distances(voters, v_mean[None, :], weights=weights)
dmean = np.mean(v_dist)
dtol = dmean * tol
elif strategy == 'candidate':
dmax = np.max(distances, axis=1)
dtol = dmax * tol
else:
raise ValueError('Incorrect strategy arg = %s' % strategy)
logger.info('strategy=%s' % strategy)
logger.info('relative tol = %s', tol)
logger.info('absolute dtol = %s', dtol)
dtol = np.array(dtol)
if dtol.ndim == 1:
dtol = dtol[:, None]
return dtol
def voter_scores_by_tolerance(voters,
candidates,
distances=None,
weights=None,
tol=1,
cnum=None,
error_std=0,
strategy='abs',):
"""
Creating ratings from 0 to 1 of voter for candidates
using a tolerance circle.
- Assume that all voters are honest.
- Assume that voters have a preference "tolerance".
Candidates whose preference distance exceeds this tolerance have utility
set to zero.
- Linear mapping of preference distance and utility.
- Utility = 1 if candidate preference is exactly voter preference.
- Utility = 0 if candidate preference is exactly the tolerance distance.
- Assume that voters will give strongest possible preference to closest candidate,
unless that candidate is outside their preference tolerance.
Parameters
----------
voters : array shape (a, n)
Voter preferences; `a` voter cardinal preferences for `n` issues.
candidates : array shape (b, n)
`b` number of candidate preferences for `n`-dimensional issues.
tol : float, or array shaped (a,)
Voter candidate tolerance distance. If cardinal preference exceed tol,
utility set to zero. Toleranace is in same units as voters & candidates
cnum : None (default), int, or int array shaped (a,)
Max number of candidates that will be ranked. Can be set for each voter.
strategy : str
Tolerance determination strategy. Use the following string options:
- "abs" -- set `tol` as an absolute value to compare to distance.
- "voter" -- set `tol` as factor of the average voter distance from the centroid.
- At tol=1, candidates farther than 1 x avg voter distance are rated zero
- At tol=2, candidates farther than 2 x avg voter distance are rated zero.
- "candidate" -- set `tol` relative to farthest distance of candidate to voter.
- At tol=1, the max distance candidate is rated zero.
- At tol=0.5, candidates at half of the max distance are rated zero
Returns
-------
out : array shaped (a, b)
Utility scores from a-voters for each b-candidate.
"""
# Create preference differences for every issue.
# diff = shape of (a, n, b) or (a, b)
# distances = shape of (a, b)
if distances is None:
distances = voter_distances(voters, candidates, weights=weights)
# distances = voter_distance_error(distances, error_std, rstate=rstate)
if strategy == 'abs':
dtol = tol
elif strategy == 'voter':
v_mean = np.mean(voters, axis=0)
v_dist = voter_distances(voters, v_mean[None, :], weights=weights)
dmean = np.mean(v_dist)
dtol = dmean * tol
elif strategy == 'candidate':
dmax = np.max(distances, axis=1)
dtol = dmax * tol
else:
raise ValueError('Incorrect strategy arg = %s' % strategy)
logger.info('strategy=%s' % strategy)
logger.info('relative tol = %s', tol)
# logger.info('absolute dtol = %s', dtol)
dtol = np.array(dtol)
if dtol.ndim == 1:
dtol = dtol[:, None]
# Get utility from tol
i = np.where(distances > dtol)
utility = (dtol - distances) / dtol
utility[i] = 0
# Set to zero candidates past max number to score
if cnum is not None:
ranks = voter_rankings(voters, candidates,
cnum=cnum,
distances=distances)
iremove = ranks <= 0
utility[iremove] = 0
#rescale utility so favorite has max score,
max_utility = np.max(utility, axis=1)
min_utility = np.min(utility, axis=1)
i2 = np.where(max_utility == 0)
max_utility[i2] = 1. # avoid divide by zero error for unfilled ballots
umax = max_utility[:, None]
umin = min_utility[:, None]
# Rescale utilities so that least favorite has zero score.
ratings = utility / max_utility[:, None]
ratings = (utility - umin) / (umax - umin)
ratings = np.maximum(0, ratings)
return ratings
def voter_scores_by_rank(voters, candidates, cnum=None):
"""
Calculate scores by assuming voters will only rate a set number `cnum`
of candidates from 0 to 1. Tolerance is based on number of candidates
rather than preference distance.
Parameters
----------
voters : array shape (a, n)
Voter preferences; n-dimensional voter cardinal preferences for n issues.
candidates : array shape (b, n)
Candidate preferences for n-dimensional issues.
cnum : None (default), int, or int array shaped (a,)
Max number of candidates that will be ranked. Can be set for each voter.
Returns
-------
out : array shaped (a, b)
Utility scores from a-voters for each b-candidate.
"""
distances = voter_distances(voters, candidates)
rankings = voter_rankings(voters, candidates, cnum, distances)
iremove = rankings <= 0
distances[iremove] = -1
dtol = np.max(distances, axis=1)
utility = (dtol - distances) / dtol
utility[iremove] = 0
#rescale utility so favorite has max score
max_utility = np.max(utility, axis=1)
i2 = np.where(max_utility == 0)
max_utility[i2] = 1.
return utility / max_utility[:, None]
def zero_out_random(ratings, limits, weights=None, rs=None):
"""
Zero-out scores or ranks by random. Simluation of limits of voter information,
where for many candidates, voters may not be informed of all of them.
Parameters
----------------
ratings : array shaped (a, b)
Ratings, scores, ranks from a-voters for each b-candidate.
limits : int array shaped (a,)
Number of canidates each voter has knowledge about
weights : array shaped (b,)
Media model, probability weighting for each candidate where some
candidates are more likely to be known than others.
Returns
-------
out : array shaped (a,b)
Adjusted ratings, scores, ranks with candidate limits applied.
"""
ratings = np.copy(ratings)
limits = limits.astype(int)
vnum, cnum = ratings.shape
remove_arr = np.maximum(0, cnum - limits)
if rs is None:
rs = np.random.RandomState()
for i, remove_num in enumerate(remove_arr):
index = rs.choice(cnum, size=remove_num, p=weights, replace=False)
ratings[i, index] = 0
return ratings
def __zero_out_random(ratings, climits, weights=None, rs=None):
"""
Zero-out scores or ranks by random. Simluation of limits of voter information,
where for many candidates, voters may not be informed of all of them.
Parameters
----------------
scores : array shaped (a, b)
Ratings, scores, ranks from a-voters for each b-candidate.
climits : int array shaped (a,)
Number of canidates each voter has knowledge about
weights : array shaped (b,)
Media model, probability weighting for each candidate where some
candidates are more likely to be known than others.
Returns
-------
out : array shaped (a,b)
Adjusted ratings, scores, ranks with candidate limits applied.
"""
raise NotImplementedError()
climits = climits.astype(int)
if rs is None:
rs = np.random.RandomState()
ratings = np.atleast_2d(ratings).copy()
voter_num, candidate_num = ratings.shape
if weights is None:
weights = np.ones(candidate_num)
wsum = np.sum(weights)
weights = weights / wsum
# premove = 1 - weights
# premove = premove / np.sum(premove)
#
# cremoves = candidate_num - climits
# cremoves[cremoves < 0] = 0
iremove0 = np.ones(candidate_num, dtype=bool)
for i, clim in enumerate(climits):
iremove = iremove0.copy()
index = rs.choice(candidate_num, size=clim, p=weights, replace=False)
iremove[index] = False
ratings[i, iremove] = 0
return ratings
|
#Problem 18: Maximum path sum I
#Michael Ge, June 13, 2015
'''
By starting at the top of the triangle below and moving to adjacent numbers
on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt (right click and
'Save Link/Target As...'), a 15K text file containing a
triangle with one-hundred rows.
'''
#Variables
HEIGHT = 100
NUM_EL = (HEIGHT) * (HEIGHT + 1) / 2
#Node: contains a value, and children nodes
class Node:
def __init__(self, value, parent, childL, childR):
self.v = value
self.cL = childL
self.cR = childR
def get_childL(self):
return self.cL
def get_childR(self):
return self.cR
def get_value(self):
return self.v
def set_childL(self, _c):
self.cL = _c
def set_childR(self, _c):
self.cR = _c
def set_value(self, _v):
self.v = _v
#Data Input
with open('test.txt') as f:
nums = map(int, f.read().split())
nodes = []
for x in nums:
nodes.append(Node(x, None, None, None))
f.close()
#Triangle Graph Generation
inc = 0
for row in range(HEIGHT):
for _ in range(1, row+1):
nodes[inc].set_childL(nodes[inc+row])
nodes[inc].set_childR(nodes[inc+row+1])
inc+=1
#Largest Sum Algorithm; Compares right to left up the tree
for node in nodes[::-1]:
left = node.get_childL()
right = node.get_childR()
if left is not None and right is not None:
node.set_value(node.get_value() +
max(left.get_value(), right.get_value()))
elif left is not None:
node.set_value(node.get_value() + left.get_value())
elif right is not None:
node.set_value(node.get_value() + right.get_value())
print nodes[0].get_value()
|
"""Una lista que guarda las ganancias maximas para cada presupuesto hasta el presupuiesto dado"""
miniMochilas = []
"""una lista donde se guardan diccionarios para poder tener las cantidades usadas para cada producto"""
cantDiferentesPesos = []
"""limite de stock del producto"""
cantidadMaxima = []
"""El producto asociado a su peso"""
productos = {}
"""El costo de produccion para cada producto"""
costProd = []
"""ganancia por producto, se quiere tener la mayor ganancia sin pasar el presupuesto"""
gananciasNetas = []
def contarGananciaLimite(PresupuestoActual):
for i in range(len(costProd)):
pesoActual = costProd[i]
valorActual = gananciasNetas[i]
for x in range(cantidadMaxima[i]):
for j in range(PresupuestoActual, pesoActual-1, -1):
if miniMochilas[j-pesoActual] + valorActual > miniMochilas[j]:
for k in range(len(cantDiferentesPesos[j])):
cantDiferentesPesos[j][costProd[k]] = cantDiferentesPesos[j-pesoActual][costProd[k]]
cantDiferentesPesos[j][pesoActual] = cantDiferentesPesos[j][pesoActual]+1
miniMochilas[j] = miniMochilas[j-pesoActual] + valorActual
def ChoiceExample(NroEjemplo):
global cantidadMaxima
global productos
global costProd
global gananciasNetas
global miniMochilas
global cantDiferentesPesos
cantDiferentesPesos.clear()
miniMochilas.clear()
cantidadMaxima.clear()
productos.clear()
costProd.clear()
gananciasNetas.clear()
if(NroEjemplo == 1):
print("Ejecutando ejemplo de autos...")
cantidadMaxima = [2, 3, 2, 4, 3, 2]
productos = {6592: "Suzuki Swift", 1360: "Suzuki Santana", 16000: "Nissan Patrol 2011", 200000: "Lamborghini URUS", 39580: "BMW X7", 15960: "Tesla Cybertruck RWD"}
costProd = [6592, 1360, 16000, 200000, 39580, 15960]
gananciasNetas = [9888, 2040, 24000, 300000, 59370, 23940]
Presupuesto = 300000
Mochila(Presupuesto)
elif(NroEjemplo==2):
print("Ejecutando ejemplo de zapatos...")
cantidadMaxima = [7, 8, 5, 6, 8, 3]
productos = {94: "Adidas Nemeziz 19", 85: "Adidas Mutator", 93: "Adidas The Predator",
84: "Nike Mercurial Superfly 8 Elite FG", 72: "Nike Mercurial Vapor 14 Elite FG",
81: "Nike Phantom GT Elite Dynamic Fit 3D FG"}
costProd = [94, 85, 93, 84, 72, 81]
gananciasNetas = [40, 36, 40, 36, 31, 35]
Presupuesto = 1000
Mochila(Presupuesto)
elif (NroEjemplo == 3):
print("Ejecutando ejemplo de mouses...")
cantidadMaxima = [8, 10, 15, 5, 5, 20]
productos = {40: "Logitech G 910", 14: "Razer Gaming Viper", 6: "Pictek Mouse",
21: "Razer Basilisk X", 70: "Logitech G PRO X Superlight Inalambrico",
4: "VEGCOO C10"}
costProd = [40, 14, 6, 21, 70, 4]
gananciasNetas = [55, 16, 8, 24, 85, 6]
Presupuesto = 500
Mochila(Presupuesto)
elif (NroEjemplo == 4):
print("Ejecutando ejemplo de procesadores...")
cantidadMaxima = [10, 18, 32, 24, 38, 22]
productos = {126: "AMD Ryzen 7 5800X", 210: "AMD Ryzen 9 5900X", 66: "Intel Core i5-9600K",
96: "Intel Core i7-10700K", 57: "AMD Ryzen 5 2600",
114: "Intel Core i9-9900K"}
costProd = [126, 210, 66, 96, 57, 114]
gananciasNetas = [294, 490, 154, 224, 133, 266]
Presupuesto = 2000
Mochila(Presupuesto)
elif (NroEjemplo == 5):
print("Ejecutando ejemplo de panetones...")
cantidadMaxima = [20, 20, 46, 23, 78, 46, 12]
productos = {30: "Panetón Gustossi", 40: "Panetón La Francesa ChocoChip", 80: "Panetón D'onfrio Chocotón",
120: "Panetón Anapqui Real", 20: "Panetón Todinno",
42: "Panetón San Gabriel", 35: "Panetón San Gabriel Deli-Choc"}
costProd = [30, 40, 80, 120, 20, 42, 35]
gananciasNetas = [5, 8, 10, 20, 3, 8, 11]
Presupuesto = 2500
Mochila(Presupuesto)
elif (NroEjemplo == 6):
print("Ejecutando ejemplo de consolas...")
cantidadMaxima = [10, 16, 30, 32, 20, 25, 14, 20]
productos = {450: "PlayStation 5", 355: "PlayStation 5 Online Edition", 480: "XBOX Series X",
280: "XBOX Series S", 245: "Nintendo Switch",
200: "Nintendo Switch Lite", 380: "PlayStation 4 Pro", 400: "XBOX One X"}
costProd = [450, 355, 480, 280, 245, 200, 380, 400]
gananciasNetas = [50, 45, 20, 20, 40, 20, 30, 40]
Presupuesto = 21000
Mochila(Presupuesto)
elif(NroEjemplo == 0):
cant = input("Introduce el numero de productos que tiene: ")
while not cant.isdigit() or not (int(cant) > 0):
cant = input(f"La entrada '{cant}' no es valida, intenta otra vez: ")
cant = int(cant)
for i in range(cant):
temp = input(f"Introduce el nombre del producto {i+1}: ")
temp2 = input(f"Introduce la cantidad maxima de '{temp}' que no sea igual a uno anterior: ")
while not temp2.isdigit() or not (int(temp2) > 0):
temp2 = input(f"La entrada '{temp2}' no es valida, intenta otra vez: ")
temp2 = int(temp2)
cantidadMaxima.append(temp2)
temp3 = input(f"Introduce el coste de produccion de '{temp}': ")
while not temp3.isdigit() or not (int(temp3) > 0):
temp3 = input(f"La entrada '{temp3}' no es valida, intenta otra vez: ")
temp3 = int(temp3)
costProd.append(temp3)
temp4 = input(f"Introduce la ganancia neta del producto '{temp}': ")
while not temp4.isdigit() or not (int(temp4) > 0):
temp4 = input(f"La entrada '{temp4}' no es valida, intenta otra vez: ")
temp4 = int(temp4)
gananciasNetas.append(temp4)
productos[temp3] = temp
Presupuesto = input("Introduce el presupuesto que tiene: ")
while not Presupuesto.isdigit() or not (int(Presupuesto) > 0):
Presupuesto = input(f"La entrada '{Presupuesto}' no es valida, intenta otra vez: ")
Presupuesto = int(Presupuesto)
print("Ejecuntando ejemplo propio...")
Mochila(Presupuesto)
print("============================================================================================================================================================================")
def Mochila(Presupuesto):
for i in range(Presupuesto+1):
miniMochilas.append(0)
cantidades = {}
for j in costProd:
cantidades[j] = 0
cantDiferentesPesos.append(cantidades)
contarGananciaLimite(Presupuesto)
print("Ejecutado con éxito")
print("============================================================================================================================================================================")
print(f"Para un presupuesto de {Presupuesto} se tiene:")
inversion = 0
for i in cantDiferentesPesos[Presupuesto]:
inversion += cantDiferentesPesos[Presupuesto][i]*i
print(f"Con una inversion de {inversion} se consigue un total de {miniMochilas[Presupuesto]+inversion} donde se tiene una ganancia maxima neta de {miniMochilas[Presupuesto]}.")
for i in cantDiferentesPesos[Presupuesto]:
if cantDiferentesPesos[Presupuesto][i] != 0:
print(f"Producir {cantDiferentesPesos[Presupuesto][i]} de '{productos[i]}' con coste de {cantDiferentesPesos[Presupuesto][i]*i}.")
print("============================================================================================================================================================================")
Choice2 = ""
while(Choice2 != "MENU"):
Choice2 = input("Escriba 'MENU' para volver al menu: " )
def Menu():
print("============================================================================================================================================================================")
print("Escribe 'E1' para ir al ejemplo 1.")
print("Escribe 'E2' para ir al ejemplo 2.")
print("Escribe 'E3' para ir al ejemplo 3.")
print("Escribe 'E4' para ir al ejemplo 4.")
print("Escribe 'E5' para ir al ejemplo 5.")
print("Escribe 'E6' para ir al ejemplo 6.")
print("Escribe 'E' para generar un ejemplo nuevo.")
print("Escribe 'FIN' para salir del programa.")
print("============================================================================================================================================================================")
class main():
Menu()
Choice = input()
while(Choice != "FIN"):
if(Choice == "E1"):
ChoiceExample(1)
elif(Choice == "E2"):
ChoiceExample(2)
elif(Choice == "E3"):
ChoiceExample(3)
elif(Choice == "E4"):
ChoiceExample(4)
elif(Choice == "E5"):
ChoiceExample(5)
elif(Choice == "E6"):
ChoiceExample(6)
elif(Choice == "E"):
ChoiceExample(0)
else:
print(f"Comando no valido {Choice}")
Menu()
Choice = input() |
import pprint
# x = -1
# print("Hello")
#
# if x < 0:
# print("Меньше нуля")
# print("Good bay")
# a, b = 10, 5
# if a > b:
# print("a > b")
#
# if a > b and a >0:
# print("Good")
#
# if (a >b) and (a > 0 or b < 1000):
# print("good")
#
# if 5 < b and b < 10:
# print("Good")
# if '34' > '123':
# print("Good")
#
# if '123' > '12':
# print("Good")
#
# if [1, 2] > [1, 1]:
# print("Good")
# print("Hello")
#
# x = 38
# if x < 0:
# print("Меньше нуля")
# else:
# print("Больше нуля")
# print("Good bay")
# print("Hello")
#
# x = 38
# if x < 0:
# print("Меньше нуля")
# elif x == 0:
# print("Равно нулю")
# elif x == 1:
# print("Равно еденице")
# else:
# print("Больше нуля")
# print("Good bay")
# Цыкл while(до тех пор пока)
# print("Hello")
# i = 1
# while i < 10:
# i = i * 2
# print(i)
# print("Good bay")
# print("Hello")
# f1, f2 = 1, 1
# while f2 < 100000000000:
# print(f2)
# next_f2 = f1 + f2
# next_f1 = f2
# f1, f2 = next_f1, next_f2
# print("Good bay")
# my_pets = ['lion', 'dog', 'skunk', 'hamster', 'cat', 'monkey']
# i = -1
# while i < len(my_pets):
# i += 1
# if i == 2:
# continue
# pet = my_pets[i]
# print('Проверяем', pet)
# if pet == 'cat':
# print('Ура, кот найден!')
# break
# print('Good bay')
# print("Hello")
# f1, f2, count = 0, 1, 0
# while f2 < 1000000:
# count +=1
# if count > 27:
# print("Итерация больше 27 - прерываюсь")
# break
# f1, f2 = f2, f1 + f2
# if f2 < 1000:
# continue
# print(f2)
# else:
# print("Было", count, "итераций")
# Цикл for
# элементы списка
# a, b = 1, 2
# (a, b) = (1, 2)
# for element in [(1, 2), (3, 4)]:
# a, b = element[0], element[1]
# print(a + b)
#
# for (a, b) in [(1, 2), (3, 4)]:
# print(a + b)
# pair_list = [(1, 2), (3, 4), (5, 6)]
# for a, b in pair_list:
# print(a + b)
# tripl_list = [(1, 2, 3), (4, 5, 6)]
# for a, b, c in tripl_list:
# print(a, b, c)
# Полезные функции в цикле
# zoo_pets = [
# 'lion', 'skunk',
# 'elephant', 'horse',
# ]
# for i, animal in enumerate(zoo_pets):
# print(i, animal)
# for i in range(100, 600, 50):
# print(i)
# zoo_pets = [
# 'lion', 'skunk',
# 'elephant', 'horse',
# ]
# for animal in zoo_pets:
# for char in animal:
# print(char)
# print(animal)
# zoo_pets_mass = {
# 'lion': 300,
# 'skunk': 5,
# 'elephant': 5000,
# 'horse': 400,
# }
# total_mass = 0
# for animal in zoo_pets_mass:
# print(animal, zoo_pets_mass[animal])
# total_mass += zoo_pets_mass[animal]
# print('Общая масса животных', total_mass)
# for animal, mass in zoo_pets_mass.items():
# print(animal, mass)
# total_mass += mass
# print('Общий вес животных', total_mass)
# for mass in zoo_pets_mass.values():
# print(mass)
# total_mass += mass
# print('Общая масса', total_mass)
# def same_func():
# print('Привет! Я функция')
#
# same_func()
# my_list = [3, 14, 15, 92, 6]
# for element in my_list:
# same_func()
# def function_with_params(param):
# print('Функцию вызвали с параметром', param)
#
#
# my_list = [3, 14, 15, 92, 6]
# for element in my_list:
# print('Начало цикла')
# function_with_params(param=element)
# print('Конец цикла')
# def power(number, pow):
# print('Функцию вызвали с параметрами', number, 'в степени', pow)
# power_value = number ** pow
# return power_value
#
#
# my_list = [3, 14, 15, 92, 6]
# for element in my_list:
# result = power(element, 10)
# print(result)
# def my_function():
# """Не делает ничего, но документируем,
# Нет, правда, Эта функция ничего не делает.
# """
# pass
#
# print(my_function.__doc__)
# динамическая типизация
# def multiplay(nub_1, nub_2):
# print('Функцию вызвали с параметрами', nub_1, nub_2)
# value = nub_1 * nub_2
# return value
# def multiplay(nub_1, nub_2):
# print('Функцию вызвали с параметрами', nub_1, nub_2)
# if isinstance(nub_1, int) and isinstance(nub_2, int):
# value = nub_1 * nub_2
# return value
# return 'error'
#
# print(multiplay(42, 27))
# print(multiplay(5, 'Привет'))
# print(multiplay(5, 7))
# параметры передаются как ссылка
# def elephant_to_free(some_list):
# elephand_found = 'elephand' in some_list
# if elephand_found:
# some_list.remove('elephand')
# print('Слон на свобооде')
# else:
# print('Все слоны отпушенны на свободу')
# return elephand_found
#
#
# zoo = ['lion', 'elephand', 'monkey', 'skunk', 'horse', 'elephand']
#
# elephant_to_free(zoo)
# elephant_to_free(zoo)
# elephant_to_free(zoo)
# print('Осталось выпустить только:', zoo)
a = 4#бумага
b = 5#бумага
c = 4#конверт
d = 6#конверт
if a < c and b < d:
print('ok')
else:
print('no')
|
from random import randint
def input_matrix(no_Of_Elements, max_grad_polinom):#crearea matricei patratate de polinoame de la tastatura
Matrix = []
for it1 in range(no_Of_Elements):
row = []
for it2 in range(no_Of_Elements):
polinom = []
print(f'Polinomul situat pe linia {it1} coloana {it2} :' , end=" ")
for it3 in range(max_grad_polinom+1):
print(f'Coeficientul lui x^{it3}=', end="")
polinom.append(int(input())) #adaugam in vectorul polinom coeficientii cititi de la tastatura(polinom[0] fiind coeficientul lui x^0, polinom[1] coeficientul lui x^1...)
row.append(polinom) #adaugam in vectorul row polinomul creat anterior
Matrix.append(row) #adaugam in vectorul Matrix randul de polinoame creat anterior formand astfel o matrice tridimensionala
return Matrix
def create_matrix(no_Of_Elements, max_coef, max_grad_polinom): #crearea matricei patrate de polinoame generate random
Matrix = []
for it1 in range(no_Of_Elements):
row = []
for it2 in range(no_Of_Elements):
polinom = []
for it3 in range(max_grad_polinom+1):
polinom.append(randint(0, max_coef)) #adaugam in vectorul polinom un numar random generat intre 0 si variabila max_coef(polinom[0] fiind coeficientul lui x^0, polinom[1] coeficientul lui x^1...)
row.append(polinom) #adaugam in vectorul row polinomul creat anterior
Matrix.append(row) #adaugam in vectorul Matrix randul de polinoame creat anterior formand astfel o matrice tridimensionala
return Matrix
def print_matrix(Matrix): #afisarea matricei patrate de polinoame cu coeficienti reali
for it1 in range(len(Matrix)):
for it2 in range(len(Matrix[it1])):
print(f'Polinomul situat pe linia {it1} coloana {it2} este:', end=" ")
for it3 in range(len(Matrix[it1][it2])):
print(f'{Matrix[it1][it2][it3]}*x^{it3}', end="")
if it3 != (len(Matrix[it1][it2])-1):
print('+', end="")
print('\n', end="")
def Pij(root, position1, position2, Matrix): #evaluarea unui polinom intr-un punct dat p
value = 0
polinom = Matrix[position1][position2]
for it1 in range(len(polinom)):
value = value + polinom[it1] * (root ** it1) #calculam polinomul inlocuind x-ul cu root
print(f'Valoarea polinomului situat pe linia {position1} coloana {position2} in punctul {root} este: {value}')
def sum(A, B): #suma a doua matrici A si B
Matrix = []
for it1 in range(len(A)):
row = []
for it2 in range(len(A[it1])):
polinom = []
for it3 in range(len(A[it1][it2])):
polinom.append(A[it1][it2][it3] + B[it1][it2][it3]) #adunam cele doua polinoame coeficient cu coeficient si le stocam in vectorul polinom
row.append(polinom)
Matrix.append(row)
return Matrix
def prodpol(A, B): #produsul dintre doua polinoame A si B
polinom = [0]*(len(A)+len(B))
for it1 in range(len(A)):
for it2 in range(len(B)):
polinom[it1+it2] += A[it1]*B[it2]
return polinom
def sumpol(vector_of_poli): #suma polinoamelor aflate intr-un vector
sum = [0]*(len(vector_of_poli[0]))
for it1 in range(len(vector_of_poli)):
for it2 in range(len(vector_of_poli[it1])):
sum [it2] += vector_of_poli[it1][it2]
return sum
def prod(A, B): #produsul intre doua matrici A si B
Matrix = []
for it1 in range(len(A)):
row = []
for it2 in range(len(A)):
polinom = []
for it3 in range(len(A)):
polinom.append(prodpol(A[it1][it3],B[it3][it2])) #calculam produsul dintre polinomul A si polinomul B folosind functia prodpol
row.append(sumpol(polinom)) #vectorul polinom contine len(A) polinoame, realizam suma acestora folosind functia sumpol pentru a obtine polinomul final
Matrix.append(row)
return Matrix
|
import random
class Maze:
def __init__(self, width, height):
self.width = width // 2 * 2 + 1
self.height = height // 2 * 2 + 1
self.start = [-1, -1]
self.goal = [-1, -1]
self.quad = random.choice(range(4))
if self.quad == 0:
self.start = [width-1, 0]
self.goal = [width, 0]
if self.quad == 1:
self.start = [0, 0]
self.goal = [0, 0]
if self.quad == 2:
self.start = [0, height-1]
self.goal = [0, height]
if self.quad == 3:
self.start = [width-1, height-1]
self.goal = [width, height]
# this creates a 2d-array for your maze data (False: path, True: wall)
self.cells = [
[True for x in range(self.width)]
for y in range(self.height)
]
self.create_maze(self.start[0], self.start[1])
def set_path(self, x, y):
self.cells[y][x] = False
def set_wall(self, x, y):
self.cells[y][x] = True
# a function to return if the current cell is a wall,
# and if the cell is within the maze bounds
def is_wall(self, x, y):
# checks if the coordinates are within the maze grid
if 0 <= x < self.width and 0 <= y < self.height:
# if they are, then we can check if the cell is a wall
return self.cells[y][x]
# if the coordinates are not within the maze bounds, we don't want to go there
else:
return False
def create_maze(self, x, y):
# set the current cell to a path, so that we don't return here later
self.set_path(x, y)
# we create a list of directions (in a random order) we can try
all_directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
random.shuffle(all_directions)
# we keep trying the next direction in the list, until we have no directions left
while len(all_directions) > 0:
# we remove and return the last item in our directions list
direction_to_try = all_directions.pop()
# calculate the new node's coordinates using our random direction.
# we *2 as we are moving two cells in each direction to the next node
node_x = x + (direction_to_try[0] * 2)
node_y = y + (direction_to_try[1] * 2)
# check if the test node is a wall (eg it hasn't been visited)
if self.is_wall(node_x, node_y):
# success code: we have found a path
# set our linking cell (between the two nodes we're moving from/to) to a path
link_cell_x = x + direction_to_try[0]
link_cell_y = y + direction_to_try[1]
if self.quad == 0:
if ((self.width - self.goal[0]) + self.goal[1]) < ((self.width - link_cell_x) + link_cell_y):
self.goal[0] = link_cell_x
self.goal[1] = link_cell_y
if self.quad == 1:
if (self.goal[0] + self.goal[1]) < (link_cell_x + link_cell_y):
self.goal[0] = link_cell_x
self.goal[1] = link_cell_y
if self.quad == 2:
if (self.goal[0] + (self.height - self.goal[1])) < (link_cell_x + (self.height - link_cell_y)):
self.goal[0] = link_cell_x
self.goal[1] = link_cell_y
if self.quad == 3:
if (self.goal[0] + self.goal[1]) > (link_cell_x + link_cell_y):
self.goal[0] = link_cell_x
self.goal[1] = link_cell_y
self.set_path(link_cell_x, link_cell_y)
# "move" to our new node. remember we are calling the function every
# time we move, so we call it again but with the updated x and y coordinates
self.create_maze(node_x, node_y)
return
def matrix(self):
matrix = [['1'] * self.width for _ in range(self.height)]
for y in range(self.height):
for x in range(self.width):
if self.cells[y][x]:
matrix[y][x] = '1'
else:
matrix[y][x] = '0'
matrix[self.goal[1]][self.goal[0]] = "D"
matrix[self.start[1]][self.start[0]] = "S"
return matrix
def __str__(self):
string = ""
conv = {
True: "1",
False: "0"
}
for y in range(self.height):
for x in range(self.width):
if x == self.goal[0] and y == self.goal[1]:
string += "D"
elif x == self.start[0] and y == self.start[1]:
string += "S"
else:
string += conv[self.cells[y][x]]
string += "\n"
return string |
import numpy as np
import matplotlib.pyplot as plt
from enum import Enum
# Methods & Derivative function
def derivative(x, y):
return (x + 20 * y) * np.sin(x * y)
def rk_2nd_order(x, a2, h, initial=0, group='h'):
a1 = 1 - a2
p1 = 0.5 / a2
q11 = 0.5 / a2
y = np.zeros(len(x))
y[0] = initial
for i in range(1, len(x)):
k1 = derivative(x[i - 1], y[i - 1])
k2 = derivative(x[i - 1] + p1 * h, y[i - 1] + q11 * k1 * h)
y[i] = y[i - 1] + (a1 * k1 + a2 * k2) * h
if group == 'h':
plt.plot(x, y, linewidth=1, label=Method(a2).name)
else:
plt.plot(x, y, linewidth=1, label='h = ' + str(h))
def euler_method(x, h, initial, group='h'):
y = np.zeros(len(x))
y[0] = initial
for i in range(1, len(x)):
slope = derivative(x[i - 1], y[i - 1])
y[i] = y[i - 1] + slope * h
if group == 'h':
plt.plot(x, y, linewidth=1, label="Euler_method")
else:
plt.plot(x, y, linewidth=1, label='h = ' + str(h))
def rk_4th_order(x, h, initial, group='h'):
y = np.zeros(len(x))
y[0] = initial
for i in range(1, len(x)):
k1 = derivative(x[i - 1], y[i - 1])
k2 = derivative(x[i - 1] + 0.5 * h, y[i - 1] + 0.5 * h * k1)
k3 = derivative(x[i - 1] + 0.5 * h, y[i - 1] + 0.5 * h * k2)
k4 = derivative(x[i - 1] + h, y[i - 1] + k3 * h)
y[i] = y[i - 1] + (1 / 6) * (k1 + 2 * k2 + 2 * k3 + k4) * h
if group == 'h':
plt.plot(x, y, linewidth=1, label="RK_4th_order")
else:
plt.plot(x, y, linewidth=1, label='h = ' + str(h))
class Method(Enum):
Huen = 1 / 2
Midpoint = 1
Ralston = 2 / 3
# Plotting graphs by step-size (h)
plt.style.use('fivethirtyeight')
# Step sizes
h_values = [0.5, 0.1, 0.05, 0.01]
# Initial value, at x=0
ini = 4
for h in h_values:
# Setting up Graph
plt.figure(figsize=(12, 6))
plt.axhline(y=0, color='lightgrey', linewidth=3)
plt.axvline(x=0, color='lightgrey', linewidth=3)
# Domain
x = np.arange(0, 10.01, h)
# Euler's Method, first order
euler_method(x, h=h, initial=ini)
# Huen's Method, a2=1/2
rk_2nd_order(x, a2=1 / 2, h=h, initial=ini)
# Midpoint Method, a2=1
rk_2nd_order(x, a2=1, h=h, initial=ini)
# Ralston's Method, a2=1/2
rk_2nd_order(x, a2=2 / 3, h=h, initial=ini)
# RK 4th Order Method
rk_4th_order(x, h=h, initial=ini)
plt.title("Plots for h=" + str(h))
plt.legend()
plt.savefig('step_size/h=' + str(h) + '.png', format='png')
# Plotting graphs according to Methods
plt.style.use('fivethirtyeight')
# Step sizes
h_values = [0.5, 0.1, 0.05, 0.01]
# Initial value, at x=0
ini = 4
# Domain
x = np.arange(0, 10.01, h)
# Euler's Method, first order
plt.figure(figsize=(12, 6))
plt.axhline(y=0, color='lightgrey', linewidth=3)
plt.axvline(x=0, color='lightgrey', linewidth=3)
for h in h_values:
x = np.arange(0, 10.01, h)
euler_method(x, h=h, initial=ini, group='method')
plt.title("Euler's Method")
plt.legend()
plt.savefig('methods/Euler\'s Method.png', format='png')
# Huen's Method, a2=1/2
plt.figure(figsize=(12, 6))
plt.axhline(y=0, color='lightgrey', linewidth=3)
plt.axvline(x=0, color='lightgrey', linewidth=3)
for h in h_values:
x = np.arange(0, 10.01, h)
rk_2nd_order(x, a2=1 / 2, h=h, initial=ini, group='method')
plt.title("Huen\'s Method")
plt.legend()
plt.savefig('methods/Huen\'s Method.png', format='png')
# Midpoint Method, a2=1
plt.figure(figsize=(12, 6))
plt.axhline(y=0, color='lightgrey', linewidth=3)
plt.axvline(x=0, color='lightgrey', linewidth=3)
for h in h_values:
x = np.arange(0, 10.01, h)
rk_2nd_order(x, a2=1, h=h, initial=ini, group='method')
plt.title("Midpoint Method")
plt.legend()
plt.savefig('methods/Midpoint Method.png', format='png')
# Ralston's Method, a2=1/2
plt.figure(figsize=(12, 6))
plt.axhline(y=0, color='lightgrey', linewidth=3)
plt.axvline(x=0, color='lightgrey', linewidth=3)
for h in h_values:
x = np.arange(0, 10.01, h)
rk_2nd_order(x, a2=2 / 3, h=h, initial=ini, group='method')
plt.title("Ralston's Method")
plt.legend()
plt.savefig('methods/Ralston\'s Method.png', format='png')
# RK 4th Order Method
plt.figure(figsize=(12, 6))
plt.axhline(y=0, color='lightgrey', linewidth=3)
plt.axvline(x=0, color='lightgrey', linewidth=3)
for h in h_values:
x = np.arange(0, 10.01, h)
rk_4th_order(x, h=h, initial=ini, group='method')
plt.title("RK 4th order Method")
plt.legend()
plt.savefig('methods/RK 4th order Method.png', format='png')
|
import time
######## THIS WAS SUPPOSED TO CONTAINS ALL THE MENUS OF THE GAME #######
#Menu only usefull for the combat, TODO all the others (Magic, consumables, lvl up , etc..)
class Menu() :
def intro(self):
print(""" Preparez vous à rentrer dans la tour!
Vous ouvrez la porte:
1er étage! """)
def combat(self, player, enemy):
#choice = 0
time.sleep(1)
print(" "
""
" VERSUS : lvl", player.lvl," ", enemy.name, " HP :",enemy.hp,"""
""",enemy.description,"""
YOUR HP: """, player.hp,"/",player.max_hp," YOUR MANA: ", player.mana, "/", player.max_mana,"""
VOS ACTIONS DISPONIBLES:
ATTACK (1) !MAGIC! (2) CONSUMABLE (3)
""")
#while choice != 1 & choice !=2 & choice != 3 :
choice = int(input(" "))
return choice
def trade(self, player, merchant):
# choice = 0
time.sleep(1)
print(""" You encountered the merchant!!
""",merchant.name,""" """,merchant.description,"""
""",merchant.gold," gold","""
ITEMS: """,merchant.items,"""
VOS ACTIONS DISPONIBLES:
TRADE (1) !LEAVE! (2)
""")
# while choice != 1 & choice !=2 & choice != 3 :
choice = int(input(" "))
return choice |
from tkinter import *
def change_tex():
my_label.config(text='孙博是小肥猪')
window =Tk()
window.title('fat-pig')
my_label=Label(window,width=50,height=5,text='')
my_label.grid(row=0,column=0)
my_button=Button(window,text='谁是小肥猪',width=10,command=change_tex)
my_button.grid(row=1,column=0)
window.mainloop() |
"github.com/lewisgaul/python-tutorial"
# WEEK 6 CHALLENGE - classes and GUIs
# Work out how the code below works, add in some comments to make it clearer
# where you can.
# First change the code below so that clicking the button stops the timer. If
# there's any style configuration you'd like to do try searching online
# (e.g. search 'tkinter button background colour'), or ask me.
# Use the code below to make a simple game (feel free to use your imagination
# and ask if you need help). Try to include some more widgets.
import tkinter as tk
import time as tm
class TimerGui(tk.Tk):
def __init__(self):
super().__init__()
# Create a Timer instance (defined below).
self.timer = Timer(self)
self.timer.pack()
# Call the method below.
self.place_button('Click me!')
def place_button(self, text):
# When creating a widget (e.g. Button, Label) there are a number of
# arguments you can pass. Here we give the button text and an action
# which is a function which will be run when it is clicked.
button = tk.Button(self, text=text, command=self.button_action)
# Place the button (it is only created above).
button.pack()
def button_action(self):
print("Button pressed")
class Timer(tk.Label):
def __init__(self, parent):
# Create a Label instance from the tk module.
super().__init__(parent)
self.start_time = tm.time()
self.update()
def update(self):
# Below is some string formatting (2 decimal places).
# Configure the text that is displayed on the timer label.
self.config(text="{:.2f}".format(tm.time() - self.start_time))
# Run this method again after 1 millisecond.
self.after(1, self.update)
if __name__ == '__main__':
gui = TimerGui() #create a gui
gui.mainloop() #method inherited from tk.Tk (starts the GUI)
|
class BasicShoppingList:
def __init__(self, L=[]):
self.items = [[item,1] for item in L]
def __str__(self):
result = ''
for i, n in self.items:
result += '{:10s} x {}\n'.format(i, n) #e.g. 'Apples x 3\n'
return result
def add(self, product, quantity=1):
products = [i[0] for i in self.items]
if product in products:
index = products.index(product)
self.items[index][1] += quantity
else:
self.items.append([product, quantity])
# Alternatively, inherit from list and gain methods like 'sort'.
class ShoppingList(list):
def __init__(self, L=[]):
items = [[item,1] for item in L]
super().__init__(items)
def __str__(self):
result = ''
for i, n in self:
result += '{:10s} x {}\n'.format(i, n) #e.g. 'Apples x 3\n'
return result
def add(self, product, quantity=1):
products = [i[0] for i in self]
if product in products:
index = products.index(product)
self[index][1] += quantity
else:
self.append([product, quantity])
bsl = BasicShoppingList(['Pears', 'Apples'])
print(bsl)
bsl.add('Apples', 2)
bsl.add('Sausages', 12)
print(bsl)
#bsl.sort() #Gives error
sl = ShoppingList(['Pears', 'Apples'])
print(sl)
sl.add('Apples', 2)
sl.add('Sausages', 12)
print(sl)
sl.sort()
print(sl)
|
#!/usr/bin/env python
# Useage: argparse --which arguments -do="we" match
import sys
for x in sys.argv:
if x == '--which':
print('--which')
elif x == 'arguments':
print('arguments')
elif x == '-do="we"':
print('-do="we"')
elif x == 'match':
print('match')
else:
print('no matching args found')
print 'arg is ', x
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv) |
age = int(input("age"))
if age > 25:
print("hello") |
command = ""
started = False
stopped = False
while command != "quit":
command = input("> ").lower()
if command == "start":
# check if the car already started
if started:
print("Car has been started")
else:
started = True
print("car started ...")
elif command == "stop":
# check if the car has been stopped
if stopped:
print('car has been stopped')
else:
stopped = True
print("car stopped")
elif command == "help":
# multiline print
print("""
start - to start the car
stop - to stop the car
quit - to quit
""")
elif command == "quit":
break
else:
print("Oops Sorry Check you Command") |
# 8/9/2021 ball class
#practice OOP within python
class Ball:
def __init__(self,color,diameter):
self.color = color
self.diameter = diameter
def roll(self,distance):
self.distance = distance
print("Ball rolled: "+ str(distance) + "! ")
def bounce(self,jumps):
self.jumps = jumps
print("Ball bounced: " + str(jumps) + "! ")
myfavball = Ball('marble blue', 3) #create ball
print(myfavball.color)
print (str(myfavball.diameter))
myfavball.roll(5)
myfavball.bounce(2)
|
## BMI Calculator 2.0
# Instructions
# Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height.
# It should tell them the interpretation of their BMI based on the BMI value.
# - Under 18.5 they are underweight
#- Over 18.5 but below 25 they have a normal weight
# - Over 25 but below 30 they are slightly overweight
# - Over 30 but below 35 they are obese
# - Above 35 they are clinically obese.
# The BMI is calculated by dividing a person's weight (in kg) by the square of their height (in m):
#Example Input
#weight = 85
#height = 1.75
# Example Output
#85 ÷ (1.75 x 1.75) = 27.755102040816325
#Your BMI is 28, you are slightly overweight.
#"Your BMI is 18, you are underweight."
#"Your BMI is 22, you have a normal weight."
#"Your BMI is 28, you are slightly overweight."
#"Your BMI is 33, you are obese."
#"Your BMI is 40, you are clinically obese."
weight = int(input("Enter your weight"))
height = float(input("Enter your your height in m"))
formula = weight/(height**2)
bmi = round(formula)
if(bmi<=18.5):
print(f"Your BMI is {bmi}, you are underweight.")
elif(bmi>18.5 and bmi<=25):
print(f"Your BMI is {bmi}, you have a normal weight.")
elif(bmi>25 and bmi<30):
print(f"Your BMI is {bmi}, you are slightly overweight.")
elif(bmi>30 and bmi<35):
print(f"Your BMI is {bmi}, you are obese.")
else:
print(f"Your BMI is {bmi}, you are clinically obese")
|
## Odd or Even
# Instructions
# Write a program that works out whether if a given number is an odd or even number.
num = int(input("Enter a number"))
if(num%2 == 0):
print("The given num is Even")
else:
print("The given number is Odd") |
print("Prime Number Checker")
import time
def prime_number_checker(number):
b =[]
for i in range(1, number):
a = number % i
if a == 0:
b.append(i)
if len(b) > 2:
print(f"The {number} is not prime")
else:
print(f"The {number} is prime")
a =int(input("Enter a number to check :"))
t1 = time.time()
prime_number_checker(number=a)
t2 = time.time()
tot = t1 - t2
print(tot)
|
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
from turtle import Turtle
class Player(Turtle):
def __init__(self):
super().__init__()
self.shape("turtle")
self.pu()
self.color("black")
self.setheading(90)
self.goto(STARTING_POSITION)
def turtle_move(self):
self.forward(MOVE_DISTANCE)
def player_refresh(self):
self.goto(STARTING_POSITION)
|
from turtle import Turtle,Screen
import random
screen = Screen()
screen.screensize(2000,1500)
my_turtle = Turtle()
my_turtle.shape("arrow")
my_turtle.speed("fastest")
my_turtle.hideturtle()
colours = ["CornflowerBlue", "DarkOrchid", "IndianRed",
"DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGreen"]
for i in range(71):
c = random.choice(colours)
my_turtle.pencolor(c)
my_turtle.circle(100)
my_turtle.left(5)
my_turtle.circle(100)
screen.exitonclick()
|
import random
def partition(li, left, right):
temp = li[left]
while left < right:
while left < right and li[right] >= temp:
right -= 1
li[left] = li[right]
while left < right and li[left] <= temp:
left += 1
li[right] = li[left]
li[left] = temp
return left
def quick_sort(array, left, right):
if left < right:
mid = partition(array, left, right)
print(mid)
# print(array)
quick_sort(array, left, mid-1)
quick_sort(array, mid+1, right)
def quick_sort_no_rec(array):
stack = []
left = 0
right = len(array)-1
stack.append(left)
stack.append(right)
while stack:
j = stack.pop() # right
i = stack.pop() # left
mid = partition(array, i, j)
if mid - 1 > i:
stack.append(i) # left
stack.append(mid-1) # right
if mid + 1 < j:
stack.append(mid+1) # left
stack.append(j) # right
random.seed(66)
arr_li = [i for i in range(10)]
random.shuffle(arr_li)
print(arr_li)
# quick_sort(arr_li, 0, len(arr_li)-1)
quick_sort_no_rec(arr_li)
print(arr_li) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.