text
stringlengths 37
1.41M
|
---|
import networkx as nx
import matplotlib-pyplot as plt
g=nx.Graph()
g.add_node(2)
g.add_node(3)
g.add_edge(2,3)
g.add_edge(3,4)
g.add_edge(4,6)
g.add_edge(4,1)
# print detrails of graph
print(nx.info(g)
# visualize Graph
nx.draw(g)
plt.show()
|
# -*- encoding: utf-8 -*-
"""
@File : 31-计算字符个数.py
@Time : 2020/8/9 9:50
@Author : 李逍遥.Legend
@Email : [email protected]
@Software: PyCharm
@Target :
"""
'''
-----------票价规则----------
轨道交通价格调整为:
6公里(含)内3元;
6公里至12公里(含)4元;
12公里至22公里(含)5元;
22公里至32公里(含)6元;
32公里以上部分,每增加1元可乘坐20公里。
'''
#获取公里数
km = int(input("请输入乘坐公里数:"))
# print(km)
#定义一个初始化票价
vaule = 0
if km <= 0:
print("输入的公里数有误!!!")
elif km <= 6:
vaule = 3
print("单程票价:", vaule)
elif km <= 12:
vaule = 4
print("单程票价:", vaule)
elif km <= 22:
vaule = 5
print("单程票价:", vaule)
elif km <=32:
vaule = 6
print("单程票价:", vaule)
elif km > 32:
a = (km - 33) // 20 + 1#考虑到刚好满20公里的整数倍情况,一次在32处+1,保障刚好满20的整数倍的时候,收费正确
vaule = 6 + a
print("单程票价:", vaule)
'''
-----------折扣规则----------
使用市政交通一卡通刷卡乘坐轨道交通,
每自然月内每张卡支出累计满100元以后的乘次,价格给予8折优惠;
满150元以后的乘次,价格给予5折优惠;
支出累计达到400元以后的乘次,不再享受打折优惠。
'''
"""
假设每个月,小明都需要上20天班,每次上班需要来回1次,即每天需要乘坐2次同样路线的地铁
最终得出这"20"天小明做地铁消费多少钱?(20天 40个来回)
"""
#定义一个变量,保存总金额
total_money = 0
for n in range(40):
if total_money < 100:
total_money += vaule
elif total_money < 150:
total_money += vaule * 0.8
elif total_money < 400:
total_money += vaule * 0.5
else:
total_money += vaule
print("一周坐四十次总共花费:%.2f元" % total_money)
|
# -*- encoding: utf-8 -*-
"""
@File : 16-while循环语句.py
@Time : 2020/8/4 20:48
@Author : 李逍遥.Legend
@Email : [email protected]
@Software: PyCharm
@Target :
"""
import time
a = 0
#while循环语句,当while条件一直符合时,会循环执行
while a < 1:
money = int(input("请投币:"))
if money >= 2:
print("请上车……")
time.sleep(2)
seat = int(input("请输入当前剩余座位数量:"))
if seat == 0:
print("没有座位,请站好!")
else:
print("有座位,请入座!")
else:
print("余额不足,请充值!")
a += 1
print("\n循环结束!")
"""
计算1~100的累计和
"""
num = 1
my_sum = 0
while num <= 100:
my_sum += num
num += 1
print("1~100的累计和为:", my_sum)
"""
计算1~100之间的偶数之和
"""
num = 1
sum = 0
while num <= 100:
if num % 2 == 0:
sum += num
num += 1
else:
print("1~100之间的偶数和为:", sum)
|
counta = 0 #前面的大写字母
countb = 0 #小写字母
countc = 0 #后面的大写字母
if str1[i].isupper():
if countb:
countc += 1
else:
counta += 1
countc = 0
if str1[i].isslower():
if counta != 3:
counta = 0
countb = 0
countc = 0
else:
if countb:
counta = 0
countb = 0
countc = 0
else:
countb = 1
countc = 0
taget = i
if counta == 3 and countc == 3:
print(str1[i],end = ' ')
counta = 3
countb = 0
countc = 0
|
import random
secret = random.randint(1,10)
print("第一个作品")
temp = input("输入你心中想的数字:")
guess = 0
num = 1
while guess != secret and num < 3:
num += 1
if temp.isdigit():
try:
guess = int(temp)
except (ValueError,EOFError,KeyboardInterrupt):
print('输入错误')
temp = input("猜错了请重新输入:")
guess = int(temp)
if guess == secret:
print("哥,对了对了")
print("猜对了也没有奖励啊")
else:
if guess > secret:
print("哥,大了大了")
else:
print("嘿,小了!小了")
else:
temp = input("请重新输入:")
print("游戏结束啦")
|
from datetime import date
from time import sleep
cores = {'limpa':'\033[m',
'azul':'\033[34m',
'amarelo':'\033[33m' }
#ETAPA 1 E 2
def obter_limite():
cargo = str(input('Qual cargo você ocupa na empresa que trabalha? '))
salario = input('Qual é o seu salário atual? R$')
# VERIFICAÇÃO SE SALARIO É FLOAT
while salario.isalpha() == True:
salario = input('Digite seu salário em númeral! Ex: 1000.00.\nPor favor, informe o seu salário atual? R$')
salario = float(salario)
while salario <= 0:
salario = input('Seu salário não pode ser igual ou menor que R$0,00. Por favor, informe o seu salário atual? R$')
while salario.isalpha() == True:
salario = input('Digite seu salário em númeral! Ex: 1000.00.\nPor favor, informe o seu salário atual? R$')
salario = float(salario)
anonasc = int(input('Em que ano você nasceu? '))
# VERIFICAÇÃO SE ANO DE NASCIMENTO É MAIOR QUE 0 E MENOR QUE ANO ATUAL!
while anonasc <= 0 or anonasc > date.today().year:
if anonasc <= 0:
anonasc = int(input('Não aceitamos números abaixo de 0. Em que ano você nasceu? '))
if anonasc > date.today().year:
anonasc = int(input('Não aceitamos viajantes do tempo!. Insira um ano de nascimento válido! Em que ano você nasceu? '))
idade = date.today().year - anonasc
print('-='*30)
print('CARGO: {}{}{}'.format(cores['azul'], cargo, cores['limpa']))
print('SALÁRIO: R${}{:.2f}{}'.format(cores['azul'], salario, cores['limpa']))
print('ANO DE NASCIMENTO: {}{}{} '.format(cores['azul'], anonasc, cores['limpa']))
print('-='*30)
print('Sua idade atual aproximada é {} anos'.format(idade))
gasto_permitido = salario * (idade / 1000) + 100
print('Estamos realizando sua análise de crédito! Aguarde...')
sleep(1.5)
return gasto_permitido, idade
#ETAPA 3
def verificar_produto(valor):
if valor <= limite * 0.6:
print('Liberado!')
elif valor > limite * 0.6 and valor <= limite * 0.9:
print('Liberado ao parcelar em até 2x')
elif valor > limite * 0.9 and valor < limite:
print('Liberado ao parcelar em 3 ou mais vezes')
elif valor >= limite:
print('Bloqueado!')
#DESCONTO ESPECIAL
nome_completo = 'Rodrigo Urbano Silva'
nome_short = 'Rodrigo'
desconto_nome = 1
if len(nome_completo) <= price <= idade or idade <= price <= len(nome_completo):
desconto_nome = len(nome_short) / 100
new_price = price * (1 - desconto_nome )
print('Novo preço com desconto de {:.0f}% será de R${:.2f}'.format(desconto_nome*100, new_price))
else:
new_price = price
print('Seguindo...')
return desconto_nome
######################################################################################################################
print('-=' * 42)
print('\tBem-vindo à Loja do Urahara! Aqui quem fala é o Rodrigo Urbano Silva!')
print('-=' * 42)
print('Primeiramente iremos realizar uma análise de crédito, para isso vamos pedir alguns dados')
limite, idade = obter_limite()
print('Segundo a nossa análise de crédito, O(a) sr(a) poderá gastar ate R${}{:.2f}{} na nossa loja!'.format(cores['azul'], limite, cores['limpa']))
print('-='*30)
nome_completo = 'Rodrigo Urbano Silva'
while True:
valor = 0
n = input('Quantos produtos deseja cadastrar? ')
while n.isnumeric() == False:
n = input('Quantos produtos deseja cadastrar? Somente números ')
n = int(n)
for x in range(n):
produto = str(input('Digite o nome do produto que deseja comprar: '))
price = input('Agora digite o preço do produto: R$')
while price.isalpha() == True:
price = input('Digite o preço do produto usando apenas números. R$')
price = float(price)
valor += price
desconto_esp = verificar_produto(valor)
if len(nome_completo) <= price <= idade or idade <= price <= len(nome_completo):
valor = valor - (price * desconto_esp)
lim_sobra = limite - valor
if lim_sobra > 0:
print('Você ainda tem R${:.2f} para gastar na loja!'.format(lim_sobra))
if lim_sobra == 0:
print('Você atingiu o limite de gasto!')
if lim_sobra <= 0:
print('Infelizmente você estourou o limite de gasto em R${:.2f}'.format(lim_sobra * -1))
print(f'Valor total da compra: R${valor:.2f}')
print('-='*20)
option = str(input('Deseja iniciar uma nova compra do zero? [S/N] ')).upper().strip()[0]
while option not in 'SN':
option = str(input('Escolha entre [S/N] ')).upper().strip()[0]
if option == 'N':
break
else:
print('Limpando seu carrinho...')
sleep(0.5)
print('Pronto! Vamos iniciar a sua nova compra!')
print('-='*20)
print('OBRIGADO E VOLTE SEMPRE!') |
d={1:"r",2:"p",3:"a",4:"r"}
duplicate={}
for key, value in d.items():
if value not in duplicate.values():
duplicate[key]=value
print(duplicate)
|
n=int(input("enter a value:"))
for i in range(n):
print((str(n-i) + "*") * (n-1-i) + str(n-i))
for j in range(2,n+1):
print((str(j) + "*") * (j-1) + str(j))
|
def gretestinteger(List):
for i in range(size-1):
List[i] = max(List[i+1:])
return List
size=int(input("enter the size of the list:"))
List = []
for i in range(size):
List.append(int(input("enter the element number:"+str(i+1)+ "in the list")))
print("the list after replacing is:", gretestinteger(List)) |
f = open("day1.txt", "r")
inputs = map(int, f.readlines())
total = 0
for i in inputs:
module_fuel = 0 # total fuel for the module
added_fuel = (i // 3) - 2 # added fuel for each iteration of the fuel calculation
while added_fuel > 0:
module_fuel += added_fuel
added_fuel = (added_fuel // 3) - 2
total += module_fuel
print(total)
|
'''
This is the Machine Learning Project of Home Price Prediction
it contain 13 labels and 1 feature that decides the predicted output
For users go to the end of the programme and make changes in Using the model
labels and get the predicted price by own .I attached housing.names and
housing.data in files and by analysis i found output of the different models
best is RandomForestRegressor model.
I attached data.csv file that is excel file you can edit the data of that file
and test with the different input data's and get the different output.
'''
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
from joblib import dump, load
housing = pd.read_csv("data.csv")
# def split_train_test(data, test_ratio):
# np.random.seed(42)
# shuffled = np.random.permutation(len(data))
# print(shuffled)
# test_set_size = int(len(data) * test_ratio)
# test_indices = shuffled[:test_set_size]
# train_indices = shuffled[test_set_size:]
# return data.iloc[train_indices], data.iloc[test_indices]
train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
# print(f"Rows in train set: {len(train_set)}\nRows in test set: {len(test_set)}\n")
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing['CHAS']):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
a = strat_test_set['CHAS'].value_counts()
b = strat_train_set['CHAS'].value_counts()
# print(a)
# print(b)
housing = strat_train_set.copy()
# Looking for correlations
corr_matrix = housing.corr()
a=corr_matrix['MEDV'].sort_values(ascending=False)
# print(a)
# Trying out attribute combinations
housing["TAXRM"] = housing['TAX']/housing['RM']
# print(housing.head())
housing = strat_train_set.drop("MEDV", axis=1)
housing_labels = strat_train_set["MEDV"].copy()
# Missing Attributes
housing.dropna(subset=["RM"])
# print(a.shape)
# print(housing.drop("RM", axis=1).shape)
# a=housing.head()
# print(a)
# a =housing['CHAS'].value_counts()
# print(a)
median = housing["RM"].median()
housing["RM"].fillna(median)
imputer = SimpleImputer(strategy="median")
imputer.fit(housing)
X = imputer.transform(housing)
housing_tr = pd.DataFrame(X, columns=housing.columns)
# print(housing_tr.describe())
# Creating a Pipeline
my_pipeline = Pipeline([
('imputer', SimpleImputer(strategy="median")),
# ..... add as many as you want in your pipeline
('std_scaler', StandardScaler()),
])
housing_num_tr = my_pipeline.fit_transform(housing)
# print(housing_num_tr.shape)
# Selecting a desired model for The Home Price Predictor
# model = LinearRegression()
# model = DecisionTreeRegressor()
model = RandomForestRegressor() #This is the best model for this type of problem it gives minimum rms values that can increase it's performance of predictions.
model.fit(housing_num_tr, housing_labels)
some_data = housing.iloc[:5]
some_labels = housing_labels.iloc[:5]
prepared_data = my_pipeline.transform(some_data)
model.predict(prepared_data)
list(some_labels)
# Evaluting the model
housing_predictions = model.predict(housing_num_tr)
mse = mean_squared_error(housing_labels, housing_predictions)
rmse = np.sqrt(mse)
# print(rmse)
# Using better evalution technique-Cross Validation
scores = cross_val_score(model, housing_num_tr, housing_labels, scoring="neg_mean_squared_error", cv=10)
rmse_scores = np.sqrt(-scores)
# print(rmse_scores)
def print_scores(scores):
print("Scores:", scores)
print("Mean: ", scores.mean())
print("Standard deviation: ", scores.std())
# print(print_scores(rmse_scores))
# Saving The model
dump(model, 'Dragon.joblib')
# Testing the model on test data
X_test = strat_test_set.drop("MEDV", axis=1)
Y_test = strat_test_set["MEDV"].copy()
X_test_prepared = my_pipeline.transform(X_test)
final_predictions = model.predict(X_test_prepared)
final_mse = mean_squared_error(Y_test, final_predictions)
final_rmse = np.sqrt(final_mse)
# print(final_predictions, list(Y_test))
# print(final_rmse)
prepared_data[0]
# print(prepared_data[0])
# Using the model
model = load('Dragon.joblib')
features = np.array([[-5.43942006, 4.12628155, -1.6165014, -0.67288841, -1.42262747,
-11.44443979304, -4.31238772, 7.61111401, -26.0016879 , -0.5778192 ,
-0.97491834, 0.41164221, -6.86091034]])
print(model.predict(features))
|
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
permutation = []
self.helper([], nums, permutation)
return permutation
def helper(self, array, remaining, permutation):
if len(remaining) == 0:
permutation.append(array)
return
for i in range(len(remaining)):
self.helper(array + [remaining[i]], remaining[:i] +
remaining[i + 1:], permutation)
s = Solution()
print s.permute([1, 2, 3])
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
master = []
list = []
self.traverse(root, list, master)
return master
def traverse(self, root, list, master):
if not root:
return
list.append(str(root.val))
if root.left == None and root.right == None:
master.append("->".join(list))
return
self.traverse(root.left, list[:], master)
self.traverse(root.right, list[:], master)
from TestObjects import *
b = BinarySearchTree()
s = Solution()
print s.binaryTreePaths(None)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
m = {}
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
self.m = {}
self.traverse(root)
freq = max(self.m.values())
return [e for e in self.m if self.m[e] == freq]
def traverse(self, root):
if not root:
return
self.traverse(root.left)
self.traverse(root.right)
if root.left:
root.val += root.left.val
if root.right:
root.val += root.right.val
print root.val
self.m[root.val] = self.m.get(root.val, 0) + 1
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
# in order traversal, append to List
# get kth item
list = []
list = self.inOrderTraversal(root, list)
return list[k - 1]
def inOrderTraversal(self, root, list):
if root == None:
return
self.inOrderTraversal(root.left, list)
list.append(root.val)
self.inOrderTraversal(root.right, list)
return list
s = Solution()
from TestObjects import BinarySearchTree
b = BinarySearchTree()
print s.kthSmallest(b.root, 2)
|
def insert(root,node):
if not root:
root = node
else:
if node.val > root.val:
if not root.right:
root.right = node
else:
insert(root.right, node)
else:
if not root.left:
root.left = node
else:
insert(root.left, node) |
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
list = set(nums)
result = []
for i in range(1, len(nums) + 1):
if i not in list:
result.append(i)
return result
|
# class Solution(object):
#
# def findDuplicates(self, nums):
# """
# :type nums: List[int]
# :rtype: List[int]
# """
# list = set()
# result = []
# for n in nums:
# if n in list:
# result.append(n)
# else:
# list.add(n)
# return result
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
list = []
for n in nums:
if nums[abs(n) - 1] < 0:
list.append(abs(n))
else:
nums[abs(n) - 1] *= -1
return list
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
list = []
self.inorderTraversal(root, list)
return self.isInOrder(list)
def inorderTraversal(self, root, list):
if root == None:
return
self.inorderTraversal(root.left, list)
list.append(root.val)
self.inorderTraversal(root.right, list)
def isInOrder(self, list):
print list
for i in range(0, len(list) - 1):
if list[i] >= list[i + 1]:
return False
return True
s = Solution()
from TestObjects import *
root = TreeNode(1)
root.left = TreeNode(1)
b = BinarySearchTree()
print s.isValidBST(root)
|
# Test objects used to test code
# I made a few sample preloaded data structures to test the basic
# functionality of some of my solutions
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BinarySearchTree(object):
'''
6
2 8
0 4 7 9
3 5
'''
def __init__(self):
self.root = TreeNode(6)
self.root.left = TreeNode(2)
self.root.left.left = TreeNode(0)
self.root.left.right = TreeNode(4)
self.root.left.right.left = TreeNode(3)
self.root.left.right.right = TreeNode(5)
self.root.right = TreeNode(8)
self.root.right.left = TreeNode(7)
self.root.right.right = TreeNode(9)
class BinaryTree(object):
'''
1
2 3
4 5 6 7
'''
def __init__(self):
self.root = TreeNode(1)
self.root.left = TreeNode(2)
self.root.left.left = TreeNode(4)
self.root.left.right = TreeNode(5)
self.root.right = TreeNode(3)
self.root.right.left = TreeNode(6)
self.root.right.right = TreeNode(7)
class SymetricBinaryTree(object):
'''
1
2 2
3 4 4 3
'''
def __init__(self):
self.root = TreeNode(1)
self.root.left = TreeNode(2)
self.root.left.left = TreeNode(3)
self.root.left.right = TreeNode(4)
self.root.right = TreeNode(2)
self.root.right.left = TreeNode(4)
self.root.right.right = TreeNode(3)
|
# Definition for singly-linked list.
# class ListNode(object):
#
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
return self.helper(head, None)
def helper(self, current, prev):
if current == None:
return prev
next = current.next
current.next = prev
return self.helper(next, current)
|
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
# hashmap for levels
dic = {'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1,
'p': 1, 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h': 2, 'j': 2, 'k': 2, 'l': 2, 'z': 3, 'x': 3, 'c': 3, 'v': 3, 'b': 3, 'n': 3, 'm': 3}
answer = []
for word in words:
lower = word.lower()
val = dic[lower[0]]
answer.append(word)
for l in lower:
if dic[l] != val:
answer = answer[:-1]
break
return answer
|
def removeDupNoExtraArray(dataSet):
data = list(dataSet)
startIndex = 0
lastIndex = len(data) - 1
lenOfData = len(data)
while startIndex <= lastIndex:
tempIndex = startIndex + 1
while tempIndex < lenOfData:
if data[tempIndex] == data[startIndex]:
print "\n======Match found======\nswap:1 ---",data[tempIndex],"-->",data[lastIndex],"\n",data
swapData = data[tempIndex]
data[tempIndex] = data[lastIndex]
data[lastIndex] = swapData
lastIndex -= 1
print "\nswap:2 ---",data[startIndex],"-->",data[lastIndex],"\n",data
swapData = data[startIndex]
data[startIndex] = data[lastIndex]
data[lastIndex] = swapData
lastIndex -= 1
else:
tempIndex += 1
if tempIndex == lenOfData:
print "No match: ", data[startIndex]
startIndex += 1
print "Final output: ", ''.join(data[:lastIndex])
if __name__ == "__main__":
var = raw_input("Enter the input string: ")
removeDupNoExtraArray(var)
|
span = 2
if span == 1:
print('Hello')
elif span == 2:
print('Howdy')
else:
print('Greetings')
def func_with_no_args():
return f'Hello world! {span}'
class someclass:
def __init__(self, a):
self.a = a
def s(self):
print(self.a)
def convert_list_to_sent(self, sen):
list = ''
if len(sen) == 1:
return sen[0]
for i in range(len(sen)):
if i == len(sen) - 1:
list += 'and ' + sen[i]
else:
list += sen[i] + ', '
return list
if __name__ == '__main__':
print(func_with_no_args())
foo = someclass(3)
foo.s()
print([1, 2] * 4)
s = ['asd', 'ds', 'jgf', 'rgr']
print('ds' not in s)
a, *args = s
print(a, args)
tuple2 = (1, 2, 3) # const list
single_el_tuple = (1,)
print(foo.convert_list_to_sent(s))
assert foo.convert_list_to_sent(['ads', 'ad']) == 'ads, and ad'
|
"""Class Dog Description"""
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is now sitting")
def roll_over(self):
print(self.name.title() + " is now rolling over")
class Car:
def __init__(self, make, model, year=2009):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def odometer_reading(self):
print('The odometer is ' + str(self.odometer))
def set_odometer(self, number):
self.odometer=number
def inc_odometer(self, number):
if number > 0:
self.odometer += number
else:
print('Enter a positive value')
|
"""
Calculate Mahalanobis distance using Minimum Covariance Determinant
ref) https://scikit-learn.org/stable/auto_examples/covariance/plot_mahalanobis_distances.html
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.covariance import MinCovDet
n_samples = 125
n_outliers = 25
n_features = 2
# generate data
gen_cov = np.eye(n_features)
gen_cov[0, 0] = 2.
X = np.dot(np.random.randn(n_samples, n_features), gen_cov)
# add some outliers
outliers_cov = np.eye(n_features)
outliers_cov[np.arange(1, n_features), np.arange(1, n_features)] = 8.
X[-n_outliers:] = np.dot(np.random.randn(n_outliers, n_features), outliers_cov)
# fit a Minimum Covariance Determinant (MCD) robust estimator to data
robust_cov = MinCovDet().fit(X)
# #############################################################################
# Display results
fig = plt.figure()
# Show data set
subfig1 = plt.subplot()
inlier_plot = subfig1.scatter(X[:, 0], X[:, 1],
color='black', label='inliers')
outlier_plot = subfig1.scatter(X[:, 0][-n_outliers:], X[:, 1][-n_outliers:],
color='red', label='outliers')
subfig1.set_xlim(subfig1.get_xlim()[0], 11.)
subfig1.set_title("Mahalanobis distances of a contaminated data set:")
# Show contours of the distance functions
xx, yy = np.meshgrid(np.linspace(plt.xlim()[0], plt.xlim()[1], 100),
np.linspace(plt.ylim()[0], plt.ylim()[1], 100))
zz = np.c_[xx.ravel(), yy.ravel()]
mahal_robust_cov = robust_cov.mahalanobis(zz)
mahal_robust_cov = mahal_robust_cov.reshape(xx.shape)
robust_contour = subfig1.contour(xx, yy, np.sqrt(mahal_robust_cov),
cmap=plt.cm.YlOrBr_r, linestyles='dotted')
subfig1.legend([robust_contour.collections[1], inlier_plot, outlier_plot],
['robust dist', 'inliers', 'outliers'],
loc="upper right", borderaxespad=0)
plt.xticks(())
plt.yticks(())
plt.show() |
expected_salary = 0
# Initialize a dictionary with a base salary value.
expected_salaries = {"NY": 70000, "CA": 70000, "FL": 50000, "NC": 50000, "TX": 60000}
# Initialize the user's info as an empty dictionary.
user_profile = True
def calculate_expected_salary_from_user_experience(user_information, user_trade_tools,
user_experience, number_of_education_years, candidate_type_str):
"""
A function for calculating the expected salary based on the user's
state, and their years of experience.
"""
# Get the user's state from the incoming user_information object
state = user_information["State"]
# Set the base salary, based on the user's state
base_salary = expected_salaries[state]
# Initialize a new_expected_salary variable, which is set to the base_salary
new_expected_salary = base_salary
if isinstance(user_information, dict):
print("All Fields have been completed.")
print()
else:
print("This is not a dictionary. It is {}".format(type(user_information)))
print()
# Re-calculate the salary based on the user's experience.
if int(user_experience) == 1:
new_expected_salary = base_salary - 5000
print("Unfortunately with your limited experience we will have to deduct $5k from your base salary.")
elif int(user_experience) == 2:
new_expected_salary = base_salary + 2000
print("With your level of experience, expect a $2k bump in your base salary.")
elif int(user_experience) == 3:
new_expected_salary = base_salary + 5000
print("Exactly what we are looking for! Expect a $5K added to your base salary.")
elif int(user_experience) == 4:
new_expected_salary = base_salary + 10000
print(
"We're giving you an additional $10k increase to your base salary for the many years of experience you "
"have "
"in this field.")
candidate_developer = False
candidate_designer = False
candidate_type_wording_map = {
"developer": "coding languages",
"designer": "design programs"
}
candidate_type_wording = candidate_type_wording_map[candidate_type_str]
if len(user_trade_tools) < 3:
new_expected_salary = new_expected_salary - 7500
print("Learn more " + candidate_type_wording + ": $7.5K was deducted from the expected salary.")
elif len(user_coding_languages) > 3:
new_expected_salary = new_expected_salary + 10000
print("Learning more than 3 " + candidate_type_wording + " added $10K to expected salary.")
else:
new_expected_salary = new_expected_salary + 5000
print("Knowing 3 " + candidate_type_wording + " or less only added $5K to expected salary.")
if int(number_of_education_years) > 3:
new_expected_salary = new_expected_salary + 10000
print("Dedication to learning added $10K to base salary ")
elif int(number_of_education_years) < 3:
new_expected_salary = new_expected_salary - 7500
print("Number for years of education needs improvement: Deduct $7.5K from base salary.")
else:
new_expected_salary = new_expected_salary - 2000
print("Continue learning to increase salary: added $2K to expected salary.")
print("Expect around $" + str(new_expected_salary) + " annually for this position.")
print()
return new_expected_salary
current_salary = 0
def calculate_expected_salary_from_coding_experience(current_salary, user_languages, user_experience, user_trade_tools):
# Re-calculate the salary, based off the user experience, and the number of languages they know.
new_expected_salary = current_salary
if int(user_experience) == 1:
if len(user_languages) < 2:
new_expected_salary = new_expected_salary - 10000
print("Learn more Coding Languages: Deduct $10k from expected salary.")
elif len(user_languages) == 2:
new_expected_salary = new_expected_salary + 5000
else:
new_expected_salary = new_expected_salary + 2500
if int(user_experience) == 2:
if len(user_languages) == 2:
new_expected_salary = new_expected_salary - 5000
elif len(user_languages) == 3:
new_expected_salary = new_expected_salary + 7000
else:
new_expected_salary = new_expected_salary + 4500
if len(user_languages) == 3:
new_expected_salary = new_expected_salary + 7000
print("Great! We can add a minimum of $7k to your annual salary for the amount of Coding Languages you know.")
if int(user_experience) == 3:
if len(user_languages) < 3:
new_expected_salary = new_expected_salary - 5000
elif len(user_coding_languages) == 4:
new_expected_salary = new_expected_salary + 9000
else:
new_expected_salary = new_expected_salary + 6500
if len(user_languages) == 4:
new_expected_salary = new_expected_salary + 9000
print(
"Perfect! You are a model candidate for the position, we can negotiate a $9k bump in you annual salary "
"after "
"for the amount of Coding Languages you know.")
if int(user_experience) == 4:
if len(user_languages) == 4:
new_expected_salary = new_expected_salary + 9000
elif len(user_languages) == 5:
new_expected_salary = new_expected_salary + 11000
else:
new_expected_salary = new_expected_salary + 8500
if len(user_languages) == 5:
new_expected_salary = new_expected_salary + 11000
print(
"With your proficiency with multiple Coding Languages, we can negotiate a $11k bump in your annual salary.")
else:
candidate_designer = True
new_expected_salary = current_salary
if int(user_experience) == 1:
if len(user_trade_tools) < 2:
new_expected_salary = new_expected_salary - 10000
print("Learn more Coding Languages: Deduct $10k from expected salary.")
elif len(user_trade_tools) == 2:
new_expected_salary = new_expected_salary + 5000
else:
new_expected_salary = new_expected_salary + 2500
if int(user_experience) == 2:
if len(user_trade_tools) == 2:
new_expected_salary = new_expected_salary - 5000
elif len(user_trade_tools) == 3:
new_expected_salary = new_expected_salary + 7000
else:
new_expected_salary = new_expected_salary + 4500
if len(user_trade_tools) == 3:
new_expected_salary = new_expected_salary + 7000
print(
"Great! We can add a minimum of $7k to your annual salary for the amount of Coding Languages you know.")
if int(user_experience) == 3:
if len(user_trade_tools) < 3:
new_expected_salary = new_expected_salary - 5000
elif len(user_coding_languages) == 4:
new_expected_salary = new_expected_salary + 9000
else:
new_expected_salary = new_expected_salary + 6500
if len(user_trade_tools) == 4:
new_expected_salary = new_expected_salary + 9000
print(
"Perfect! You are a model candidate for the position, we can negotiate a $9k bump in you annual "
"salary after "
"for the amount of Coding Languages you know. ")
if int(user_experience) == 4:
if len(user_trade_tools) == 4:
new_expected_salary = new_expected_salary + 9000
elif len(user_trade_tools) == 5:
new_expected_salary = new_expected_salary + 11000
else:
new_expected_salary = new_expected_salary + 8500
if len(user_trade_tools) == 5:
new_expected_salary = new_expected_salary + 11000
print(
"With your proficiency with multiple Coding Languages, we can negotiate a $11k bump in your annual "
"salary.")
return new_expected_salary
|
from datetime import datetime
from UserProfile1 import UserProfile, Developer, Designer
print("Welcome candidate! Please enter in your information.")
print()
# Initialize the variables for the items that we will ask for the user to input.
# They will default to False (or it could be None).
# If the variable is not set, then we'll ask them to enter that information.
user_dob_old = False
user_age = False
user_full_name = False
user_state = False
user_country = False
user_number_of_education_years = False
# Initialize expected salary to 0. We'll update this later, based on the user's information.
expected_salary = 0
# Initialize a dictionary with a base salary value.
expected_salaries = {"NY": 70000, "CA": 70000, "FL": 50000, "NC": 50000, "TX": 60000}
# Initialize the user's info as an empty dictionary.
user_profile = True
# Initialize a flag that will determine whether or not to ask for candidate information.
should_ask_for_info = True
def calculate_expected_salary_from_user_experience(user_information, user_trade_tools,
user_experience, number_of_education_years, candidate_type_str):
"""
A function for calculating the expected salary based on the user's
state, and their years of experience.
"""
# Get the user's state from the incoming user_information object
state = user_information["State"]
# Set the base salary, based on the user's state
base_salary = expected_salaries[state]
# Initialize a new_expected_salary variable, which is set to the base_salary
new_expected_salary = base_salary
if isinstance(user_information, dict):
print("All Fields have been completed.")
print()
else:
print("This is not a dictionary. It is {}".format(type(user_information)))
print()
# Re-calculate the salary based on the user's experience.
if int(user_experience) == 1:
new_expected_salary = base_salary - 5000
print("Unfortunately with your limited experience we will have to deduct $5k from your base salary.")
elif int(user_experience) == 2:
new_expected_salary = base_salary + 2000
print("With your level of experience, expect a $2k bump in your base salary.")
elif int(user_experience) == 3:
new_expected_salary = base_salary + 5000
print("Exactly what we are looking for! Expect a $5K added to your base salary.")
elif int(user_experience) == 4:
new_expected_salary = base_salary + 10000
print(
"We're giving you an additional $10k increase to your base salary for the many years of experience you "
"have "
"in this field.")
candidate_developer = False
candidate_designer = False
candidate_type_wording_map = {
"developer": "coding languages",
"designer": "design programs"
}
candidate_type_wording = candidate_type_wording_map[candidate_type_str]
if len(user_trade_tools) < 3:
new_expected_salary = new_expected_salary - 7500
print("Learn more " + candidate_type_wording + ": $7.5K was deducted from the expected salary.")
elif len(user_coding_languages) > 3:
new_expected_salary = new_expected_salary + 10000
print("Learning more than 3 " + candidate_type_wording + " added $10K to expected salary.")
else:
new_expected_salary = new_expected_salary + 5000
print("Knowing 3 " + candidate_type_wording + " or less only added $5K to expected salary.")
if int(number_of_education_years) > 3:
new_expected_salary = new_expected_salary + 10000
print("Dedication to learning added $10K to base salary ")
elif int(number_of_education_years) < 3:
new_expected_salary = new_expected_salary - 7500
print("Number for years of education needs improvement: Deduct $7.5K from base salary.")
else:
new_expected_salary = new_expected_salary - 2000
print("Continue learning to increase salary: added $2K to expected salary.")
print("Expect around $" + str(new_expected_salary) + " annually for this position.")
print()
return new_expected_salary
current_salary = 0
def calculate_expected_salary_from_coding_experience(current_salary, user_languages, user_experience, user_trade_tools):
# Re-calculate the salary, based off the user experience, and the number of languages they know.
new_expected_salary = current_salary
if int(user_experience) == 1:
if len(user_languages) < 2:
new_expected_salary = new_expected_salary - 10000
print("Learn more Coding Languages: Deduct $10k from expected salary.")
elif len(user_languages) == 2:
new_expected_salary = new_expected_salary + 5000
else:
new_expected_salary = new_expected_salary + 2500
if int(user_experience) == 2:
if len(user_languages) == 2:
new_expected_salary = new_expected_salary - 5000
elif len(user_languages) == 3:
new_expected_salary = new_expected_salary + 7000
else:
new_expected_salary = new_expected_salary + 4500
if len(user_languages) == 3:
new_expected_salary = new_expected_salary + 7000
print("Great! We can add a minimum of $7k to your annual salary for the amount of Coding Languages you know.")
if int(user_experience) == 3:
if len(user_languages) < 3:
new_expected_salary = new_expected_salary - 5000
elif len(user_coding_languages) == 4:
new_expected_salary = new_expected_salary + 9000
else:
new_expected_salary = new_expected_salary + 6500
if len(user_languages) == 4:
new_expected_salary = new_expected_salary + 9000
print(
"Perfect! You are a model candidate for the position, we can negotiate a $9k bump in you annual salary "
"after "
"for the amount of Coding Languages you know.")
if int(user_experience) == 4:
if len(user_languages) == 4:
new_expected_salary = new_expected_salary + 9000
elif len(user_languages) == 5:
new_expected_salary = new_expected_salary + 11000
else:
new_expected_salary = new_expected_salary + 8500
if len(user_languages) == 5:
new_expected_salary = new_expected_salary + 11000
print(
"With your proficiency with multiple Coding Languages, we can negotiate a $11k bump in your annual salary.")
else:
candidate_designer = True
new_expected_salary = current_salary
if int(user_experience) == 1:
if len(user_trade_tools) < 2:
new_expected_salary = new_expected_salary - 10000
print("Learn more Coding Languages: Deduct $10k from expected salary.")
elif len(user_trade_tools) == 2:
new_expected_salary = new_expected_salary + 5000
else:
new_expected_salary = new_expected_salary + 2500
if int(user_experience) == 2:
if len(user_trade_tools) == 2:
new_expected_salary = new_expected_salary - 5000
elif len(user_trade_tools) == 3:
new_expected_salary = new_expected_salary + 7000
else:
new_expected_salary = new_expected_salary + 4500
if len(user_trade_tools) == 3:
new_expected_salary = new_expected_salary + 7000
print(
"Great! We can add a minimum of $7k to your annual salary for the amount of Coding Languages you know.")
if int(user_experience) == 3:
if len(user_trade_tools) < 3:
new_expected_salary = new_expected_salary - 5000
elif len(user_coding_languages) == 4:
new_expected_salary = new_expected_salary + 9000
else:
new_expected_salary = new_expected_salary + 6500
if len(user_trade_tools) == 4:
new_expected_salary = new_expected_salary + 9000
print(
"Perfect! You are a model candidate for the position, we can negotiate a $9k bump in you annual "
"salary after "
"for the amount of Coding Languages you know. ")
if int(user_experience) == 4:
if len(user_trade_tools) == 4:
new_expected_salary = new_expected_salary + 9000
elif len(user_trade_tools) == 5:
new_expected_salary = new_expected_salary + 11000
else:
new_expected_salary = new_expected_salary + 8500
if len(user_trade_tools) == 5:
new_expected_salary = new_expected_salary + 11000
print(
"With your proficiency with multiple Coding Languages, we can negotiate a $11k bump in your annual "
"salary.")
return new_expected_salary
# Now, ask for a user's information as long as should_ask_for_info is True.
candidate_developer = False
candidate_designer = False
while should_ask_for_info:
try:
# Ask "Are you a Designer or Developer?"
candidate_type = input("What would best describe your coding background? \n Type [1]"
"For Software Developer \n "
"Type [2]For Web Designer ")
print()
candidate_type_map = {
"1": "developer",
"2": "designer"
}
candidate_type_str = candidate_type_map[candidate_type]
if int(candidate_type) == 1:
candidate_developer = True
candidate_designer = False
elif int(candidate_type) == 2:
candidate_developer = False
candidate_designer = True
else:
raise ValueError
# Ask the user for various forms for information.
if not user_full_name:
user_full_name = input("Enter Full Name: ")
if not user_dob_old:
user_dob_old = input("Enter Date of Birth (MM/DD/YYYY): ")
# Convert the date of birth into a different format.
dob_timestamp = datetime.strptime(user_dob_old, '%m/%d/%Y')
user_dob = dob_timestamp.strftime('%B %d, %Y')
if not user_age:
user_age = int(input("Enter Current Age: "))
valid_state = list(expected_salaries.keys())
for state in valid_state:
print(state)
if not user_state:
user_state = input('Enter State (Please enter the 2 letter abbreviation:) ')
if user_state not in valid_state:
raise KeyError()
if not user_country:
user_country = input("Enter Country: ")
print()
if not user_number_of_education_years:
skills = "Software Development"
if candidate_designer:
skills = "Web Design"
user_number_of_education_years = int(
input("Enter the number of years you've been learning " + skills + "? ")
)
is_active = True
user_profile = UserProfile(user_dob, user_age, user_full_name, user_country, user_state,
user_number_of_education_years)
user_trade_tools = []
# Create a user profile from the info provided, using the UserProfile class.
if candidate_developer:
user_design_tools = []
user_coding_languages = str(
input("Which Coding Languages do you know? (Separate each language by a comma)\n"))
print()
user_trade_tools = user_coding_languages.split(",")
user_profile = Developer(user_dob, user_age, user_full_name, user_country, user_state,
user_number_of_education_years, user_trade_tools)
else:
user_coding_languages = []
user_design_tools = str(input("What Software Design Tools do you use? (Separate each tool by a comma)"))
print()
user_profile = Designer(user_dob, user_age, user_full_name, user_country, user_state,
user_number_of_education_years, user_trade_tools)
user_trade_tools = user_design_tools.split(",")
if user_design_tools == '':
raise ValueError
user_password = user_profile.get_password()
print(user_password)
new_password = input("Please enter a new password ")
user_profile.set_password(new_password)
print("Your new password is", new_password)
user_password = user_profile.get_password()
print()
user_email = user_profile.get_email()
print(user_email)
user_email = input("Please enter valid Email Address ")
user_profile.set_email(user_email)
print("Verify Email Address", user_email)
user_email = user_profile.get_email()
user_Id = user_profile.create_user_id()
print("Your Account Id is", user_Id)
print()
user_info = {
"Date of Birth": user_profile.user_dob,
"Current Age": user_profile.user_age,
"Full Name": user_profile.user_full_name,
"Country of Residence": user_profile.user_country,
"State": user_profile.user_state,
"Educational Years": user_profile.user_number_of_education_years
}
# Ask the user for the number of years of experience they have.
users_experience = input(
"How many years of experience do you have?\n[1] Less than 1 year experience.\n"
"[2] 1-3 years of experience.\n[3] 3-8 years of experience.\n[4]"
"8+ years of experience.\n")
users_experience = int(users_experience)
print()
# Calculate the expected salary based on the user's state and their experience.
expected_salary = calculate_expected_salary_from_user_experience(user_info, user_trade_tools,
users_experience,
user_number_of_education_years,
candidate_type_str)
# Re-calculate the expected salary based on the user's coding experience and languages. expected_salary =
# calculate_expected_salary_from_coding_experience(expected_salary, user_coding_languages, users_experience,
# candidate_developer, candidate_designer)
# Ask the user if they would like to add another candidate.
another_candidate = input("Would you like to enter another another candidate? (Y/N) \n")
should_ask_for_info = another_candidate.upper() == "Y"
print()
# Reset the variables so that we can ask questions again.
if should_ask_for_info:
user_dob_old = False
user_age = False
user_full_name = False
user_state = False
user_country = False
user_number_of_education_years = False
else:
# Display the user's info and expected salary, if we are not going to ask for another candidate.
# print("Expect $" + str(expected_salary) + " for your level of experience.")
# print()
print(user_info)
print()
for item in expected_salaries:
if user_state == item in expected_salaries:
print("You're base expected salary for just living in " + str(
user_state) + " could have been $" + str(
expected_salaries[item]) + ".")
print()
print("Thank you for your input, we will contact you soon.")
except ValueError:
print("Please answer all questions.")
except KeyError:
user_state = False
print("Please enter valid State.") |
import os
import re
def walk_through_files(path, file_extensions):
"""
Generator function: searches the directory recursively to obtain all files that match the file_extensions
Args:
path: input path to search in
file_extensions: Tuple of extensions to filter on
"""
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if filename.endswith(file_extensions):
yield os.path.join(dirpath, filename).replace("\\","/") # ensure right backslashes (Windows)!
def generate_list(directory, file_extensions=('.pdf', '.tiff')):
"""
Populates a list of compatible files and returns it
Args:
directory: root directory of the documents
file_extensions: Tuple of extensions to filter on
Returns:
A list of document paths
"""
documentsList = []
for fname in walk_through_files(directory, file_extensions):
documentsList.append(fname)
return documentsList
def clean_text(text, exportType):
"""
Basic string cleaning function, removes non printable charactes as well as tabs and newlines
Args:
text: the text input
Returns:
The cleaned text
"""
if exportType=='csv':
text = re.sub('[^Α-Ωa-zΈΌΊΏΉΎα-ω0-9A-Zάέόίώήύϊϋ\ \.,`#%&@:$·\-\*^/;()!\'/\"]', "", text)
else:
text = re.sub('[^Α-Ωa-zΈΌΊΏΉΎα-ω0-9A-Zάέόίώήύϊϋ\ \.\n,`#%&@:$·\-\*^/;()!\'/\"]', "", text)
text = re.sub("(\ {2,})", " ", text)
return text |
import cv2 as cv
import numpy as np
img = cv.imread('Photos/cats.jpg')
cv.imshow("Cats",img)
blank = np.zeros(img.shape,dtype='uint8')
cv.imshow("blank",blank)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray',gray)
# blur = cv.GaussianBlur(gray,(5,5),cv.BORDER_DEFAULT)
# cv.imshow('Blur',blur)
# canny = cv.Canny(blur,125,175)
# cv.imshow("Canny",canny)
ret, thresh = cv.threshold(gray,125,255,cv.THRESH_BINARY)
cv.imshow("Thresh",thresh)
# Thresholding just binarizes images
contours, hireachies = cv.findContours(thresh, cv.RETR_LIST,cv.CHAIN_APPROX_SIMPLE)
# cv.fincontours returns a list of all co ordinates of the contours and Hireachy - which represents the hireachy of the contour
print(len(contours))
cv.drawContours(blank,contours,-1,(0,0,255),2)
cv.imshow("Contours",blank)
cv.waitKey(0) |
# print("Welcome to the rollercoaster!!")
# height = int(input("What is your height? "))
# bill = 0
# if height >= 130:
# print("You can ride he rollercoaster!")
# age = int(input("What is your age? "))
# if age < 12:
# bill = 5
# print("Please pay $5")
# elif age <= 18:
# bill = 12
# print("Please pay $12")
# elif age>=45 and age <=55:
# print("Everything is going to be ok have a ride with us!")
# else:
# bill =15
# print("Please pay $15")
# wants_photo=input("Do you want a photo taken? Y or N. ")
# if wants_photo == 'Y':
# bill+=3 #same as bill = bill + 3
# print(f"Your finall bill is ${bill}")
# else:
# print("Sorry, height not allowed!")
# BMI Calculator 2.0
# height = float(input("enter your height in m: "))
# weight = float(input("enter your weight in kg: "))
# bmi = int(round((weight/height**2), 0))
# if bmi < 18.5:
# print(f"Your BMI is {bmi}, you are underweight.")
# elif bmi < 25:
# print(f"Your BMI is {bmi}, you have a normal weight.")
# elif bmi < 30:
# print(f"Your BMI is {bmi}, you are slightly overweight.")
# elif bmi < 35:
# print(f"Your BMI is {bmi}, you are obese.")
# else:
# print(f"Your BMI is {bmi}, you are clinically obese.")
# Leap year Calculator
# year = int(input("Which year do you want to check? "))
# if year % 4 == 0:
# if year % 100 == 0:
# if year % 400 == 0:
# print("Leap year.")
# else:
# print("Not Leap Year.")
# else :
# print("Leap Year")
# else:
# print("Not Leap Year.")
# Pizza Order
# CODE 1
# small_pizza = 15
# medium_pizza = 20
# large_pizza = 25
# small_pepperoni = 2
# large_med_pepperoni = 3
# ex_cheese = 1
# print("Welcome to Python Pizza !!")
# size = input(
# "What size of pizza would you like? L for large M for medium S for small. ")
# pep = input("Do you want pepperoni? Y or N. ")
# cheese = input("Do you want extra cheese? Y or N. ")
# if size == 'L':
# if pep == 'Y' and cheese == 'Y':
# large_pizza = large_pizza+large_med_pepperoni+ex_cheese
# print(f"Your final bill is: ${large_pizza}.")
# elif cheese == 'Y':
# large_pizza = large_pizza+ex_cheese
# print(f"Your final bill is: ${large_pizza}.")
# elif pep == 'Y':
# large_pizza = large_pizza+large_med_pepperoni
# print(f"Your final bill is: ${large_pizza}.")
# else:
# print(f"Your final bill is: ${large_pizza}.")
# if size == 'M':
# if pep == 'Y' and cheese == 'Y':
# medium_pizza = medium_pizza+large_med_pepperoni+ex_cheese
# print(f"Your final bill is: ${medium_pizza}.")
# elif cheese == 'Y':
# medium_pizza = medium_pizza+ex_cheese
# print(f"Your final bill is: ${medium_pizza}.")
# elif pep == 'Y':
# medium_pizza = medium_pizza+large_med_pepperoni
# print(f"Your final bill is: ${medium_pizza}.")
# else:
# print(f"Your final bill is: ${medium_pizza}.")
# elif size == 'S':
# if pep == 'Y' and cheese == 'Y':
# small_pizza = small_pizza+small_pepperoni+ex_cheese
# print(f"Your final bill is: ${small_pizza}.")
# elif cheese == 'Y':
# small_pizza = small_pizza+ex_cheese
# print(f"Your final bill is: ${small_pizza}.")
# elif pep == 'Y':
# small_pizza = small_pizza+small_pepperoni
# print(f"Your final bill is: ${small_pizza}.")
# else:
# print(f"Your final bill is: ${small_pizza}.")
# CODE 2
# print("Welcome to Python Pizza Deliveries!")
# size = input("What size pizza do you want? S, M, or L ")
# add_pepperoni = input("Do you want pepperoni? Y or N ")
# extra_cheese = input("Do you want extra cheese? Y or N ")
# bill=0
# if size == 'S':
# bill+=15
# elif size == 'M':
# bill+=20
# elif size == 'L':
# bill+=25
# if add_pepperoni== 'Y':
# if size == 'S':
# bill+=2
# else:
# bill+=3
# if extra_cheese == 'Y':
# bill+=1
# print(f"Your final bill is ${bill}")
# # LOVE CALCULATOR
# print("Welcome to the Love Calculator!")
# name1 = input("What is your name? \n")
# name2 = input("What is their name? \n")
# combined_names=name1+name2
# combined_lower_case=combined_names.lower()
# t=combined_lower_case.count('t')
# r=combined_lower_case.count('r')
# u=combined_lower_case.count('u')
# e=combined_lower_case.count('e')
# l=combined_lower_case.count('l')
# o=combined_lower_case.count('o')
# v=combined_lower_case.count('v')
# e=combined_lower_case.count('e')
# col1=t+r+u+e
# col2=l+o+v+e
# score= int(str(col1)+str(col2))
# print(score)
# if score < 10 or score > 90:
# print(f"Your score is {score}, you go together like coke and mentos.")
# elif score > 40 and score < 50 :
# print(f"Your score is {score}, you are alright together.")
# else:
# print(f"Your score is {score}.")
# TREASURE ISLAND GAME
print('''
+---------------------------+
+-| TREASURE ISLAND |-+
| | w e s | |
| +-----------------------+ |
\__\ /__/
''')
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
move_init = input(
"You are at a cross road. Where do you want to go. Type 'left' or 'right'. ").lower()
if move_init == 'left':
# Game Continues...
ship_init = input(
"You arrive at a dock and the next ship arrives in 3 hours. Type 'swim' or 'wait'. ").lower()
if ship_init == 'wait':
# Game Continues...
print("The ship docks at the next island's dock and you find an old man who gives you directions to where a castle with treasure is.")
door_init = input(
"The castle has three coloured doors. Choose a door to enter and get the treasure. Type 'red', 'yellow' or 'blue'.").lower()
if door_init == 'yellow':
# Game Continues...
print("You Win!! The treasure is all yours.")
elif door_init == 'blue':
# Game Ends...
print("You have been eaten by beasts!Oops..Game Over : ( ")
elif door_init == 'red':
# Game Ends...
print("You have been burnt by fire!Oops..Game Over : ( ")
else:
# Game Ends...
print("Game Over!!")
else:
# Game Ends...
print("You have been attacked by trout. Game Over!!")
else:
# Game Ends...
print("You fell into a hole. Game Over!!!")
|
"""Code for combining columns to create new features. Giving velocities and accelerations are explained below."""
import datetime
import dateutil
from typing import Callable, Any
import numpy as np
import pandas as pd
from tqdm import tqdm
# Define constants used in the code below
RANDOM_SEED = 888
ID_COUNT = 1000
NULL_PCT = 0.15
MAX_GIFTS_PER_YEAR = 6
YEARS = [year for year in range(1990, 2022)]
CURRENT_FISCAL_YEAR = (
datetime.datetime.now() + dateutil.relativedelta.relativedelta(months=6)
).year
# Set random seed for reproducible results
np.random.seed(RANDOM_SEED)
# Create dataset
df = pd.DataFrame()
for donor_id in range(ID_COUNT):
start_year = np.random.choice(YEARS)
donor_years = list(range(start_year, 2022))
years_given = np.ma.array(
donor_years, mask=(np.array([np.random.random() for _ in donor_years]) < NULL_PCT)
).compressed()
years_given = np.repeat(
years_given, np.random.randint(1, MAX_GIFTS_PER_YEAR, size=len(years_given))
)
gifts = np.round(np.random.exponential(scale=250, size=len(years_given)), 2)
temp_df = pd.DataFrame(
data={"id": donor_id + 1000, "fiscal_year": years_given, "amount_given": gifts}
)
df = pd.concat([df, temp_df], ignore_index=True)
# Aggregate data
df = (
df.groupby(["id", "fiscal_year"])
.agg(
amount_given=("amount_given", "sum"),
gift_count=("amount_given", "count"),
)
.reset_index()
)
# Functions to calculate velocities and accelerations for all fiscal years
def calculate_simple_velocity(
df: pd.DataFrame,
fiscal_year: str = "fiscal_year",
id_column: str = "id",
amount: str = "amount_given",
current_year: int = CURRENT_FISCAL_YEAR,
window: int = 5,
velocity: str = "simple_velocity",
) -> pd.Series:
"""Calculate giving velocity for a specified fiscal year.
Giving velocity reflects the proportion of a donor's giving that
occurred with a specified window (5 years by default). Peter Wylie
wrote about it here: http://bit.ly/2nFqmZU.
Arguments:
df {pd.DataFrame} -- A DataFrame containing grouped and
aggregated giving data.
Keyword Arguments:
fiscal_year {str} -- Name of the column containing the
fiscal year (default: {'fiscal_year'})
id_column {str} -- Name of the column containing the
donor's ID (default: {'id'})
amount {str} -- Name of the column containing the amount
given (default: {'amount_given'})
current_year {int} -- The current
fiscal year (default: {CURRENT_FISCAL_YEAR})
window {int} -- The number of years in the numerator of
the calculation (default: {5})
velocity {str} -- Name of the column containing the simple
velocity (default: {'simple_velocity'})
Returns:
pd.Series -- MultiIndexed Series containing the simple velocity
"""
recent_giving_df = (
df[(df[fiscal_year] >= (current_year - window)) & (df[fiscal_year] <= current_year)]
.groupby(id_column)
.agg(recent_giving=(amount, "sum"))
)
total_giving_df = (
df[(df[fiscal_year] <= current_year)].groupby(id_column).agg(total_giving=(amount, "sum"))
)
velocity_df = recent_giving_df.join(total_giving_df)
velocity_df[velocity] = velocity_df["recent_giving"] / velocity_df["total_giving"]
velocity_df[fiscal_year] = current_year
velocity_df = velocity_df.reset_index().set_index([id_column, fiscal_year])[velocity]
return velocity_df
def calculate_rolling_velocity(
df: pd.DataFrame,
fiscal_year: str = "fiscal_year",
id_column: str = "id",
amount: str = "amount_given",
current_year: int = CURRENT_FISCAL_YEAR,
window: int = 3,
velocity: str = "rolling_velocity",
) -> pd.Series:
"""Calculate rolling giving velocity for a specified fiscal year.
Rolling giving velocity reflects the escalation or de-escalation
of a donor's giving in a specified window (3 years by default).
Blackbaud includes this score in ResearchPoint, though their
knowledgebase does not go into great detail. See the link here:
https://www.kb.blackbaud.com/articles/Article/57194.
Arguments:
df {pd.DataFrame} -- A DataFrame containing grouped and
aggregated giving data.
Keyword Arguments:
fiscal_year {str} -- Name of the column containing the
fiscal year (default: {FISCAL_YEAR})
id_column {str} -- Name of the column containing the
donor's ID (default: {ACCOUNT_ID})
amount {str} -- Name of the column containing the amount
given (default: {AMOUNT})
current_year {int} -- The current
fiscal year (default: {CURRENT_FISCAL_YEAR})
window {int} -- The number of years in the numerator of
the calculation (default: {3})
velocity {str} -- Name of the column containing the rolling
velocity (default: {'rolling_velocity'})
Returns:
pd.Series -- MultiIndexed Series containing the rolling velocity
"""
rolling_mean_df = (
df[(df[fiscal_year] >= (current_year - window)) & (df[fiscal_year] < current_year)]
.groupby(id_column)
.agg(rolling_mean=(amount, "mean"))
)
prev_fy_giving_df = (
df[df[fiscal_year] == (current_year - 1)]
.groupby(id_column)
.agg(prev_fy_giving=(amount, "sum"))
)
rolling_velocity_df = prev_fy_giving_df.join(rolling_mean_df, on=id_column)
rolling_velocity_df[velocity] = (
rolling_velocity_df["prev_fy_giving"] / rolling_velocity_df["rolling_mean"]
)
rolling_velocity_df[fiscal_year] = current_year
rolling_velocity_df = rolling_velocity_df.reset_index().set_index([id_column, fiscal_year])[
velocity
]
rolling_velocity_df = rolling_velocity_df.fillna(0)
return rolling_velocity_df
def calculate_acceleration(
df: pd.DataFrame, id_column: str, velocity_column: str, acceleration_column: str
) -> pd.Series:
"""Calculate the difference between velocity calculations for each donor.
Defined as velocity(year) - velocity(previous year) for any given year.
Though this is not a true derivative of velocity, it comes close:
[change in velocity(time)] / [change in time] as time approaches the
smallest possible value. For this dataset, the smallest value of time
is one year.
Arguments:
df {pd.DataFrame} -- A DataFrame that contains, at a minimum, an
ID column and a velocity column.
id_column {str} -- Name of the ID column.
velocity_column {str} -- Name of the velocity column.
acceleration_column {str} -- Name of the resulting acceleration column.
Returns:
pd.Series -- A Series of acceleration for a given velocity column.
"""
acceleration = pd.DataFrame(df.groupby(id_column)[velocity_column].diff())
acceleration = acceleration.fillna(0)
acceleration.columns = [acceleration_column]
return acceleration
def fill_missing_fiscal_years(
df: pd.DataFrame,
id_column: str = "id",
fiscal_year: str = "fiscal_year",
amount: str = "amount_given",
) -> pd.DataFrame:
"""Add fiscal years in which donors did not give to the DataFrame.
Several calculations for churn and recovery modeling require
donors to have data points for every fiscal year after their
first gift. This code does that, and fills the newly-created
data points with a value of 0.
Arguments:
df {pd.DataFrame} -- A DataFrame containing grouped and
aggregated giving data.
Keyword Arguments:
id_column {str} -- Name of the column containing the donor's ID (default: {'id'})
fiscal_year {str} -- Name of the column containing the fiscal year (default: {'fiscal_year'})
amount {str} -- Name of the column containing the amount given (default: {'amount_given'})
Returns:
pd.DataFrame -- A DataFrame with missing fiscal years added
"""
temp_df = df.set_index([id_column, fiscal_year]).copy()
temp_df = temp_df.unstack(level=[fiscal_year], fill_value=0).stack(
level=[fiscal_year], dropna=False
)
temp_df = temp_df.reset_index()
first_gift_year_df = df.groupby(id_column).agg(first_gift_year=(fiscal_year, "min"))
temp_df = temp_df.join(first_gift_year_df, on=id_column)
temp_df = temp_df[temp_df[fiscal_year] >= temp_df["first_gift_year"]]
temp_df = temp_df.drop("first_gift_year", axis=1)
return temp_df
def apply_to_all_years(
df: pd.DataFrame,
func_name: Callable,
start_year: int,
end_year: int = CURRENT_FISCAL_YEAR,
fillna_value: Any = 0,
*args,
**kwargs,
) -> pd.DataFrame:
"""Apply calculations for a single fiscal year to multiple years.
This function makes it easy to apply velocity calculations
to every fiscal year in a dataset.
Arguments:
df {pd.DataFrame} -- A DataFrame used by the specified callable
func_name {Callable} -- Function or other callable that makes
a calculation for a single year
start_year {int} -- The first fiscal year to apply the callable to
Keyword Arguments:
end_year {int} -- The last fiscal year to apply the callable to
(default: {CURRENT_FISCAL_YEAR})
fillna_value {Any} -- The desired value for any missing data
(default: {0})
Returns:
pd.DataFrame -- A MultiIndexed DataFrame containing the passed
calculation applied to all specified years
"""
df_to_join = pd.DataFrame()
to_iterate = tqdm(list(range(start_year, end_year + 1)))
column_name = None
for year in to_iterate:
to_iterate.set_description(f"Applying {func_name.__name__} to {year}")
temp_df = func_name(df, current_year=year, *args, **kwargs)
if column_name is None:
column_name = temp_df.name
df_to_join = pd.concat([df_to_join, temp_df])
# Create a MultiIndex so returned DataFrame can be joined on `id_column` and `fiscal_year`
df_to_join.index = pd.MultiIndex.from_tuples(df_to_join.index)
df_to_join.columns = [column_name]
df_to_join = df_to_join.fillna(fillna_value)
return df_to_join
def add_velocities(df):
result = df.copy()
for func in [calculate_simple_velocity, calculate_rolling_velocity]:
temp_df = apply_to_all_years(result, func, result["fiscal_year"].min())
result = result.join(temp_df, on=["id", "fiscal_year"])
result = result.fillna(0)
return result
def add_accelerations(df):
result = df.copy()
velocity_dict = {
"simple_velocity": "simple_acceleration",
"rolling_velocity": "rolling_acceleration",
}
for velocity, acceleration in velocity_dict.items():
result[acceleration] = calculate_acceleration(result, "id", velocity, acceleration)
return result
# Add combined columns to the dataset
df = fill_missing_fiscal_years(df)
df = add_velocities(df)
df = add_accelerations(df)
df.head(20)
|
string = raw_input("Input here:")
txt=string.split()
result=[]
for words in txt:
if len(words) < 5:
continue
result.append(words)
print ','.join(result),"has characters more than five letters"
|
def cipher(
message: str,
key: list[int],
/,
):
"""
Encrypts message using row transposition cipher using supplied key.
"""
rows = len(message)//len(key) + (1 if len(message) % len(key) else 0)
output = []
for row in range(rows):
output.append(['']*len(key))
for i, key_value in enumerate(key):
output[row][i] = message[len(key)*row + key_value] if len(key)*row + key_value < len(message) else '\ufffd'
output[row] = ''.join(output[row])
return ''.join(output)
def decipher(
ciphertext: str,
key: list[int],
/,
):
"""
Decrypts row transposition-encrypted ciphertext using supplied key.
"""
if len(ciphertext) % len(key):
raise ValueError("Ciphertext length must be multiple of key length!")
rows = len(ciphertext) // len(key)
output = []
for row in range(rows):
output.append(['']*len(key))
for i, key_value in enumerate(key):
output[row][key_value] = ciphertext[len(key)*row + i]
output[row] = ''.join(output[row])
output = ''.join(output)
if (padding_index := output.find('\ufffd')) != -1:
return output[:padding_index]
return output
|
#!/usr/bin/env python3
"""
This script parses a file with the following format ID date-time string1 string2 string3
"""
__author__ = "Cristian Garcia"
__version__ = "0.1.0"
__license__ = "MIT"
import argparse
import sys
import re
regex = r"^([0-9]+)\s+([0-9]{4}\-[0-1][1-9]-[0-3][0-9]-[0-2][0-9]:[0-6][0-9]:[0-6][0-9])\s+(\"[^\"]*\"|\w+)\s+(\"[^\"]*\"|\w+)\s+(\"[\w]*\"|\w+)$"
def main(fileToParse):
total_lines = 0
ok_lines = list()
for line in open(fileToParse):
reg = re.search(regex, line, re.MULTILINE)
if reg:
ok_lines.append(reg.groups())
total_lines += 1
else:
total_lines += 1
print(f"The file contains {total_lines} lines")
lines = input("Give me a comma separated list of ids: ")
output_list=list()
for ok in ok_lines:
for id in lines.split(','):
if id == ok[0]:
output_list.append(ok)
for item in sorted(output_list):
print (item[0],item[3])
if __name__ == "__main__":
main(sys.argv[1])
|
myDict = {"name": "Anand", "age": "41", "countryOfBirth": "India", "favoriteLanguage": "Python"}
def print_dictionary(x):
print "My name is " + x["name"]
print "My age is " + x["age"]
print "I was born in " + x["countryOfBirth"]
print "My favorite language is " + x["favoriteLanguage"]
for item in x.keys():
print x[item]
for item in x.values():
print item
print_dictionary(myDict)
|
from Product import Product
class store(object):
def __init__(self, products, location, owner):
self.products = products
self.location = location
self.owner = owner
def add_product(self, product):
self.products.append(product)
return self
def remove_product(self, productName):
i = 0
found = False
for product in self.products:
if product.item_name == productName:
found = True
break
i += 1
if found == True:
del self.products[i]
return self
def inventory(self):
for product in self.products:
print product.item_name
print product.price
print " "
p1 = Product(25, "Bluetooth mouse", 50, "Logitech")
p2 = Product(10, "Mousepad", 20, "Microsoft")
p3 = Product(15, "Trackpad", 30, "Zen Design")
s = store([p1, p2], "San Jose", "Shak")
s.add_product(p3)
s.inventory()
s.remove_product("Mousepad")
print "===================="
s.inventory()
|
from random import randrange
class Board:
"""
The first two ranks of the board at start of a game of Fischer Random Chess.
"""
def __init__(self):
def set_piece(max_skip_spaces, character):
"""
Put a piece onto the board.
:param max_skip_spaces: The maximum number of spaces the piece could skip from left to right in placement.
:param character: The character used to represent the piece.
"""
skip_spaces = randrange(0, max_skip_spaces + 1)
for i in range(0, 8):
if self.random_rank[i] == "":
skip_spaces -= 1
if skip_spaces <= 0:
self.random_rank[i] = character
break
# Random rank
self.random_rank = [""]*8
self.random_rank[randrange(0, 7, 2)] = "♗" # Bishop 1
self.random_rank[randrange(1, 8, 2)] = "♗" # Bishop 2
set_piece(6, "♕") # Queen
set_piece(4, "♘") # Knight 1
set_piece(3, "♘") # Knight 2
set_piece(0, "♖") # Rook 1
set_piece(0, "♔") # King
set_piece(0, "♖") # Rook 2
def __str__(self):
output = "♙"*8 + "\n"
for piece in self.random_rank:
output += piece
return output
|
from board import Board
from constants import *
class Game:
def __init__(self, player1, player2):
self.board = Board()
self.current_turn = 0
self.total_move_count = 0
self.human_player = player1
self.computer_player = player2
@property
def current_player(self):
return self.human_player if self.current_turn == 0 else self.computer_player
@property
def is_board_filled(self):
return self.total_move_count == ROW_COUNT * COLUMN_COUNT
def _toggle_turn(self):
self.current_turn += 1
self.current_turn %= 2
self.total_move_count += 1
def _check_state(self, col):
row = self.board.drop_coin(col, self.current_player.mark)
return self.board.is_winning_move(row, col, self.current_player.mark)
def start(self):
while True:
column = self.current_player.next_turn(self.board)
while self.board.is_invalid_move(column):
if self.current_player is self.human_player:
column = int(input("Potez nije validan, probaj ponovo: "))
else:
self.current_player.next_turn(self.board)
state = self._check_state(column)
if self.current_player.mark == COMPUTER_PLAYER_MARK:
self.board.print_board()
if state or self.is_board_filled:
break
self._toggle_turn()
|
months = ['January','February','March','April','May','June','July','August','September', 'October','November','December']
month_abbvs = dict((m[:3].lower(), m) for m in months)
def valid_month(month):
if month:
short_month = month[:3].lower()
return month_abbvs.get(short_month)
def valid_day(day):
if day.isdigit():
iday = int(day)
if iday >= 1 and iday <= 31:
return iday
def valid_year(year):
if year and year.isdigit():
if int(year) >= 1900 and int(year) <= 2020:
return int(year)
|
def snake_to_camel(text):
text = text.split('_')
camel = text.pop()
for chunk in text:
camel += text.capitalize()
def camel_to_snake(text):
snake = ''
for letter in text:
if letter.isupper():
snake += '_'
snake += letter.lower()
return snake
|
from tkinter import *
from tkinter import ttk
# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
class VerticalScrolledFrame(Frame):
"""A pure Tkinter scrollable _mainFrame that actually works!
* Use the 'interior' attribute to place widgets inside the scrollable _mainFrame
* Construct and pack/place/grid normally
* This _mainFrame only allows vertical scrolling
"""
def __init__(self, parent, height = None, width = None, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a self.__canvas object and a vertical scrollbar for scrolling it
self.__vscrollbar = Scrollbar(self, orient=VERTICAL)
self.__vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
self.__canvas = Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=self.__vscrollbar.set)
self.__canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
self.__vscrollbar.config(command=self.__canvas.yview)
# reset the view
self.__canvas.xview_moveto(0)
self.__canvas.yview_moveto(0)
# create a _mainFrame inside the self.__canvas which will be scrolled with it
self.interior = interior = Frame(self.__canvas)
interior_id = self.__canvas.create_window(0, 0, window=interior,
anchor=NW)
self.__canvas.config(height=height)
# track changes to the self.__canvas and _mainFrame _width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner _mainFrame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
self.__canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != self.__canvas.winfo_width():
# update the self.__canvas's _width to fit the inner _mainFrame
self.__canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != self.__canvas.winfo_width():
# update the inner _mainFrame's _width to fill the self.__canvas
self.__canvas.itemconfigure(interior_id, width=self.__canvas.winfo_width())
self.__canvas.bind('<Configure>', _configure_canvas)
def destruct(self):
self.__canvas.pack_forget()
self.__vscrollbar.pack_forget()
|
def opening_files(name):
fav_foods = open(name)
fav_foods_list = fav_foods.readlines()
fav_foods.close()
return fav_foods_list
nina_fav_foods = opening_files("nina_fav_foods.txt")
sara_fav_foods = opening_files("sara_fav_foods.txt")
print nina_fav_foods, sara_fav_foods
#if nina_fav_foods[0]==sara_fav_foods[0]:
#print "Our favorite foods are the same :)"
#else:
#print "Our favorite foods are different :("
for x in range(3):
if nina_fav_foods[x] in sara_fav_foods:
food=nina_fav_foods[x]
print "We both love", food
|
#Class for applying the Luhn(Mod 10) Algorithm to generate or validate a check sum
#Written by: D. Reilly 2012
class LuhnFormula:
def doubleDigitAndSum(self,digit):
#double a number, 0-9 and if it is >10 sum the resulting 2 digits
dbl = int(digit)*2
if dbl > 9:
str_dbl = str(dbl)
new_val = int(str_dbl[0])+int(str_dbl[1])
return new_val
else:
return dbl
def checksumValidator(self,id):
id_length = len(id)
checksum = []
sum = 0
#Handle ID of even length
if id_length % 2 == 0:
i = 0
while i < id_length:
#if we are on an odd digit it double and sum
if(i%2!=0):
n_val = self.doubleDigitAndSum(id[i])
print(n_val)
checksum.append(n_val)
else:
checksum.append(int(id[i]))
i += 1
#print("Checksum: ", ''.join(checksum,',')
else:
#Handle ID of odd length
i = 0
while i < id_length:
#if we are on an even digit it double and sum
if(i%2==0):
n_val = self.doubleDigitAndSum(id[i])
checksum.append(n_val)
else:
checksum.append(int(id[i]))
i += 1
for i in checksum:
sum += int(i)
if sum % 10 == 0:
return 1
else:
return 0
|
#!/usr/bin/env python
# coding:utf8
class ChineseGetter(object):
def __init__(self):
self.trans = dict(dog="狗", cat="猫")
def get(self, item):
return self.trans.get(item, str(item))
class EnglishGetter(object):
def get(self, item):
return str(item)
def get_localizer(language="English"):
languages = dict(English=EnglishGetter, Chinese=ChineseGetter)
return languages[language]()
if __name__ == "__main__":
e, c = get_localizer(), get_localizer(language="Chinese")
for item in "dog parrot cat bear".split():
print(e.get(item), c.get(item))
|
#!/usr/bin/env python
# coding:utf8
from abc import abstractmethod, ABCMeta
class AbstractProductA(metaclass=ABCMeta):
@abstractmethod
def productAOperation(self):
pass
class AbstractProductB(metaclass=ABCMeta):
@abstractmethod
def productBOperation(self):
pass
class Factory(metaclass=ABCMeta):
@abstractmethod
def createProductA(self):
pass
@abstractmethod
def createProductB(self):
pass
class ProductA1(AbstractProductA):
def productAOperation(self):
print("ProductA1 instance has been created")
class ProductA2(AbstractProductA):
def productAOperation(self):
print("ProductA2 instance has been created")
class ProductB1(AbstractProductB):
def productBOperation(self):
print("ProductB1 instance has been created")
class ProductB2(AbstractProductB):
def productBOperation(self):
print("ProductB2 instance has been created")
class ConcreteFactory1(Factory):
def createProductA(self):
return ProductA1()
def createProductB(self):
return ProductB1()
class ConcreteFactory2(Factory):
def createProductA(self):
return ProductA2()
def createProductB(self):
return ProductB2()
if __name__ == "__main__":
factory = ConcreteFactory1()
factory.createProductA().productAOperation()
factory.createProductB().productBOperation()
factory = ConcreteFactory2()
factory.createProductA().productAOperation()
factory.createProductB().productBOperation()
|
#!/usr/bin/env python
# coding:utf8
from abc import abstractmethod, ABCMeta
class Product(metaclass=ABCMeta):
@abstractmethod
def productOperation(self):
pass
class Creator(object):
__clazz = None
def __init__(self, name):
self.__clazz = name
def creatorOperaton(self):
print("Creator instance has been created")
def factoryMethod(self):
return self.__clazz()
class ConcreteProduct(Product):
def productOperation(self):
print("Product instance has been created")
if __name__ == "__main__":
creator = Creator(ConcreteProduct)
product = creator.factoryMethod().productOperation()
|
from base.Item import Item
class Player:
def __init__(self,name):
"""
Main player class, to store things like inventory and other things
param name: The name of the player. Purely for astetics
"""
self.name = name
self.health = 100
self.inventory = []
self.looking_at_bird = False
self.angered_bird = False
self.boss_defeated = False
self.door_unlocked = False
self.game_end = False
def pickupItem(self,item):
"""
Adds item to players inventory
"""
# Check if the given item is actually an Item
if isinstance(item,Item):
self.inventory.append(item)
def damage(self,dmg):
"""
Damage the player, from getting attacked or otherwise
"""
self.health = self.health - dmg
if self.health < 0:
self.health = 0
def heal(self,health):
"""
Heal the player
"""
self.health = self.health + health |
# --------------
#1)
##File path for the file
file_path
#Code starts here
def read_file(path):
#Opening of the file located in the path in 'read' mode
file = open(path, 'r')
#Reading of the first line of the file and storing it in a variable
sentence = file.readline()
#Closing of the file
file.close()
#Returning the first line of the file
return sentence
#Calling the function to read file
sample_message = read_file(file_path)
print(sample_message)
#2)
#using fucntion from previous step to store message sentence for file_path_1 and file_path_2
message_1 = read_file(file_path_1)
print(message_1)
message_2 = read_file(file_path_2)
print(message_2)
#Function to fuse message
def fuse_msg(message_a,message_b):
#Integer division of two numbers
quotient = (int(message_b)//int(message_a))
#Returning the quotient in string format
return str(quotient)
#Calling the function 'fuse_msg'
secret_msg_1 = fuse_msg(message_1,message_2)
print(secret_msg_1)
#3)
#Calling the function to read the content of file_path_3
message_3 = read_file(file_path_3)
print(file_path_3)
#Creating function to substitute message
def substitute_msg(message_c):
if message_c == 'Red':
sub = 'Army General'
elif message_c == 'Green':
sub = 'Data Scientist'
elif message_c == 'Blue':
sub = 'Marine Biologist'
return sub
#Using funcion to identify secret_msg_2
secret_msg_2 = substitute_msg(message_3)
print(secret_msg_2)
#4)
#calling the function to read the content of file_path_4 and file_path_5
message_4 = read_file(file_path_4)
print(message_4)
message_5 = read_file(file_path_5)
print(message_5)
# creating a function to compare messages
def compare_msg(message_d,message_e):
#Splitting the message into a list
a_list = message_d.split()
#Splitting the message into a list
b_list = message_e.split()
#Comparing the elements from both the lists
c_list = [i for i in a_list if i not in b_list]
#Combining the words of a list back to a single string sentence
final_msg = " ".join(c_list)
#Returning the sentence
return final_msg
#Calling the function 'compare messages'
secret_msg_3 = compare_msg(message_4,message_5)
#Printing the secret message
print(secret_msg_3)
#5)
#calling the function to read the content of file_path_6
message_6 = read_file(file_path_6)
print(message_6)
#function to filter message
def extract_msg(message_f):
#Splitting the message into a list
a_list = message_f.split()
#Creating the lambda function to identify even length words
even_word = lambda x: (len(x)%2==0)
#Splitting the message into a list
b_list = filter(even_word,a_list)
#Combining the words of a list back to a single string sentence
final_msg = " ".join(b_list)
#Returning the sentence
return final_msg
#Calling the function 'filter_msg'
secret_msg_4 = extract_msg(message_6)
#print the message
print(secret_msg_4)
#6
#Secret message parts in the correct order
message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'
##Combining the secret message parts into a single complete secret message
secret_msg = " ".join(message_parts)
print(secret_msg)
#Function to write inside a file
def write_file(secret_msg, path):
#Opening a file named 'secret_message' in 'write' mode
file = open(path,'a+')
#Writing to the file
file.write(secret_msg)
#closes the file
file.close()
#Calling the function to write inside the file
write_file(secret_msg,final_path)
##Printing the entire secret message
print(secret_msg)
|
# import the required modules
import csv
import mymod
if __name__ == "__main__":
file_name = input("Please enter the name of your file(including extension i.e. .csv .txt .xlsx). ")
while True:
try:
elect_year = str(input("Please enter the election year."))
if int(elect_year) % 4 != 0:
print("Please enter a valid election year.")
if int(elect_year) < 2016:
print("Please enter a valid election year.")
if int(elect_year) > 1976:
print("Please enter a valid election year.")
else:
break
except(TypeError):
elect_year = str(input("Please enter a valid election year."))
except(ValueError):
elect_year = str(input("Please enter a valid election year."))
def get_data(file, elect):
with open(file, 'r') as file:
reader = csv.DictReader(file)
rows = [row for row in reader if row['YEAR']==elect]
file.close()
print("There are", len(rows),"rows for this year.")
return rows
## def write_data(data, write_file):
## try:
## with open(write_file, 'w'):
## write_file.writelines(data)
## write_file.close()
## except IOError:
## print("No such file or directory")
##
## print("File saved.")
data = get_data(file_name, elect_year)
#print(data)
while True:
print("\nOption A","Given an election year, how many votes did each candidate receive total (in the whole country)?\n")
print("\nOption B","Given an election year, how many votes did each party receive total (in the whole country)?\n")
print("\nOption C","Given an election year, how many votes were “write-in” votes?\n")
print("\nOption D","Given an election year, who won the popular vote?\n")
user_choice = str(input("\nPlease select your choice, enter q to quit.\n"))
if user_choice.lower() == 'q':
break
elif user_choice.lower() == 'a':
print(mymod.table_print(mymod.tallied_data(data, "CANDIDATE", "VOTES"),['Candidate','Votes'],width = 50))
elif user_choice.lower() == 'b':
print(mymod.table_print(mymod.tallied_data(mymod.insertion_sort(data,'PARTY'), "PARTY", "VOTES"),['Party','Votes'],width = 50))
elif user_choice.lower() == 'c':
writein = dict(mymod.tallied_data(data, "WRITEIN", "VOTES"))
print("In", elect_year, "there were",writein["TRUE"], "write in votes")
elif user_choice.lower() == 'd':
candidate = mymod.tallied_data(data, "CANDIDATE", "VOTES")
print("In", elect_year,candidate[0][0], "won the popular vote.")
else:
print("That isn't a valid option")
## print(mymod.table_print(mymod.tallied_data(mymod.insertion_sort(data,'TOTALVOTES'), "STATE", "TOTALVOTES"),['State','Total State']))
## max_votes = []
## for item in mymod.tallied_data(mymod.insertion_sort(data,'VOTES'), "CANDIDATE", "VOTES"):
## max_votes.append(item[-1:8])
## print(max_votes[max(max_votes)])
#1976-2016-president.csv
##
## newtxtfile = str(input("Please enter your desired file name(Use .txt extension)."))
##
## party = mymod.tallied_data(data, "PARTY", "VOTES")
##
## for file in newtxtfile:
## write_data(party[0][0],file)
# read in and clean up data
# write a function for each pf the 4 questions you want to answer
# write the main body of your code
#{'YEAR': '2012', 'STATE': 'Alabama', 'STATE_ABR': 'AL', 'CANDIDATE': 'Romney, Mitt', 'PARTY': 'republican', 'WRITEIN': 'FALSE', 'VOTES': '1255925', 'TOTALVOTES': '2074338'}
|
import random
class Die():
"""docstring for Die class"""
def __init__(self):
""""""
self.side = 0
def throw(self):
""" This method is for throw dice"""
self.side=random.randint(1,6)
def get_value(self):
""" This method is for getting value for dice thrown"""
return self.side
# is an Instance of class Die
my_object = Die()
for i in range(1,10):
my_object.throw()
#Innvoking the method throw()
my_object.throw()
die_value = my_object.get_value()
print "The value thrown is",die_value
|
a = []
list = [12,3,4,'anand',12,'raj']
# user_input = raw_input("Please Enter a value : ")
for i in list:
if len(a)>=1:
if type(a[0]) == type(i):
a.append(i)
print "Value appended to List is : ", i
else:
print "This value is not typecast : ", i
else:
a.append(i)
print "Initial Value appended to List is : ", i
|
def get_problemkeys(filename):
"""
Takes in a dataset in XML format, parses it and returns a list with the values of tags with problematic characters.
"""
problemchars_list = []
for _, element in ET.iterparse(filename):
if element.tag == 'tag':
if problemchars.search(element.attrib['k']):
problemchars_list.append(element.attrib['k'])
return problemchars_list
print(get_problemkeys(dataset)) |
#!/usr/bin/python
def funm(x):
return x ** 2
def funf(x):
return x > 2 and x < 5
def funr(x,y):
return x + y
l = [1,2,3,4,5]
l1 = [6,7,8,9,0]
print map(funm,l)
print filter(funf,l)
print reduce(funr,l)
print zip(l,l1)
|
# First line take a number of country and if the country is repeating in list don't count that county and last give how many unique country are there
# Example:
# Line1: 7
# UK
# China
# USA
# France
# New Zealand
# UK
# France
# Ans: 5
c=[]
a = int(input())
for i in range(0,a):
ele= str(input())
c.append(ele)
total = len(c)
if total==0:
print()
if total<=1:
print(total)
for j in range(len(c)):
for k in range(j):
if c[j]==c[k]:
total = total-1
print(total)
-----OR-------
# n,s= int(input()),set()
# for i in range(n):
# s.add(input())
# print(len(s)) |
a=float(1)
e=0.5
while (a+e) != a:
e=e/1.0001
print(e)
|
from functools import reduce
class BoardWrapper:
"""
A hashable and __eq__ comparable representation of the board state.
Exposes the Isolation board via the `board` attribute.
Instances can be used as keys in a hash table. For example, use this
class if you'd like to memoize the heuristic score of a board state.
"""
def __init__(self, board):
self.board = board
self._key = self._board_state()
self._hash = hash(self._key)
# Keeping _key and _hash as static values is a bit of a hack, given
# the board is mutable. However, boards aren't treated as mutable
# values in the life of a call to alpha_beta, and therefore this
# works.
def __hash__(self):
return self._hash
def __eq__(self, other):
return isinstance(other, BoardWrapper) and self._key == other._key
def _board_state(self):
"""A (int, int, int, int, int) tuple representing the board state:
the board's width, height, active-player location, inactive-player
location, and a bit array representing all blank spaces currently
on the board.
"""
return (self.board.width,
self.board.height,
self.board.get_player_location(self.board.active_player),
self.board.get_player_location(self.board.inactive_player),
self._board_bit_representation())
def _board_bit_representation(self):
"A compact bit_array representing all blank spaces of the board."
def _mark_blank_space(bit_array, blank_space):
"Mark blank space with a 1 in the bit_array."
row, col = blank_space
offset = row * self.board.width + col
return bit_array | (1 << offset)
return reduce(_mark_blank_space, self.board.get_blank_spaces(), 0)
|
"""Create a Model class to hold quotes."""
class QuoteModel():
"""Create a QuoteModel class to hold quotes."""
def __init__(self, body, author):
"""Store parameter values in local variable.
Arguments:
body {str} -- an inspiring quote.
author {str} -- author of the quote.
"""
self.body = body
self.author = author
def __repr__(self):
"""Return stored parameter values in local variable.
Returns:
{str} -- quote and its author.
"""
return f'<{self.body}, {self.author}>'
|
#!/usr/bin/env python
from sympy import *
from sympy.utilities.solution import *
x = Symbol("x")
y = Symbol("y")
z = Symbol("z")
a = Symbol("a")
eqs = [
[x - 3*y + z - 4, 2*x - 8*y + 8*z + 2, -6*x + 3*y - 15*z - 9],
[x - 3*y + z - 4, 2*x - 8*y + 8*z + 2,],
[x - 3*y + z - 4, 2*x - 8*y + 8*z + 2, 2*x - 8*y + 8*z + 3],
# [y + z - 1, x - y + z, 2*x - 2*y + 2*z, 2 * x + y, 2 * x + y, y + z - 1, y + z - 1],
# [y + z - 1, y + z, 2*x - 2*y + 2*z, 2 * x + y, 2 * x + y, y + z - 1, 2 * y + z - 1],
[x - y + 2*z + 3, 4*x + 4*y - 2*z - 1, -2*x + 2*y - 4*z - 6],
[x - y, x + y + a],
[x - y, 2*x - 2*y, -x + y - 3]
]
for eq in eqs:
print '===================================================='
reset_solution()
res = solve(eq, [x, y, z])
R = last_solution()
for r in R:
print r
print '=== Answer:'
if len(res) == 0:
print "There is no solution"
else:
for r, s in res.items():
print latex(r), '=', latex(s) |
# Second GA program
import math
import random
from circle_class import Circle # import my circle class
from tkinter import*
# Problem found @ AI-junkie.com. This file uses a GA to find the largest circle that can fill a
# space between other circles in the given grid. All that is necessary for the other circles
# are their origins and radii.
# A circle class is provided to speed comparisons needed by the fitness function. Fitness is
# based on area if a circle doesn't intersect others. Future improements could be made by
# allowing floating points for x/y/radius (may allow tighter fits), as well as possibly
# developing a fitness that allows intersections as possible answers, assigning a fitness with
# a penalty. For now, Occum's Razor, intetsecting circles or circles containing others will
# be assigned a fitness of 0.
# In this implementation, we will have three locii. The first will represent the X coord,
# the second the Y coord, and finally, the third is the radius. We are allowing binary values
# that translate from (0-500) in base 10. This means each locus is of length 9.
class Chromosome:
name = ""
fitness = 0.00
def __init__(self):
self.name = "000000000000000000000000000" # max value of 500
self.fitness = 0.00
def __repr__(self):
return 'Name: ' + self.name + ' Fitness: ' + str(self.fitness)
# World variables
sol = Chromosome() # best solution found so far
population = [] # current population
random.seed() # help generate random chromosomes
length = 27 # chromosome length
pop_size = 100 # must(?) be divisible by 4
mutation_rate = .001 # likelihood of mutation
xover_point = 18 # point of crossover for parent pairs (will change radius)
numGens = 100 # number of generations we wish to iterate through
# TK World Variables
master = Tk()
canvas_width = 500
canvas_height = 500
# No dictionary necessary for conversion, we will simply translate from a 10 digit bin to decimal
# accomplished via int(<10 digit str>, base=2), will convert the string to a base 10 number
# Initial list of circles. Keeping it small at the moment since the fitness function will
# compare a population of M circles by the number N circles here. This can result in a
# O(n^2) operation -- plus we do this for P number of generations O(n^3)
initial_list = [ Circle(100,150,65), Circle(200,300, 105), Circle(450,150,50),
Circle(200,50,10), Circle(300,50,30), Circle(400,400,25),
Circle(400,300,25) ]
# Will create a random population of pop_size of chromosomes, each of length 'length'
def createPopulation():
#print('Creating Initial Population!')
# automatically creating a string of size 'length' then flipping 'bits' as we go
for j in range(0, pop_size):
val = ""
for i in range(0,length):
if random.random() > random.random():
val = val + '1'
else:
val = val + '0'
c = Chromosome()
c.name = val
population.append(c)
# Decodes the name of a chromosome into its 3 locii (also does base2 to 10 conversion)
def decode(chrome):
val = ""
for i in range(0, length, 9):
val = val + str(int(chrome.name[i:i+9], base=2)) + ' '
#print(val)
return val
# Test each member of the population
def testPopulation():
for item in population:
fitness(item)
# Fitness function -- we will test the random circle against circles in the initial list.
# Only if it doesn't intersect or contain(s) other circles, will fitness be assigned
# Fitness will equal its area.
def fitness(chrome):
val = decode(chrome) # interpret the circle
xyrad = val.split()
circ = Circle(int(xyrad[0]),int(xyrad[1]), int(xyrad[2]))
# Evaluate this circle against all the circles in the initial_list
# Also do a bounds check for drawing the circle on the screen
for item in initial_list:
if circ.intersects(item) == True:
return
if circ.containsCircle(item) == True:
return
if circ.x + circ.radius > canvas_width or circ.x - circ.radius < 0:
return
if circ.y + circ.radius > canvas_height or circ.y - circ.radius < 0:
return
chrome.fitness = circ.area()
if chrome.fitness >= sol.fitness:
sol.fitness = chrome.fitness
sol.name = chrome.name
# Builds the next generation of chromosomes to test on. It selects a parent pair from the
# current population to produce an offspring. After crossover, there is a small mutation
# chance. Then offspring is added to the new population pool.
def buildNewPopulation():
#print('Building New Population!')
newPop = []
# Roulette wheel selection first (those with higher fitness scores have a better chance of
# being selected for breeding)
total_sum = sumPop() # sum the total value of the population's fitness scores
# Build new population
while len(newPop) != pop_size:
r = random.uniform(0, total_sum) # Get random number within this range
a = findChrom(r) # find a chromosome in the population with fitness >= r
r = random.uniform(0, total_sum) # Get random number within this range
b = findChrom(r) # find a chromosome in the population with fitness >= r
c = crossOver(a,b) # crossover the selected parents
mutate(c); # add in possible mutation
newPop.append(c) # add to the new population
return newPop # next generation gets a chance to shine
# Mutates the chromosome with a set probability (steps through each bit, flips it if a threshold is met)
def mutate(chrome):
for i in range(0, len(chrome.name)):
if random.random() <= mutation_rate: # if met, flip this bit
if chrome.name[i] == '1':
chrome.name[i] == '0'
else:
chrome.name[i] == '1'
# Crosses the parents at a random point to create a child
def crossOver(a, b):
# now cross at this point
child = Chromosome()
for i in range(0,xover_point):
child.name = child.name + a.name[i]
for i in range(xover_point, len(b.name)):
child.name = child.name + b.name[i]
return child
# Finds a chromosome in the population whose fitness is >= the number passed in
def findChrom(r):
for item in population:
if item.fitness >= r:
return item
# if none found, return a random element
newR = random.randint(0,pop_size-1)
return population[newR]
# Sums fitness values of total population
def sumPop():
total_sum = 0
for item in population:
total_sum = total_sum + item.fitness
return total_sum
# Functions to TK
def checkered(canvas, line_distance):
# vertical lines at an interval of "line_distance" pixel
for x in range(line_distance,canvas_width,line_distance):
canvas.create_line(x, 0, x, canvas_height, fill="#476042")
# horizontal lines at an interval of "line_distance" pixel
for y in range(line_distance,canvas_height,line_distance):
canvas.create_line(0, y, canvas_width, y, fill="#476042")
def circle(canvas,x,y, r):
id = canvas.create_oval(x-r,y-r,x+r,y+r)
return id
# main function
def main():
createPopulation()
generation = 0
while generation <numGens:
testPopulation()
population = buildNewPopulation()
generation = generation + 1
print(sol.name)
print('Generations calculated: ' + str(generation) + '!')
print(str(decode(sol)))
print(str(sol.fitness))
xyrad = decode(sol).split()
x = int(xyrad[0])
y = int(xyrad[1])
r = int(xyrad[2])
circ = Circle(x,y,r)
w = Canvas(master,
width=canvas_width,
height=canvas_height)
w.pack()
checkered(w,20)
# following circles are "static" and will be added to the finder program
circle(w, 100, 150, 65)
circle(w, 200, 300, 105)
circle(w, 450, 150, 50)
circle(w, 200, 50, 10)
circle(w, 300, 50, 30)
circle(w, 400, 400, 25)
circle(w, 400, 300, 25)
w.create_oval(x-r,y-r,x+r,y+r, fill="green") # new circle
mainloop()
# run the program
main()
|
import math
def make_int_array_from_string(string):
string_array = string.split(" ")
return [float(num) for num in string_array]
def dot_multiply(row, column):
result = 0
for i in range(len(row)):
result += row[i] * column[i]
return result
def remove_column(matrix, column):
answer_matrix = [element * 1 for element in matrix]
for row in answer_matrix:
row.pop(column)
answer_matrix.pop(0)
return answer_matrix
class Matrix:
def __init__(self, row_count, column_count):
self.row_count = row_count
self.column_count = column_count
self.matrix = list()
def create_matrix_from_input(self):
matrix = []
for row in range(self.row_count):
row_array = make_int_array_from_string(input())
matrix.append(row_array)
self.matrix = matrix
def set_matrix_list(self, array):
self.matrix = array
def render_matrix(self):
for row in self.matrix:
string = " "
print(string.join([str(element) for element in row]))
def remove_column_at_row(self, column, row):
answer_matrix = [element * 1 for element in self.matrix]
for row_item in answer_matrix:
row_item.pop(column)
answer_matrix.pop(row)
matrix_object = Matrix(row - 1, column - 1)
matrix_object.set_matrix_list(answer_matrix)
return matrix_object
def add_matrix(self, matrix_b):
if len(self.matrix) != len(matrix_b.matrix):
return "ERROR"
if len(self.matrix[0]) != len(matrix_b.matrix[0]):
return "ERROR"
for row_index in range(self.row_count):
for item_index in range(self.column_count):
self.matrix[row_index][item_index] += matrix_b.matrix[row_index][item_index]
def multiply_by_constant(self, constant):
self.matrix = [[0 if element == 0 else round(constant * element, 4) for element in row] for row in self.matrix]
def main_diagonal_transpose(self):
new_matrix = Matrix(self.column_count, self.row_count)
columns_result = []
for index in range(self.column_count):
individual_column = []
for row in range(self.row_count):
individual_column.append(self.matrix[row][index])
columns_result.append(individual_column)
new_matrix.set_matrix_list(columns_result)
return new_matrix
def side_diagonal_transpose(self):
new_matrix = Matrix(self.column_count, self.row_count)
old_matrix = self.matrix
old_matrix.reverse()
columns_result = []
for index in range(self.column_count):
individual_column = []
for row in range(self.row_count):
individual_column.append(old_matrix[row][index])
columns_result.append(individual_column)
columns_result.reverse()
new_matrix.set_matrix_list(columns_result)
return new_matrix
def vertical_line_transpose(self):
matrix_list = self.matrix
for row in matrix_list:
row.reverse()
result_matrix = Matrix(self.row_count, self.column_count)
result_matrix.set_matrix_list(matrix_list)
return result_matrix
def horizontal_line_transpose(self):
matrix_list = self.matrix
matrix_list.reverse()
result_matrix = Matrix(self.row_count, self.column_count)
result_matrix.set_matrix_list(matrix_list)
return result_matrix
def multiply_by_matrix(self, matrix):
answer_matrix = Matrix(self.row_count, matrix.column_count)
if self.column_count != matrix.row_count:
return "ERROR"
matrix_b_trans = matrix.main_diagonal_transpose()
result = []
for row in self.matrix:
new_row = []
for column in matrix_b_trans.matrix:
entry = dot_multiply(row, column)
new_row.append(entry)
result.append(new_row)
answer_matrix.set_matrix_list(result)
return answer_matrix
def calculate_determinant(self):
matrix = self.matrix
if len(matrix) == 1:
return matrix[0][0]
elif len(matrix) == 2:
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0])
else:
row_1 = matrix[0]
answer = 0
for i in range(len(row_1)):
further = remove_column(matrix, i)
further_matrix = Matrix(len(matrix) - 1, len(row_1) - 1)
further_matrix.set_matrix_list(further)
element = row_1[i]
answer += (element * ((-1) ** i) * further_matrix.calculate_determinant())
return answer
def invert(self):
if self.calculate_determinant() == 0:
return "ERROR"
second_matrix = Matrix(self.row_count, self.column_count)
second_matrix_list = []
for i in range(self.row_count):
new_row = []
for j in range(self.column_count):
new_element = (-1) ** (i + j + 2) * (self.remove_column_at_row(j, i)).calculate_determinant()
new_row.append(new_element)
second_matrix_list.append(new_row)
second_matrix.set_matrix_list(second_matrix_list)
second = second_matrix.main_diagonal_transpose()
second.multiply_by_constant(1 / self.calculate_determinant())
return second
def receive_menu_option():
print('1. Add matrices')
print('2. Multiply matrix by a constant')
print('3. Multiply matrices')
print('4. Transpose matrix')
print('5. Calculate a determinant')
print('6. Inverse matrix')
print('0. Exit')
return input('Your choice: ')
def menu_option_add():
row, space, column = input('Enter size of first matrix: ')
matrix_a = Matrix(int(row), int(column))
matrix_a.create_matrix_from_input()
row2, space, column2 = input('Enter size of second matrix: ')
matrix_b = Matrix(int(row2), int(column2))
matrix_b.create_matrix_from_input()
matrix_a.add_matrix(matrix_b)
print('The result is:')
matrix_a.render_matrix()
def menu_option_cons():
row, space, column = input('Enter size of matrix: ')
matrix_a = Matrix(int(row), int(column))
matrix_a.create_matrix_from_input()
const = float(input('Enter constant: '))
matrix_a.multiply_by_constant(const)
print('The result is:')
matrix_a.render_matrix()
def menu_option_mult():
row, space, column = input('Enter size of first matrix: ')
matrix_a = Matrix(int(row), int(column))
matrix_a.create_matrix_from_input()
row2, space, column2 = input('Enter size of second matrix: ')
matrix_b = Matrix(int(row2), int(column2))
matrix_b.create_matrix_from_input()
answer = matrix_a.multiply_by_matrix(matrix_b)
print('The result is: ')
answer.render_matrix()
def menu_option_transpose():
print('1. Main diagonal')
print('2. Side diagonal')
print('3. Vertical line')
print('4. Horizontal line')
choice = input('Your choice: ')
row, space, column = input('Enter size of matrix: ')
matrix = Matrix(int(row), int(column))
print('Enter matrix: ')
matrix.create_matrix_from_input()
answer = None
if choice == '1':
answer = matrix.main_diagonal_transpose()
if choice == '2':
answer = matrix.side_diagonal_transpose()
if choice == '3':
answer = matrix.vertical_line_transpose()
if choice == '4':
answer = matrix.horizontal_line_transpose()
print('The result is:')
answer.render_matrix()
def menu_option_determinant():
row, space, column = input('Enter size of matrix: ')
matrix = Matrix(int(row), int(column))
matrix.create_matrix_from_input()
answer = matrix.calculate_determinant()
print('The result is: ')
print(answer)
def menu_option_inverse():
row, space, column = input('Enter size of matrix: ')
matrix = Matrix(int(row), int(column))
matrix.create_matrix_from_input()
result_matrix = matrix.invert()
if result_matrix == 'ERROR':
print("This matrix doesn't have an inverse.")
else:
print('The result is: ')
Matrix.render_matrix(result_matrix)
def main():
user_input = receive_menu_option()
while user_input != '0':
if user_input == '1':
menu_option_add()
if user_input == '2':
menu_option_cons()
if user_input == '3':
menu_option_mult()
if user_input == '4':
menu_option_transpose()
if user_input == '5':
menu_option_determinant()
if user_input == '6':
menu_option_inverse()
print()
user_input = receive_menu_option()
main()
|
#asyncio2.py to build and run coroutines in parallel
import asyncio
import time
async def say(delay, msg):
await asyncio.sleep(delay)
print(msg)
async def main ():
task1 = asyncio.create_task( say(1, 'Good'))
task2 = asyncio.create_task( say(1, 'Morning'))
print("Started at ", time.strftime("%X"))
await task1
await task2
print("Stopped at ", time.strftime("%X"))
asyncio.run(main()) |
# myadd3.py is a class with with add two numbers method
def add( x, y):
"""This function adds two numbers"""
if (not isinstance(x, (int, float))) | \
(not isinstance(y, (int, float))):
raise TypeError("only numbers are allowed")
return x + y
|
# process1.py to create simple processes with function
import os
from multiprocessing import Process, current_process as cp
from time import sleep
def print_hello():
sleep(2)
print("{}-{}: Hello".format(os.getpid(), cp().name))
def print_message(msg):
sleep(1)
print("{}-{}: {}".format(os.getpid(), cp().name, msg))
def main():
processes = []
# creating process
processes.append(Process(target=print_hello, name="Process 1"))
processes.append(Process(target=print_hello, name="Process 2"))
processes.append(Process(target=print_message,
args=["Good morning"], name="Process 3"))
# start the process
for p in processes:
p.start()
# wait till all are done
for p in processes:
p.join()
print("Exiting the main process")
if __name__ == '__main__':
main() |
# pandastrick4.py
import pandas as pd
weekly_data = {'day':['Monday','Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday'],
'temp':[40, 33, 42, 31, 41, 40, 30],
'condition':['Sunny','Cloudy','Sunny','Rainy','Sunny',
'Cloudy','Rainy']
}
df = pd.DataFrame(weekly_data)
print(df[(df.condition == 'Rainy') | (df.condition == 'Sunny')])
print(df[df['condition'].str.contains('Rainy|Sunny')]) |
# process5.py to use queue to exchange data
from multiprocessing import Process
from multiprocessing import Queue
def copy_data (list, myqueue):
for num in list:
myqueue.put(num)
def output(myqueue):
while not myqueue.empty():
print(myqueue.get())
def main():
mylist = [2, 5, 7]
myqueue = Queue()
p1 = Process(target=copy_data, args=(mylist, myqueue))
p2 = Process(target=output, args=(myqueue,))
p1.start()
p1.join()
p2.start()
p2.join()
print("Queue is empty: ",myqueue.empty())
print("Exiting the main process")
if __name__ == '__main__':
main() |
#carexample7.py
class Car:
__mileage_units = "Mi"
def __init__(self, col, mil):
self.__color = col
self.__mileage = mil
def __str__(self):
return f"car with color {self.color} and mileage {self.mileage}"
@property
def color(self):
return self.__color
@property
def mileage(self):
return self.__mileage
@mileage.setter
def mileage (self, new_mil):
self.__mileage = new_mil
if __name__ == "__main__":
car = Car ("blue", 1000)
print (car)
print (car.color)
print(car.mileage)
car.mileage = 2000
print (car.color)
print(car.mileage)
|
# thread3b.py when thread synchronization is used
from threading import Lock, Thread as Thread
def inc_with_lock (lock):
global x
for _ in range(1000000):
lock.acquire()
x+=1
lock.release()
x = 0
mylock = Lock()
# creating threads
t1 = Thread(target=inc_with_lock , args=(mylock,), name="Th 1")
t2 = Thread(target=inc_with_lock , args=(mylock,), name="Th 2")
# start the threads
t1.start()
t2.start()
#wait for the threads
t1.join()
t2.join()
print("final value of x :", x)
|
#exception1.py
try:
#print (x)
x = 5
y = 1
z = x /y
print('x'+y)
except NameError as e:
print(e)
except ZeroDivisionError:
print("Division by 0 is not allowed")
except Exception as e:
print("An error occured")
print(e)
|
#methodoverloading1.py
class Car:
def __init__(self, color, seats):
self.i_color = color
self.i_seat = seats
def print_me(self, i='basic'):
if(i =='basic'):
print(f"This car is of color {self.i_color}")
else:
print(f"This car is of color {self.i_color} with seats {self.i_seat}")
if __name__ == "__main__":
car = Car("blue", 5 )
car.print_me()
car.print_me('blah')
car.print_me('detail')
|
#iterator4.py
class Week:
def __init__(self):
self.days = {1: 'Monday', 2: "Tuesday",
3: "Wednesday", 4: "Thursday",
5: "Friday", 6: "Saturday", 7: "Sunday"}
def __iter__(self):
return WeekIterator(self.days)
class WeekIterator:
def __init__(self, dayss):
self.days_ref = dayss
self._index = 1
def __iter__(self):
return self;
def __next__(self):
if self._index < 1 | self._index > 8:
raise StopIteration
else:
ret_value = self.days_ref[self._index]
self._index +=1
return ret_value
if(__name__ == "__main__"):
wk = Week()
iter1 = iter(wk)
iter2 = iter(wk)
print(iter1.__next__())
print(iter2.__next__())
print(next(iter1))
print(next(iter2)) |
#test_mycalc_subtract.py test suite for substract class method
import unittest
from myunittest.src.mycalc.mycalc import MyCalc
class MyCalcSubtractTestSuite(unittest.TestCase):
def setUp(self):
self.calc = MyCalc()
def test_subtract(self):
""" test case to validate two positive numbers"""
self.assertEqual(5, self.calc.subtract(10 , 5), "should be 5")
if __name__ == '__main__':
unittest.main()
|
#asyncio1.py to build a basic coroutine
import asyncio
import time
async def say(delay, msg):
await asyncio.sleep(delay)
print(msg)
print("Started at ", time.strftime("%X"))
asyncio.run(say(1,"Good"))
asyncio.run(say(2, "Morning"))
print("Stopped at ", time.strftime("%X"))
|
#iterator2.py
class Week:
def __init__(self):
self.days = {1:'Monday', 2: "Tuesday",
3:"Wednesday", 4: "Thursday",
5:"Friday", 6:"Saturday", 7:"Sunday"}
self._index = 1
def __iter__(self):
self._index = 1
return self
def __next__(self):
if self._index < 1 | self._index > 8:
raise StopIteration
else:
ret_value = self.days[self._index]
self._index +=1
return ret_value
if(__name__ == "__main__"):
wk = Week()
for day in wk:
print(day) |
# mycalc.py with add,subtract, multiply and divide functions
class MyCalc:
def add(self, x, y):
"""This function adds two numbers"""
return x + y
def subtract(self, x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(self, x, y):
"""This function subtracts two numbers"""
return x * y
def divide(self, x, y):
"""This function subtracts two numbers"""
return x / y
|
import math
def prime(n):
func = lambda x: [x%i for i in range(2, int(math.sqrt(x)) + 1) if x%i ==0]
return filter(func, range(2,n+1))
n = int(input("请输入一个比2大的数:"))
print(list(prime(n)))
|
import re # import for regex expressions
tokens = [] #output in array form
user_input = input("Enter your input: ").split() #NB: Include spaces in your input for split function to work properly.
print (user_input)
for word in user_input:
bool
#identifies if a given string reps a data-type
if word in [ 'int', 'bool','float', 'double', 'char','str', ]:
tokens.append(['DATATYPE', word])
#identifies the loop conditions
elif word in ['for', 'while', 'do']:
tokens.append(['KEYWORD:', word])
#identifies if a given string contains letters and classifies it as an identifier
elif re.match("[a-z]", word) or re.match("[A-Z]", word):
tokens.append(['IDENTIFIER:', word])
#identifies the arithmetic operations that may exist in the inputs
elif word in '-/*+%=':
tokens.append(['ARITHMETIC OPERATOR', word])
#identifies any relational operators
elif word in ['<', '>', '<=', '>=', '==', '!=']:
tokens.append(['RELATIONAL OPERATOR:', word])
#identifies conditional operators
elif word in ['&&', '|']:
tokens.append(['CONDITIONAL OPERATOR: ', word])
#identifies the integers
elif re.match(".[0-9]", word):
if word[len(word) - 1] == ';':
tokens.append(["INTEGER: ", word[:-1]])
else:
tokens.append(["INTEGER: ", word])
elif word in [';']
tokens.append(['END STATEMENT: ', word])
print(tokens) #print the lexical analysis classification list
|
#question1) écrire un algorithme power utilisant une boucle pour calculer x^n, x et n en entrée
def power(x,n):
valeur=1
for i in range(n):
valeur=valeur*x
# print(i,valeur)
return(valeur)
# print("##### power #####")
# print(power(3,3)) #renvoit 27
# print(power(4,2)) #renvoit 16
# print(power(2,8))
# print("### fin power ####")
#question2) dans le cas où n puissance de 2, simplifier algorithme
def power2(x,k):
valeur=x
for i in range(k):
valeur=valeur*valeur
return(valeur)
# print("##### power2 #####")
# print(power2(2,3))
# print("### fin power2 ####")
#question3) tout nombre n peut s'écrire sous forme Somme(ak2^k) avec ak=1ou0
def puissance(x,n):
valeur=1
while n>0:
if n%2==1:
valeur=valeur*x
x=x*x
n=n//2
return(valeur)
# print("#### puissance ####")
# for i in range(0,9) :
# print("2^{0}={1}".format(i,puissance(2,i)))
# print("#### fin puissance ####")
|
#tours de Hanoi
def deplacer(tour_de_dep , tour_arriv , disque):
print("deplacer le disque " + str(disque) + " de la tour " + str(tour_de_dep) + " à la tour " + str(tour_arriv))
return
# print(deplacer(2,3,5))
def hanoi(nombre_de_disque , tour_de_depart , tour_d_arrive):
if nombre_de_disque < 1:
print("le fun est présent")
elif nombre_de_disque == 1:
deplacer(tour_de_depart , tour_d_arrive , 1)
else:
autre_tour = 3 - tour_de_depart - tour_d_arrive
# 1/ deplacer n-1 disques de la "tour de depart" à "autre tour"
hanoi(nombre_de_disque - 1 , tour_de_depart , autre_tour)
# 2/ deplacer 1 disque de la tour de "tour de depart" a "tour d'arrive"
deplacer(tour_de_depart , tour_d_arrive , nombre_de_disque)
# 3/ deplacer n-1 disques de la tour "autre tour" a "tour d'arrivee"
hanoi(nombre_de_disque - 1 , autre_tour , tour_d_arrive)
return
print(hanoi(4,0,1))
|
def fibonacci(N):
U=[0]*N
U[0]=1
U[1]=1
for i in range(2,N):
U[i]=U[i-1]+U[i-2]
return(print(U))
print(fibonacci(10)) |
Questions = [
{
"body ": "Is this happening tomorow ?",
"question_id": 1,
"meetup_id": 1,
"title": "Rehumanizing humans",
"user": 1,
"votes": 0
}
]
user = 1
votes = 1
class QuestionsModel():
""" This class contains models for questions """
def __init__(self):
self.db = Questions
def single_question(self, question_id):
if len(Questions) == 0:
return False
for question in Questions:
if question["question_id"] == question_id:
return question
return False
def add_question(self, meetup_id, title,body_text):
""" Questioner endpoints for questions """
output = {
"user" : user,
"question_id" : len(self.db) + 1,
"meetup_id" : meetup_id,
"title" : title,
"body_text" : body_text
}
self.db.append(output)
return self.db
def upvote_question(self, question_id):
""" This model upvotes a question """
if len(Questions) == 0:
return False
my_question = self.single_question(question_id)
if my_question:
my_question["votes"] += 1
return my_question
return False
def downvote_question(self, question_id):
""" This model downvotes a question """
if len(Questions) == 0:
return False
my_question = self.single_question(question_id)
if my_question:
my_question["votes"] -= 1
return my_question
return False
|
# this is similar to argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_one(arg1):
print "arg1:"+ %r % arg1
def print_none():
print "I've got nothin'."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("Yeah")
print_none()
|
list_of_strings = ["1", "9", "11", "100"]
# Parse strings to integers
list_of_integers = [int(item) for item in list_of_strings]
# This one should be fine, we're providing a list of integers
for item in list_of_integers:
if item < 10:
print(item)
# This one will break, we're providing a list of strings, but we only notice at runtime
for item in list_of_strings:
if item < 10:
print(item)
|
def main():
aMatrix = [[0,1,0,0,1], [1,0,1,1,1],[0,1,0,1,0],[0,1,1,0,1],[1,1,0,1,0]]
# for vertex in range(len(aMatrix)):
# for edge in range(len(aMatrix[vertex])):
# if aMatrix[vertex][edge] == 1:
# print(vertex, ' Has Connection with ', edge)
# print()
print('Tour is started:', len(aMatrix)-1)
# for vertex for vertex in range(len(aMatrix)):
v = 0
edge = 0
counter = 0;
while counter < len(aMatrix):
if v == len(aMatrix)-1:
edge = 0
else:
edge = v + 1
if aMatrix[v][edge] == 1:
if v == len(aMatrix)-1 and edge == 0:
print('From ',v,', the tourists are now in ',edge)
print('We are back at the starting point, Tour is finished!')
counter += 1
else:
print('From ',v,', the tourists are now in ',edge)
v = edge
counter += 1
else:
print('Incremental Cyle is not available!')
break
if __name__ == '__main__':
main()
|
def quickSort(nums):
length = len(nums)
return nums
def main():
nums = [99, 44, 6, 2, 1, 5, 63, 0, 87, 283, 4, 0]
print(quickSort(nums))
if __name__ == '__main__':
main()
|
import pprint
import requests
def get_json_response(base):
'''Gets data in JSON format for the exchange rates of common currencies compared to the base currency,
which is taken as an argument(i.e base=USD).
'''
url = 'https://api.fixer.io/latest?base={}'.format(base)
json_response = requests.get(url).json()
return json_response
def get_exchange(json_response):
'''Processes the returned JSON of get_json_response function and prints exchange rates for the given base
currency.
'''
print('The exchange rate for 1 ' + json_response['base'] + ' is: ' + '\n')
for key in json_response['rates']:
print(str(json_response['rates'][key]) + ' ' + key)
json_response = get_json_response(base='USD')
pprint.pprint(json_response)
get_exchange(json_response)
|
from heapq import heappop, heapify
class MyList(list):
def __lt__(self, other):
return self[0] < other[0]
def merge_k_sorted_lists(arrs):
"""O(n*k*log(k))"""
arr = []
heap = []
k = len(arrs)
for i in range(k):
heap.append(MyList([float('inf'), arrs[i].__iter__()]))
for j in range(len(heap)):
heap[j][0] = heap[j][1].__next__()
heapify(heap)
while len(heap) > 0:
arr.append(heap[0][0])
try:
heap[0][0] = heap[0][1].__next__()
except StopIteration:
heappop(heap)
heapify(heap)
return arr
|
"""Красно-черное дерево - бинарное дерево поиска, сбалансированное(h = O(log n) ~~ h <= 2log(n + 1))
1. Каждый узел либо красный, либо черный
2. Корень и листья (NIL) - черные
3. У красного узла все дочерные узлы черные
4. Для каждого узла все простые пути от него до листьев, содержат одно и то же кол-во черный узлов"""
class Node:
def __init__(self, data=None, parent=None, left=None, right=None, color = None):
self.data = data
self.left = left
self.right = right
self.color = color # 0 - black, 1 - red
self.parent = parent
if self.parent:
self.depth = parent.depth + 1
else:
self.depth = 1
class Tree:
def __init__(self, data_root):
self.root = Node(data=data_root)
self.nil = Node()
def left_rotate(self, x):
"""Предполагается x.right != T.nil"""
y = x.right
x.right = y.left
if y.left:
y.left.parent = x
y.parent = x.parent
if x.parent is None:
self.root = y
elif x == x.p.left:
x.p.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
def add_node(self, data, node):
if data <= node.data:
if node.left:
self.add_node(data, node=node.left)
else:
node.left = Node(parent=node, data=data, color=1)
# fix-up
else:
if node.right:
self.add_node(data, node=node.right)
else:
node.right = Node(parent=node, data=data, color=1)
# fix-up
def r_bfs(self):
queue = []
p = self.root
queue.append(p)
while queue:
temp = queue.pop(0)
print('\t'*temp.depth, end='')
print(temp.data)
if temp.right:
queue.append(temp.right)
if temp.left:
queue.append(temp.left)
def depth_traversal(self, node):
if node.right:
self.depth_traversal(node.right)
print('\t'*node.depth, end='')
print(node.data)
if node.left:
self.depth_traversal(node.left)
def search(self, data, temp_node=None):
if not temp_node:
temp_node = self.root
if data == temp_node.data:
return True
if data < temp_node.data and temp_node.left:
return self.search(data, temp_node.left)
elif data > temp_node.data and temp_node.right:
return self.search(data, temp_node.right)
return False
def print_in_order(self, node):
"""sorting O(n)"""
if node.left:
self.print_in_order(node.left)
print(node.data)
if node.right:
self.print_in_order(node.right)
|
import random
def main():
dirs=(0,0,0,0)
entrance={'name':'Entrance Way','directions':dirs,'msg':'You are in Entrance Way'}
livingroom={'name':'Living Room','directions':dirs,'msg':'You are in Living Room'}
hallway={'name':'Hallway','directions':dirs,'msg':'You are in Hallway'}
kitchen={'name':'Kitchen','directions':dirs,'msg':'You are in Kitchen'}
diningroom={'name':'Dining Room','directions':dirs,'msg':'You are in Dining Room '}
familyroom={'name':'Family Room','directions':dirs,'msg':'You are in Family Room '}
entrance['directions']=(kitchen,livingroom,0,0)
livingroom['directions']=(diningroom,0,0,entrance)
hallway['directions']=(0,kitchen,0,familyroom)
kitchen['directions']=(0,diningroom,entrance,hallway)
diningroom['directions']=(0,0,livingroom,kitchen)
familyroom['directions']=(0,hallway,0,0)
rooms=[livingroom,hallway,kitchen,diningroom,familyroom]
room_with_eggs=random.choice(rooms)
Flag=False
room=entrance
print("Welcome,Bunny can you find John\'s basket?")
while True:
idx=input("select a direction 'N','E','S'or'W':")
while idx!='N' and idx!='E' and idx !='S' and idx!='W':
idx=input("Sorry,that's an invalid choice,select a direction 'N','E','S'or'W':")
direc=['N','E','S','W']
print(direc.index(idx))
x=int(direc.index(idx))
if not room['directions'][x]:
print("There is no way in that direction,")
continue
room=room['directions'][x]
if Flag==False:
if room['name']==room_with_eggs['name']:
Flag=True
print(room['msg']+"Put the eggs in the basket and reach back to entrance")
room['msg']="Your are back in "+room['name']+" You have already put the eggs,rush to entrance"
else :
print("q")
print(room['msg'])
room['msg']="Your are back in "+room['name']
else:
if room['name']=='Entrance Way':
print("You have dilivered the eggs and returned to entrance\nYou may leave \n Congrats!!!")
break
else:
print(room['msg'])
room['msg']="Your are back in "+room['name']
main()
|
# Power digit sum
# Problem 16
# 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#
# What is the sum of the digits of the number 21000?
#
# Again, a problem that is trivially implemented in Python thanks
# to its handling of arbitrarily large integers:
#
# print("The sum of digits in 2^{0} is {1}".format(EXPONENT, sum(int(digit) for digit in str(2**EXPONENT))))
#
# A simple solution that falls within the spirit of this problem
# does exist, however, by implementing the number as an array of
# digits.
#
# As the challenge of Problem16 seems to be the creation of an algorithm
# that can go arbitrarily high, without relying on library functions like
# bigint or natively infinite precision integer types like Python,
# this solution was used instead of the one-liner involving 2**1000.
#
# It's obviously inefficient as far as algorithms go, but it shows
# the process of addition with carry clearly.
from math import ceil, log
EXPONENT = 1000
DIGIT_COUNT = ceil(EXPONENT * log(2, 10)) + 1
def run():
digit_list = [0] * DIGIT_COUNT
digit_list[0] = 1
digits = 1
for x in range(EXPONENT):
for digit in range(digits - 1, -1, -1):
digit_list[digit] *= 2
if digit_list[digit] > 9:
if digit + 1 == digits:
digit_list.append(0)
digits += 1
digit_list[digit] %= 10
digit_list[digit + 1] += 1
result = sum(digit_list)
print("The sum of digits in 2^{0} is {1}".format(EXPONENT, result))
# Sample Output:
# The sum of digits in 2^1000 is 1366
#
# Total running time for Problem16.py is 0.07098571890410678 seconds
|
# Special Pythagorean triplet
# Problem 9
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
#
# First, we recognize that if a <= b
# then (a - 1)^2 + (b + 1)^2 = a^2 + b^2 + 2b - 2a + 2
# cannot possibly be smaller than a^2 + b^2.
#
# This fact can be used to substantially reduce wasted guesses.
#
# Algorithm can be further refined with binary searches instead of
# naive incrementing, but no need to optimize yet.
INITIAL_C_VALUE = 334
def run():
c = INITIAL_C_VALUE
for c in range(INITIAL_C_VALUE, 1000):
diff = 1000 - c
a = (diff) // 2
b = (diff - a)
sum_of_squares = a * a + b * b
c_squared = c * c
while sum_of_squares < c_squared:
a -= 1
b += 1
sum_of_squares = a * a + b * b
if sum_of_squares == c_squared:
print("{0}^2 + {1}^2 = {2}^2 = {3}".format(a, b, c, c_squared))
print("{0} + {1} + {2} = {3}".format(a, b, c, a + b + c))
print("abc = {0} * {1} * {2} = {3}".format(a, b, c, a * b * c))
return
# Sample Output:
# 200^2 + 375^2 = 425^2 = 180625
# 200 + 375 + 425 = 1000
# abc = 200 * 375 * 425 = 31875000
#
# Total running time for Problem9.py is 0.0004772338907904122 seconds
|
from abc import ABC, abstractmethod
class Clothes(ABC):
@abstractmethod
def fabric(self):
pass
class Coat(Clothes):
def __init__(self, V):
self.V = V
@property
def fabric(self):
return self.V / 6.5 + 0.5
class Suit(Clothes):
def __init__(self, H):
self.H = H
@property
def fabric(self):
return self.H * 2 + 0.3
my_c = Coat(5)
my_s = Suit(1.70)
print(my_c.fabric)
print(my_s.fabric)
|
class Cell:
def __init__(self, cell_cell):
self.cell_cell = cell_cell
def __add__(self, other):
if type(other) == Cell:
return Cell(self.cell_cell + other.cell_cell)
else:
print('Error: Not the Cell type')
def __sub__(self, other):
if type(other) == Cell:
if self.cell_cell - other.cell_cell > 0:
return Cell(self.cell_cell - other.cell_cell)
else:
return print('Error: Difference is less than zero')
else:
print('Error: Not the Cell type')
def __mul__(self, other):
if type(other) == Cell:
return Cell(self.cell_cell * other.cell_cell)
else:
print('Error: Not the Cell type')
def __floordiv__(self, other):
if type(other) == Cell:
return Cell(self.cell_cell // other.cell_cell)
else:
print('Error: Not the Cell type')
def __str__(self):
return f'{self.cell_cell}'
def make_order(self, num):
str = ''
for i in range(self.cell_cell):
str += '*'
if (i + 1) % num == 0:
str += '\n'
print(str)
a = Cell(15)
b = Cell(10)
print(a + b)
print(a - b)
print(a * b)
print(a // b)
a.make_order(4) |
def generator(list_a, list_b):
for i in range(0, len(list_a)):
if i <= len(list_b) - 1:
yield (list_a[i], list_b[i])
else:
yield (list_a[i], None)
tutors = ['Иван', 'Анастасия', 'Петр', 'Сергей', 'Дмитрий', 'Борис', 'Елена']
classes = ['9А', '7В', '9Б', '9В', '8Б']
# classes = ['9А', '7В', '9Б', '9В', '8Б', '10А', '10Б', '9А']
gen = generator(tutors, classes)
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
# print(next(gen)) #- здесь уже StopIteration
|
# creates random numbers/ matches, etc
# import random
# my_list=["Iram","Allyson","Dominique","Odie","Aidee","Oscar","Mom","Dad","Autumn","Marisa","Jr","Sinthia"]
# for i in range(10):
# x= random.choice(my_list)
# print (x)
import math
print (math)
|
# while True:
# line = input('> ')
# if line == "done":
# break
# print (line)
# print('Done')
largest = None
samllest = None
try:
while True:
num = input("Enter a number: ")
digit = int(num)
if digit == "done":
break
except:
print ("invalid Input")
|
def max_name_len(firstname, lastname):
print(f"The largest value of the length of my firstname and lastname is {max(len(firstname), len(lastname))}")
|
# If/ Else conditions are used to decide to do something based on something being true or false
x = 40
y = 40
# Comparison operators (==, !=, >, <, >=, <=) - Use to compare values
# Simple if
if x == y:
print(f'{x} is equal to {y}')
# Simple If/ else
if x > y:
print (f'{x} is greater than {y}')
else:
print(f'{x} is less than {y}')
# Else If
if x > y:
print (f'{x} is greater than {y}')
elif x == y:
print(f'{x} is equal to {y}')
else:
print(f'{x} is less than {y}')
# Nested If
if x > 2:
if x <= 10:
print(f'{x} is greater than 2 and less than or equal to 10')
# Logical operator (and, or, not) - Used to combine conditional statement
# and operator
if x > 2 and x <= 10:
print(f'{x} is greater than 2 and less than or equal to 10')
# or operator
if x > 2 or x <= 10:
print(f'{x} is greater than 2 or less than 10')
# not operator
if not x == y:
print(f'{x} is not equal to {y}')
# Membership Operators (not, not in) - Membership Operators are used to test if a
# sequence is presented in an object
number = [1, 2, 3, 4, 5]
# in operator
if x in number:
print(x in number)
if x not in number:
print(x not in number)
# Identity Operators (is, is not) - Compare the object, not if they are equal, but
# if they are actually the same object, with the same memory location
# is operator
if x is y:
print(x is y)
# is not operator
if x is not y:
print(x is not y)
|
res1 = int(input("Telefonou para a vítima? 1/Sim ou 0/Não: "))
res2 = int(input("Esteve no local do crime? 1/Sim ou 0/Não: "))
res3 = int(input("Mora perto da vítima? 1/Sim ou 0/Não: "))
res4 = int(input("Devia para a vítima? 1/Sim ou 0/Não: "))
res5 = int(input("Já trabalhou com a vítima? 1/Sim ou 0/Não: "))
soma = res1 + res2 + res3 + res4 + res5
if soma < 2:
print('Inocente')
elif soma == 2:
print('Suspeita')
elif 3 <= soma <= 4:
print('Cúmplice')
elif soma == 5:
print('Assassino')
|
import random
import string
import re
import argparse
def num_to_string(number, digit_assign):
for digit in digit_assign:
number = number.replace(digit, digit_assign[digit])
return number
# create testcases into 'into_file' file
# max_testcase: numbers testcase
# max_letter: maximum number of letter per word
# max_word: maximum number of word per testcase
# sign: '+'/'-' for testcase just include plus/subtract for level 1 and 2
# 'both' for testcase include both plus, subtract, bracket for level 3
# '*' for testcase just include multipy for level 4,
def generate_testcase(max_testcase, max_letter, max_word, sign):
tc = ''
for i in range(max_testcase):
word_size = random.randint(3, max_word)
numbers = []
for j in range(word_size - 1):
letter_size = random.randint(1, max_letter)
numbers.append(random.randint(
10 ** (letter_size - 1), 10 ** letter_size - 1))
if sign == '+':
numbers.append(sum(numbers))
elif sign == '-':
letter_size = random.randint(1, max_letter)
numbers.append(random.randint(
10 ** (letter_size - 1), 10 ** letter_size - 1))
numbers[0] = sum(numbers[1:])
elif sign == '*':
prod = 1
for number in numbers:
prod *= number
numbers.append(prod)
signs = []
if sign == 'both':
right = 0
for i in range(len(numbers)):
if random.choice([True, False]):
signs.append('+')
right += numbers[i]
else:
signs.append('-')
right -= numbers[i]
numbers.append(right)
if right >= 0:
signs.append('+')
else:
signs.append('-')
numbers = list(map(lambda x: str(abs(x)), numbers))
digits = set(''.join(numbers))
digit_assign = {}
letter_assign = {}
for digit in digits:
letter = random.choice(string.ascii_lowercase)
while letter_assign.get(letter) != None:
letter = random.choice(string.ascii_lowercase)
digit_assign[digit] = letter
letter_assign[letter] = digit
numbers = list(map(lambda x: num_to_string(x, digit_assign), numbers))
if sign != 'both':
tc += sign.join(numbers[:-1]) + '=' + numbers[-1] + '\n'
else:
t = ''
close_pos = -1
while close_pos < len(numbers) - 3:
if len(numbers) == 3:
if random.choice([True, False]):
open_pos = random.randint(
close_pos + 1, len(numbers) - 3)
else:
t += ('' if signs[0] ==
'+' else signs[0]) + numbers[0] + signs[1] + numbers[1]
close_pos += 1
continue
else:
open_pos = random.randint(close_pos + 1, len(numbers) - 3)
open_sign = signs[open_pos]
if open_pos == 0 and signs[0] == '+':
open_sign = ''
for i in range(close_pos + 1, open_pos):
t += ('' if i == 0 and signs[i] ==
'+' else signs[i]) + numbers[i]
t += open_sign + '(' + numbers[open_pos]
close_pos = open_pos + \
random.randint(1, len(numbers) - 2 - open_pos)
for i in range(open_pos + 1, close_pos):
t += signs[i] + numbers[i]
t += signs[close_pos] + numbers[close_pos] + ')'
t += '=' + (signs[-1] if signs[-1] == '-' else '') + numbers[-1]
tc += t + '\n'
return tc[:-1]
def read_input(filename='input.txt'):
raw_inps = open(filename, 'r').read().strip().split('\n')
symbols = set({'+', '-', '*', '=', ')', '('})
inps = []
for line in raw_inps:
pre_sign_pos = -1
cur_sign_pos = 0
is_sign_change = False
signs = []
inp = []
if (line[0] in string.ascii_letters or line[0] == '(') and (line[1] in string.ascii_letters or line[1] in symbols):
signs.append('+')
for i in range(len(line)):
c = line[i]
if c == '(' and i > 0 and line[i - 1] == '-':
is_sign_change = True
elif c == ')':
is_sign_change = False
if c in symbols:
cur_sign_pos = i
if pre_sign_pos + 1 < cur_sign_pos:
inp.append(line[pre_sign_pos + 1: cur_sign_pos])
pre_sign_pos = cur_sign_pos
if c != '=' and c != '(' and c != ')':
sign = c
if is_sign_change and c != '*':
sign = '-' if c == '+' else '+'
signs.append(sign)
if line[pre_sign_pos] == '=':
signs.append('+')
inp.append(line[pre_sign_pos + 1:])
inps.append((inp, signs))
return inps
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--range', type=str, help='range', default='3,5')
args = parser.parse_args()
opers = ['+', '-', 'both', '*']
rge = list(map(lambda x: int(x), args.range.split(',')))
rge[0] = 2 if rge[0] < 2 else rge[0]
rge[1] = 3 if rge[1] < 3 else rge[1]
word_rge = [rge[0], rge[1]]
word_rge[0] = 4 if word_rge[0] < 4 else word_rge[0]
word_rge[1] = 5 if word_rge[1] < 5 else word_rge[1]
all_tc = []
for oper in opers:
all_tc.append(generate_testcase(random.randint(
*rge), random.randint(*rge), random.randint(*word_rge), oper))
into_file = 'input.txt'
open(into_file, 'w').write('\n'.join(all_tc))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.