text
stringlengths 37
1.41M
|
---|
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
if x < 0:
return False
reversal = 0; left = x
while left > 0:
reversal = reversal*10 + left%10
left /= 10
return reversal == x
|
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
# Python trick
# 48ms
return str(int(num1) * int(num2))
# https://leetcode.com/discuss/50170/python-understand-solution-without-overflow-with-comments
# 400ms+
l1, l2 = len(num1), len(num2)
res = [0] * (l1+l2)
for i in xrange(l1-1, -1, -1):
carry = 0
for j in xrange(l2-1, -1, -1):
product = int(num1[i]) * int(num2[j]) + carry
# (i+1)+(j+1)-1
carry, res[i+j+1] = divmod(res[i+j+1] + product, 10)
# remain carry
res[i] += carry
res = ''.join(map(str, res)).lstrip('0')
return res if res else '0'
# https://leetcode.com/discuss/50707/simple-python-solution-18-lines
# reversed
# logic simplified
# 400ms+
res = [0] * (len(num1) + len(num2))
for i1, e1 in enumerate(reversed(num1)):
for i2, e2 in enumerate(reversed(num2)):
res[i1 + i2] += int(e1) * int(e2)
res[i1 + i2 + 1] += res[i1 + i2] / 10
res[i1 + i2] %= 10
res = ''.join(map(str, res[::-1])).lstrip('0')
return res if res else '0'
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {integer} sum
# @return {boolean}
def hasPathSum(self, root, sum):
# Recursive Solution
# if not root:
# return False
# if sum == root.val and not root.left and not root.right:
# return True
# hps = self.hasPathSum
# return hps(root.left, sum - root.val) or hps(root.right, sum - root.val)
# Iterative Solution
if not root:
return False
stack = [(root, sum)]
while stack:
node, sum = stack.pop()
if node.left is node.right is None and node.val == sum:
return True
if node.left:
stack.append((node.left, sum - node.val))
if node.right:
stack.append((node.right, sum - node.val))
return False
|
# 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 flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
# rcs
# 60ms
if not root:
return
self.flatten(root.left)
self.flatten(root.right)
tail = root.left
if tail:
while tail.right:
tail = tail.right
tail.right = root.right
root.right = root.left
root.left = None
# itr
# 48ms
if not root:
return
p = root
stack = []
while p:
if p.right:
stack.append(p.right)
if p.left:
p.left, p.right = None, p.left
else:
if not stack:
return
p.right = stack.pop()
p = p.right
# itr, dummy
# 60ms
if not root:
return
p = TreeNode(0)
stack = [root]
while stack:
node = stack.pop()
p.left, p.right = None, node
p = node # p.right
if p.right:
stack.append(p.right)
if p.left:
stack.append(p.left)
|
# 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 zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# itr, BFS
# 44ms
if not root:
return []
res, level = [], []
stack = [(root, 0)]
while stack:
node, depth = stack.pop(0)
if depth > len(res):
if depth%2 == 0: # if even, reverse the level above
level.reverse()
res.append(level)
level = []
level.append(node.val)
if node.left:
stack.append((node.left, depth+1))
if node.right:
stack.append((node.right, depth+1))
# add the last level
if len(res)%2 == 1: # if the last level is odd, reverse it
level.reverse()
res.append(level)
return res
# logic simplified
# 44ms
res, level = [], []
stack = [(root, 0)]
while stack:
node, depth = stack.pop(0)
if level and depth > len(res):
if depth%2 == 0:
level.reverse()
res.append(level)
level = []
if node:
level.append(node.val)
stack.append((node.left, depth+1))
stack.append((node.right, depth+1))
return res
# itr, BFS
stack, res = [root], []
while stack:
level = []
for _ in xrange(len(stack)):
node = stack.pop(0)
if node:
level.append(node.val)
stack.append(node.left)
stack.append(node.right)
if level:
level = level[::-1] if len(res)%2 else level
res.append(level)
return res
# itr, DFS
res, stack = [], [(root, 0)]
while stack:
node, level = stack.pop()
if node:
if len(res) == level:
res.append([])
if level%2 == 0:
res[level].append(node.val)
else:
res[level].insert(0, node.val)
stack.append((node.right, level+1))
stack.append((node.left, level+1))
return res
# rcs, DFS
# 48ms
res = []
self.dfs(root, 0, res)
return res
def dfs(self, root, level, res):
if root:
if len(res) < level + 1:
res.append([])
if level % 2 == 0:
res[level].append(root.val)
else:
res[level].insert(0, root.val)
self.dfs(root.left, level+1, res)
self.dfs(root.right, level+1, res)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} p
# @param {TreeNode} q
# @return {boolean}
def isSameTree(self, p, q):
if not p or not q:
return p == q
st = self.isSameTree
return p.val == q.val and st(p.left, q.left) and st(p.right, q.right)
# https://leetcode.com/discuss/36879/shortest-simplest-python
# The "proper" way:
# class Solution:
# def isSameTree(self, p, q):
# if p and q:
# return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
# return p == q
# The "tupleify" way:
# class Solution:
# def isSameTree(self, p, q):
# def t(n):
# return n and (n.val, t(n.left), t(n.right))
# return t(p) == t(q)
|
#!/usr/bin/python3
def load_input(path):
with open(path, "r") as file:
data = [x.strip() for x in file.readlines()]
return data
def puzzle(right, down):
x, y = (0, 0)
count = 0
for i in data:
x += right
y += down
if x >= len(i):
x -= len(i)
if y >= len(data):
return count
if data[y][x] == "#":
count += 1
if __name__ == '__main__':
data = load_input("./input")
print(f"Puzzle A: {puzzle(3, 1)}")
puzzle_b_product = puzzle(1, 1) * \
puzzle(3, 1) * \
puzzle(5, 1) * \
puzzle(7, 1) * \
puzzle(1, 2)
print(f"Puzzle B: {puzzle_b_product}")
|
import math
import unittest
def monte_carlo(n):
import random
inside_c=0
outside_c=0
for i in range (1,n+1):
point_x= random.random()
point_y=random.random()
print(point_x,point_y)
d= point_x**2+point_y**2
dist=d**0.5
print(dist)
if dist<=1:
inside_c=inside_c +1
outside_c=outside_c+1
print("Circle count Inside=", inside_c, "Outside=",outside_c)
ratio=inside_c/outside_c
return 4*ratio
def wallis(n):
sum=1
for i in range (1, n+1):
c1= 4*i*i
c2= c1-1
sum = sum * (c1/c2)
return 2*sum
class TestWallis(unittest.TestCase):
def test_low_iters(self):
for i in range(0, 5):
pi = wallis(i)
self.assertTrue(abs(pi - math.pi) > 0.15, msg=f"Estimate with just {i} iterations is {pi} which is too accurate.\n")
def test_high_iters(self):
for i in range(500, 600):
pi = wallis(i)
self.assertTrue(abs(pi - math.pi) < 0.01, msg=f"Estimate with even {i} iterations is {pi} which is not accurate enough.\n")
class TestMC(unittest.TestCase):
def test_randomness(self):
pi0 = monte_carlo(15000)
pi1 = monte_carlo(15000)
self.assertNotEqual(pi0, pi1, "Two different estimates for PI are exactly the same. This is almost impossible.")
self.assertFalse(abs(pi0 - pi1) > 0.05, "Two different estimates of PI are too different. This should not happen")
def test_accuracy(self):
for i in range(500, 600):
pi = monte_carlo(i)
self.assertTrue(abs(pi - math.pi) < 0.4, msg=f"Estimate with even {i} iterations is {pi} which is not accurate enough.\n")
if __name__ == "__main__":
unittest.main()
|
class RouteTrieNode:
def __init__(self, handler: str = None):
self.children = {}
self.handler = handler
def insert(self, path: str, handler: str=None):
self.children[path] = RouteTrieNode(handler)
# Trie structure to store routes and associated handlers
class RouteTrie:
def __init__(self,
root_handler: str,
not_found_handler: str):
self.root = RouteTrieNode(root_handler)
self.not_found_handler = not_found_handler
def insert(self,
path: str,
handler: str = None):
''' Inserts path one chunk at a time into the Trie
'''
# Start at the root node
node = self.root
# Iterate along supplied path
for p in path.split('/'):
# Filter out empty blocks
if p:
node.insert(p, self.not_found_handler)
node = node.children[p]
node.handler = handler
def find(self, path: str):
''' Traverse Route Trie, returning not_found_handler if path
does not exist
'''
node = self.root
# Traverse Trie
for p in path.split('/'):
if p:
if p in node.children.keys():
node = node.children[p]
else:
return self.not_found_handler
# Return handler if traversed to the end
return node.handler
# Wrapper class to handle input
class Router:
def __init__(self,
root_handler: str,
not_found_handler: str):
self.trie = RouteTrie(root_handler,
not_found_handler)
def add_handler(self, path: str, handler: str):
self.trie.insert(path, handler)
def lookup(self, path: str):
return self.trie.find(path)
if __name__ == '__main__':
# Create the router and add a route
router = Router(root_handler="root handler",
not_found_handler="not found handler")
router.add_handler(path="/home/about",
handler="about handler")
print(router.lookup("/")) # Should print 'root handler'
print(router.lookup("/home")) # Should print 'not found handler'
print(router.lookup("/home/about")) # Should print 'about handler'
print(router.lookup("/home/about/")) # Should print 'about handler'
print(router.lookup("/home/about/me")) # Should print 'not found handler'
|
# ###List Comprehensions
print(list(range(1,11)))
L = []
for i in range(1, 11):
L.append(i * i)
print(L)
# OR
newL = [ x * x for x in range(1, 11) if x % 2 == 0]
print(newL)
S = [m + n for m in 'ABC' for n in 'DEF']
print(S)
import os # 导入os模块
fileName = [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
print(fileName)
# for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value
D = {'x': 'A', 'y': 'B', 'z': 'C'}
for key, value in D.items():
print(key, ': ', value)
# 因此,列表生成式也可以使用两个变量来生成list
dl = [key+ ': '+ value for key, value in D.items()]
print(dl)
sl = ['Hello', 'World', 'IBM', 'Apple']
sll = [s.lower() for s in sl]
print(sll)
# -*- coding: utf-8 -*-
# Task
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [l.lower() for l in L1 if isinstance(l,str)]
# 测试:
print(L2)
if L2 == ['hello', 'world', 'apple']:
print('测试通过!')
else:
print('测试失败!')
|
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if intervals is None or len(intervals) < 0:
return []
intervals = sorted(intervals, key = lambda x: x[0])
merged = []
merged.append(intervals[0])
for i in range(1, len(intervals)):
last = merged[-1]
if last[1] >= intervals[i][0]:
last[1] = max(last[1], intervals[i][1])
else:
merged.append(intervals[i])
return merged
|
#!/usr/bin/env python3
"""
Print out the URLs in a tweet json stream.
"""
from __future__ import print_function
import json
import fileinput
for line in fileinput.input():
tweet = json.loads(line)
for url in tweet["entities"]["urls"]:
if "unshortened_url" in url:
print(url["unshortened_url"])
elif url.get("expanded_url"):
print(url["expanded_url"])
elif url.get("url"):
print(url["url"])
|
#!/usr/bin/env python3
"""
A program to filter tweets that contain links to a web archive. At the moment it
supports archive.org and archive.is, but please add more if you want!
"""
import json
import fileinput
archives = ["archive.is", "web.archive.org", "wayback.archive.org"]
for line in fileinput.input():
tweet = json.loads(line)
for url in tweet["entities"]["urls"]:
done = False
for host in archives:
if host in url["expanded_url"]:
print(line, end="")
done = True
# prevent outputting same data twice if it contains
# multiple archive urls
if done:
break
|
#!/usr/bin/env python
"""
Prints out the tweet ids and counts of most retweeted.
"""
from __future__ import print_function
import json
import optparse
import fileinput
from collections import defaultdict
def main():
parser = optparse.OptionParser()
options, argv = parser.parse_args()
counts = defaultdict(int)
for line in fileinput.input(argv):
try:
tweet = json.loads(line)
except:
continue
if "retweeted_status" not in tweet:
continue
rt = tweet["retweeted_status"]
id = rt["id_str"]
count = rt["retweet_count"]
if count > counts[id]:
counts[id] = count
for id in sorted(counts, key=counts.get, reverse=True):
print("{},{}".format(id, counts[id]))
if __name__ == "__main__":
main()
|
#================================================================
# 简单的Numpy程序
#----------------------------------------------------------------
# import numpy as np
# # 数组
# x1d = np.array([4,23,565])
# print(x1d)
# x2d = np.array(((1,2,3),(4,4,4),(7,7,7)))
# print(x2d)
# x = np.array([4,5,6])
# y = np.array([1,2,3])
# print(x+y)
# print(x*y)
# print(x-y)
# print(x/y)
# print(x%y)
# # matrix子类可进行矩阵运算
# x1 = np.array(((1,2,3),(1,2,3),(1,2,3)))
# x2 = np.array(((1,2,3),(1,2,3),(1,2,3)))
# print('First 2-D Array: x1')
# print(x1)
# print('Second 2-D Array: x2')
# print(x2)
# print('Array Multiplication') # 数组乘法:对应位置上的元素相乘
# print(x1*x2)
# mx1 = np.matrix(((1,2,3),(1,2,3),(1,2,3)))
# mx2 = np.matrix(((1,2,3),(1,2,3),(1,2,3)))
# print('Matrix Multiplication') # 矩阵乘法
# print(mx1*mx2)
# # 简单的统计函数
# xt = np.random.randn(10) # 创建一个有10个随机元素的数组
# print(xt)
# mean = xt.mean()
# print(mean)
# std = xt.std()
# print(std)
# var = xt.var()
# print(var)
#----------------------------------------------------------------
#================================================================
# Scipy做统计 stats.describe
#----------------------------------------------------------------
# import scipy as sp
# import scipy.stats as st
# s = sp.randn(10)
# n, min_max, mean, var, skew, kurt = st.describe(s)
# print('Number of elements:', n)
# print('Minimum:', min_max[0], ' Maximum:', min_max[1])
# print('Mean:', mean)
# print('Variance:', var)
# print('Skewness:', skew)
# print('Kurtosis:', kurt)
#----------------------------------------------------------------
#================================================================
# Scipy优化函数 Rosenbrock的非凸函数用于检验优化算法的性能
#----------------------------------------------------------------
# import numpy as np
# from scipy.optimize import minimize
# # 定义Rosenbrock函数
# def rosenbrock(x):
# return sum(100*(x[1:]-x[:-1]**2)**2 + (1-x[:-1])**2)
# x0 = np.array([1, 0.7, 0.8, 2.9, 1.1])
# res = minimize(rosenbrock, x0, method = 'nelder-mead', options = {'xtol':1e-8, 'disp':True})
# print(res.x)
#----------------------------------------------------------------
#================================================================
# Scipy图像处理
#----------------------------------------------------------------
# from scipy import misc
# import matplotlib.pyplot as plt
# # 显示图片
# l = misc.face()
# plt.gray()
# plt.imshow(l)
# plt.show()
#----------------------------------------------------------------
#================================================================
# Scipy图像的几何变换
#----------------------------------------------------------------
# import scipy
# from scipy import ndimage
# import matplotlib.pyplot as plt
# import numpy as np
# lena = scipy.misc.imread('lena512.bmp')
# lx, ly = lena.shape
# crop_lena = lena[lx//4:-lx//4, ly//4:-ly//4]
# crop_eyes_lena = lena[lx//2:int(-lx/2.2), int(ly//2.1):int(-ly/3.2)]
# rotate_lena = ndimage.rotate(lena, 45)
# # 四幅图 返回二维数组
# f, axarr = plt.subplots(2, 2)
# axarr[0,0].imshow(lena, cmap=plt.cm.gray)
# axarr[0,0].axis('off')
# axarr[0,0].set_title('Original Lena Image')
# axarr[0,1].imshow(crop_lena, cmap=plt.cm.gray)
# axarr[0,1].axis('off')
# axarr[0,1].set_title('Cropped Lena')
# axarr[1,0].imshow(crop_eyes_lena, cmap=plt.cm.gray)
# axarr[1,0].axis('off')
# axarr[1,0].set_title('Lena Cropped Eyes')
# axarr[1,1].imshow(rotate_lena, cmap=plt.cm.gray)
# axarr[1,1].axis('off')
# axarr[1,1].set_title('45 Degree Rotated Lena')
# plt.show()
#----------------------------------------------------------------
#================================================================
# Sympy 基础符号操作
#----------------------------------------------------------------
# import sympy
# a = sympy.Symbol('a')
# b = sympy.Symbol('b')
# c = sympy.Symbol('c')
# e = (a*b*b+2*b*a*b)+(a*a+c*c)
# print(e)
#----------------------------------------------------------------
#================================================================
# Sympy 表达式拓展
#----------------------------------------------------------------
# import sympy
# a = sympy.Symbol('a')
# b = sympy.Symbol('b')
# e = (a+b)**4
# print(e)
# print(e.expand())
#----------------------------------------------------------------
#================================================================
# Sympy 表达式或公式的简化
#----------------------------------------------------------------
# import sympy
# import math
# x = sympy.Symbol('x')
# a = 1/x+(x*sympy.exp(x)-1)/x
# print(sympy.simplify(a))
# print(sympy.simplify((x**3+x**2-x-1)/(x**2+2*x+1)))
#----------------------------------------------------------------
#================================================================
# Sympy 简单的积分
#----------------------------------------------------------------
# import sympy
# from sympy import integrate
# x = sympy.Symbol('x')
# print(integrate(x**3+2*x**2+x,x))
# print(integrate(x/(x**2+2*x),x))
#----------------------------------------------------------------
#================================================================
# 数据分析和可视化示例
#----------------------------------------------------------------
# import pandas as pd
# import datetime
# import pandas_datareader.data as pdr
# # 将C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas_datareader
# # 下的fred.py文件中的pandas.core.common import is_list_like修改为pandas.api.types import is_list_like
# import fix_yahoo_finance as yf
# yf.pdr_override() #需要调用这个函数
# start = datetime.datetime(2014,10,1)
# end = datetime.datetime(2014,12,30)
# apple = pdr.get_data_yahoo('AAPL', start, end)
# print(apple.head())
# apple.to_csv('apple-data.csv')
# df = pd.read_csv('apple-data.csv', index_col='Date', parse_dates=True)
# print(df.head())
#----------------------------------------------------------------
#================================================================
# 二维图像
#----------------------------------------------------------------
# import pandas as pd
# import matplotlib.pyplot as plt
# df = pd.read_csv('apple-data.csv', index_col="Date", parse_dates=True)
# df['H-L'] = df.High - df.Low
# df['50MA'] = df['Close'].rolling(50).mean()
# df[['Open','High','Low','Close','50MA']].plot()
# plt.show()
#----------------------------------------------------------------
#================================================================
# 三维图像
#----------------------------------------------------------------
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
df = pd.read_csv('apple-data.csv', parse_dates=True)
df['H-L'] = df.High - df.Low
df['50MA'] = df['Close'].rolling(50).mean()
threedee = plt.figure().gca(projection='3d')
threedee.scatter(df.index, df['H-L'], df['Close'])
threedee.set_xlabel('Index')
threedee.set_ylabel('H-L')
threedee.set_zlabel('Close')
plt.show()
#----------------------------------------------------------------
#================================================================
#
#----------------------------------------------------------------
#----------------------------------------------------------------
|
###################################
#thus reverse a string
def rev(s): return s[::-1]
# this asks a question and return the answer.takes whether new line or not
def get_answer(s, newline):
if newline:
print(s)
return (input())
else:
return(input(s))
# this asks a question and return the answer (ask in new line)
def get_answers(s): return (get_answer(s, True))
# function to check if a string is an int or not
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
###################################
|
'''
a=["a","b","c","d","100","jjj"]
print(a)
b[0]=a[4]
b[1]=a[3]
b[2]=a[2]
b[3]=a[1]
b[4]=a[0]
'''
def rinurev(a):
size = len(a)
b=[None] *size
for i in range(size):
idx = size-(i+1)
#print (i, idx)
b[i] = a[idx]
return b
'''
c=list(reversed(a))
c.append("rinu")
c.append(a)
print(c)
'''
|
def nested_sum(L):
sum=0
for i in L1:
if isinstance(i,int):
sum+=i
else:
sum+=nested_sum(i)
return sum
|
#To build an application to classify the patients to be healthy or suffering from
#cardiovascular disease based on the given attributes.
#import numpy as np
"""
HACKATHON
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df=pd.read_excel('D:/Data/cardio_train.xlsx')
df.head()
df.info()
df.describe().T
df.isnull().sum()
#coverting date into year
df['age'] = df['age']/360
#df['age'] = pd.to_numeric(df['age'], downcast='float')
df['age'] = df['age'].astype(int)
df['age'].head()
df['height'] = df['height']/100
df['height1'] = df['height'] * df['height']
df['BMI'] = df['weight'] / df['height1']
#weight/meter^2 kg/m^2
df.head()
df.BMI.value_counts()
df.age.value_counts()
df.height.value_counts()
df.weight.value_counts()
df.ap_lo.value_counts()
df.ap_hi.value_counts()
#visual for outliers
sns.boxplot(x=df['ap_lo'])
"""
Z-Score-
Wikipedia Definition
The Z-score is the signed number of standard deviations by which the value
of an observation or data point is above the mean value of
what is being observed or measured.
"""
from scipy import stats
z = np.abs(stats.zscore(df))
print(z)
"""
Looking the code and the output above, it is difficult to say
which data point is an outlier. Let’s try and define a
threshold to identify an outlier.
"""
threshold = 3
print(np.where(z > 3))
#interquartile range (IQR)## INTERQUARTILE RANGE............
Q1 = df.quantile(0.25)
Q3 = df.quantile(0.75)
IQR = Q3 - Q1
print(IQR)
"""
The below code will give an output with some true and false values.
The data point where we have False that means these values
are valid whereas True indicates presence of an outlier.
"""
print(df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))
"""
Working with Outliers: Correcting, Removing
"""
df = df[(z < 3).all(axis=1)]
df.cardio.value_counts()
df.head()
df.ap_hi.value_counts()
df.describe()
df['smo_alc'] = df['smoke'] + df['alco']
7.#Cholesterol /| 1: normal, 2: above normal, 3: well above normal |
8.#Glucose /| 1: normal, 2: above normal, 3: well above normal |
df['chlo_glu'] = df['cholesterol'] + df['gluc']
df['all_SACG'] = df['smo_alc'] + df['chlo_glu']
"""
Body Mass Index Chart .
Weight Status Body Mass Index
Underweight Below 18.5
Normal 18.5 to 24.9
Overweight 25.0 to 29.9
Obese 30.0 and Above
"""
#AS DATA IN FORM HAVING NO MISSING VALUE
#CHECKING THE OUTLIERS
df.info()
"""
EXPLORATORY DATA ANALYSIS
"""
#univariate and multi-variate analysis.
sns.countplot(df.BMI)
#
##
###
####Analysing the variable AGE AND CARDIO
sns.FacetGrid(df,hue = 'cardio',size=10).map(sns.distplot,'age').add_legend()
df.info()
sns.FacetGrid(df,hue = 'cardio',size=10).map(sns.distplot,'all_SACG').add_legend()
sns.distplot(df['BMI'], kde=False)
plt.hist(df.age)
plt.boxplot(df['BMI'])
#Creating age group in AGE columns as AGING
#df.loc[(df['age'] <= 12), 'Aging'] = '0-12'
#df.loc[((df['age'] >= 12) & (df['age'] <= 24)) , 'Aging'] = '12-24'
#df.loc[((df['age'] >= 24) & (df['age'] <= 48)) , 'Aging'] = '22-48'
#df.loc[((df['age'] >= 48) & (df['age'] <= 60)) , 'Aging'] = '48-60'
#df.loc[((df['age'] >= 60) & (df['age'] <= 70)) , 'Aging'] = '60-70'
df.head(4)
# ***Where | 1: normal, 2: above normal, 3: well above normal |
#sns.countplot(df.ap_hi)
df['ap_hi'].value_counts().head(10).plot.bar()
df['ap_hi'].plot.hist()
## Joint plots shows bivariate scatterplots
# And univariate histograms
sns.jointplot(x=df.age, y=df.cardio, kind="kde", data = df)
#plotting pairplot MULTIVARIATE ANALYSIS
sns.pairplot(df,hue = 'cardio', size =3)
df.info()
#sns.boxplot(x='age', y='cardio', data=df)
#plt.show()
#multivaiate analysis
"""
VIF =Variation Inflation Factor
"""
# Import library for VIF
from statsmodels.stats.outliers_influence import variance_inflation_factor
def calculate_vif_(X):
'''X - pandas dataframe'''
thresh = 5.0
variables = range(X.shape[1])
for i in np.arange(0, len(variables)):
vif = [variance_inflation_factor(X[variables].values, ix) for ix in range(X[variables].shape[1])]
print(vif)
maxloc = vif.index(max(vif))
if max(vif) > thresh:
print('dropping \'' + X[variables].columns[maxloc] + '\' at index: ' + str(maxloc))
del variables[maxloc]
print('Remaining variables:')
print(X.columns[variables])
return X
corr = df.corr()
sns.set_context("notebook", font_scale=0.5, rc={"lines.linewidth": 2.5})
plt.figure(figsize=(14,10))
a = sns.heatmap(corr, annot=True,cmap='coolwarm')
rotx = a.set_xticklabels(a.get_xticklabels(), rotation=90)
roty = a.set_yticklabels(a.get_yticklabels(), rotation=30)
df.info()
#remove the high multicollinearity variable
df.drop(['height1'],axis=1, inplace = True)
df.drop(['id'],axis=1, inplace = True)
df.drop(['cholesterol','gluc','smoke','alco','smo_alc','chlo_glu'],axis=1,inplace = True)
#df.drop([''])
df.info()
#train and test splitting
from sklearn.model_selection import train_test_split
X = df.drop('cardio',axis=1)
y = df['cardio']
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2,random_state=150)
# We'll need some metrics to evaluate our models
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.model_selection import cross_val_score
# Random Forest
#--------------
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators=250)
classifier.fit( X_train, y_train )
y_pred = classifier.predict( X_test )
print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
print(accuracy_score(y_test, y_pred))
cm = confusion_matrix( y_test, y_pred )
print("Accuracy on Test Set for RandomForest = %.2f" % ((cm[0,0] + cm[1,1] )/len(X_test)))
scoresRF = cross_val_score( classifier, X_train, y_train, cv=80)
print("Mean RandomForest CrossVal Accuracy on Train Set %.2f, with std=%.2f" % (scoresRF.mean(), scoresRF.std() ))
# Logistic Regression
#--------------
from sklearn.linear_model import LogisticRegression
classifier2 = LogisticRegression()
classifier2.fit( X_train, y_train )
y_pred = classifier2.predict( X_test )
cm = confusion_matrix( y_test, y_pred )
print("Accuracy on Test Set for LogReg = %.2f" % ((cm[0,0] + cm[1,1] )/len(X_test)))
scoresLR = cross_val_score( classifier2, X_train, y_train, cv=10)
print("Mean LogReg CrossVal Accuracy on Train Set %.2f, with std=%.2f" % (scoresLR.mean(), scoresLR.std() ))
|
# FILE: star_wars_adventure_creator.py
# DATE: 2018-11-26
# AUTHOR: Austin Gee
# DESCRIPTION: This is my Final project. It is a menu driven program. Before it
# all starts the program checks to see if the record containing files exist and
# then if they do not the program creates them. Using the menu the user can add
# new records to the files, edit records in the files and deactivate records in
# the various files. There is also a feature called the adventure creator. This
# feature asks the user for a file name and a couple of numbers. It then
# randomly creates the bare bones for an adventure using at least one record
# from each file.
# import various modules
import get_lists
import append_records
import add_this_to_file
import create_files
import deactivate_record
import menu
def main():
# Program Title, subtitle, and and description
title = '****************Star Wars: Force and Destiny****************'
subtitle = '****************Unofficial Adventure Creator****************'
program_description = ('\nThis program is a tool that was created to help Game Masters\n'
'running the Star Wars: Force and Destiny roleplaying game to\n'
'create new adventures. It does this by randomly generating a\n'
'list of enemies, locations, quest items, and motivations for\n'
'the Game Master to incorporate into their adventure. Of course\n'
'before any adventure can be created there needs to be at least\n'
'one record in each of the six files used to store Minions,\n'
'Rivals, Nemeses, Locations, Quest Items, and Motivations.\n'
'Enjoy!!!')
# The following loose prompts and messages are all general prompts that are not used
# in any lists and may be used by more than one function
# prompt to continue past the title page
enter_to_continue = '\nPress Enter to Continue: '
# prompt used if no value is entered
need_value = 'Please enter a value.'
need_name = 'Please enter a name.'
# add again prompt and delete again prompt
add_again_prompt = 'Do you want to add some more?(y or n):'
del_again_prompt = 'Do you want to delete some more?(y or n):'
# deactivate record prompt
deactivate_record_prompt = 'Type the name of the record you want to delete: '
# item not found message
not_found = 'The item you searched for was not found'
# Menu prompt
menu_prompt = 'Please make a selection: '
# must have a file error message
must_have_file = '\nError: You must have at least one record in every file.'
# please enter your choice message
enter_choice = 'Please enter a menu choice.'
# Titles for various displayed tables
min_title = 'Minions'
riv_title = 'Rivals'
nem_title = 'Nemeses'
loc_title = 'Locations'
q_i_title = 'Quest Items'
mot_title = 'Motivations'
# List of titles for various displayed tables
title_list = [min_title, riv_title, nem_title,
loc_title, q_i_title, mot_title]
# csv file names
minions_file = 'minions.csv'
rivals_file = 'rivals.csv'
nemeses_file = 'nemeses.csv'
locations_file = 'locations.csv'
quest_items_file = 'quest_items.csv'
motivations_file = 'motivations.csv'
#csv file name list
file_name_list = [minions_file, rivals_file, nemeses_file,
locations_file, quest_items_file, motivations_file]
# csv deactivated record dump files
minions_dump_file = 'minion_dump.csv'
rivals_dump_file = 'rivals_dump.csv'
nemeses_dump_file = 'nemeses_dump.csv'
locations_dump_file = 'locations_dump.csv'
quest_items_dump_file = 'quest_items_dump.csv'
motivations_dump_file = 'motivations_dump.csv'
# csv dump file list
dump_file_list = [minions_dump_file, rivals_dump_file, nemeses_dump_file,
locations_dump_file, quest_items_dump_file,
motivations_dump_file]
# File Headers
enemy_header = [['Name', 'Type']]
location_header = [['Name', 'Solar System', 'Galactic Location', 'Location Type']]
quest_item_header = [['Name', 'Type', 'Effect']]
motivation_header = [['Name', 'Category', 'Description']]
# File header list
header_list = [enemy_header, location_header, quest_item_header, motivation_header]
# Add record prompts
enemy_add_name_prompt = 'Enter a new name: '
enemy_add_type_prompt = 'Enter the type: '
location_add_name_prompt = 'Enter a new name: '
location_add_sol_sys_prompt = 'Enter the solar system: '
location_add_gal_loc_prompt = 'Enter the galactic location: '
location_add_loc_type_prompt = 'Enter location type: '
quest_item_add_name_prompt = 'Enter a new name: '
quest_item_add_type_prompt = 'Enter the type: '
quest_item_add_effect_prompt = 'Enter quest item effect: '
motivation_add_name_prompt = 'Enter a new name: '
motivation_add_category_prompt = 'Enter the category: '
motivation_add_description_prompt = 'Enter the description: '
# Add record list made from add record prompts
add_rec_prompt_list = [enemy_add_name_prompt, enemy_add_type_prompt, location_add_name_prompt,
location_add_sol_sys_prompt, location_add_gal_loc_prompt,
location_add_loc_type_prompt, quest_item_add_name_prompt,
quest_item_add_type_prompt, quest_item_add_effect_prompt,
motivation_add_name_prompt, motivation_add_category_prompt,
motivation_add_description_prompt]
# Name Prompts for edit file functions
edit_minion_name = 'Name of Minion you want to change: '
edit_rival_name = 'Name of Rival you want to change: '
edit_nemesis_name = 'Name of Nemesis you want to change: '
edit_location_name = 'Name of the Location you wish to change?: '
edit_quest_item_name = 'Name of the Quest Item you want to change: '
edit_motivation_name = 'Name of the Motivation you want to change: '
# Name prompts list for edit file
edit_records_list_name = [edit_minion_name, edit_rival_name, edit_nemesis_name,
edit_location_name, edit_quest_item_name,
edit_motivation_name]
# Type and category prompts for edit file functions
new_enemy_type = 'Enter new Enemy type: '
new_system = 'Enter new Solar System: '
new_gal_loc = 'Enter new Galactic location: '
new_loc_type = 'Enter new location type: '
new_quest_item_type = 'Enter new Quest Item type: '
new_quest_item_effect = 'Enter new Quest Item effect: '
new_motivation_category = 'Enter new Motivation Category: '
new_motivation_description = 'Enter new Motivation Description: '
# Type and category prompts for edit file functions list
edit_type_prompts = [new_enemy_type, new_system, new_gal_loc, new_loc_type, new_quest_item_type,
new_quest_item_effect, new_motivation_category, new_motivation_description]
# Edit record yes and no prompts
edit_enemy_type_prompt = 'Do you want to change the enemy Type?(y or n): '
edit_system_prompt = 'Do you want to Change the Solar System field?(y or n): '
edit_gal_loc_prompt = 'Do you want to change the Galactic Location field?(y or n): '
edit_loc_type_prompt = 'Do you want to change the Location Type field?(y or n): '
edit_quest_item_type_prompt = 'Do you want to change the Quest Item type?(y or n): '
edit_quest_item_effect_prompt = 'Do you want to change the Quest Item Effect?(y or n): '
edit_motivation_category_prompt = 'Do you want to change the Motivation Category?(y or n): '
edit_motivation_description_prompt = 'Do you want to change the Motivation Description?(y or n): '
# Edit record yes and no prompts list
edit_record_prompt_list = [edit_enemy_type_prompt, edit_system_prompt, edit_gal_loc_prompt,
edit_loc_type_prompt, edit_quest_item_type_prompt,
edit_quest_item_effect_prompt, edit_motivation_category_prompt,
edit_motivation_description_prompt]
# adventure creator prompts
min_prompt = 'Enter the amount of Minions you want in the adventure: '
riv_prompt = 'Enter the amount of Rivals you want in the adventure: '
enter_a_number = 'Please enter a whole number'
file_prompt = 'What name do you want to use as a file name: '
min_message = 'Minion: '
riv_message = 'Rival: '
nem_message = 'Nemesis: '
loc_message = 'Location: '
q_i_message = 'Quest Item: '
mot_message = 'Motive: '
# adventure creator prompts list
adv_cr_list = [min_prompt, riv_prompt, enter_a_number, file_prompt, min_message,
riv_message, nem_message, loc_message, q_i_message, mot_message]
# Main Menu choices
add_to_file = '1) Add a record to an existing file'
edit_record_in_file = '2) Edit an existing record in a file'
delete_record = '3) Delete a record from an existing file'
create_adventure_file = '4) create an adventure file'
quit_program = '5) quit program'
# Main Menu choices list
main_menu_choices = [add_to_file, edit_record_in_file,
delete_record, create_adventure_file, quit_program]
# Add record to a file menu choices
add_to_minion_record = '1) Add a record to the Minion file'
add_to_rival_record = '2) Add a record to the Rival file'
add_to_nemeses_record = '3) Add a record to the Nemesis file'
add_to_location_record = '4) Add a record to the Location file'
add_to_quest_item_record = '5) Add a record to the Quest Item file'
add_to_motivation_record = '6) Add a record to the Motitvation file'
add_to_return = '7) Return to main menu'
# Add record to a file menu choices list
add_record_list = [add_to_minion_record, add_to_rival_record, add_to_nemeses_record,
add_to_location_record, add_to_quest_item_record,
add_to_motivation_record, add_to_return]
# Edit a record in a file menu choices
edit_minion_record = '1) Edit Minion record'
edit_rival_record = '2) Edit Rival record'
edit_nemesis_record = '3) Edit Nemesis record'
edit_location_record = '4) Edit location record'
edit_quest_item_record = '5) Edit Quest Item record'
edit_motivation_record = '6) Edit Motivation record'
edit_return = '7) Return to main menu'
# Edit record menu choices list
edit_menu_choices = [edit_minion_record, edit_rival_record, edit_nemesis_record,
edit_location_record, edit_quest_item_record,
edit_motivation_record, edit_return]
# Deactivate record menu choices
deactivate_minion_record = '1) Deactivate a record from the Minion file'
deactivate_rival_record = '2) Deactivate a record from the Rival file'
deactivate_nemesis_record = '3) Deactivate a record from the Nemesis file'
deactivate_location_record = '4) Deactivate a record from the Location file'
deactivate_quest_item_record = '5) Deactivate a record from the Quest Item file'
deactivate_motivation_record = '6) Deactivate a record from the Motivation file'
deactivate_return = '7) Return to main menu'
# Deactivate record menu choices list
deactivate_menu_list = [deactivate_minion_record, deactivate_rival_record,
deactivate_nemesis_record, deactivate_location_record,
deactivate_quest_item_record, deactivate_motivation_record,
deactivate_return]
# Adventure Creator menu choices
adv_create = '1) Create new Adventure'
adv_return = '2) Return to main menu'
# Adventure Creator menu choices list
adv_cr_menu = [adv_create, adv_return]
# messages if there are no files found
no_minions_file = 'Creating Minions file...'
no_rivals_file = 'Creating Rivals file...'
no_nemeses_file = 'Creating Nemeses file...'
no_locations_file = 'Creating locations file...'
no_quest_items_file = 'Creating Quest Items file...'
no_motivations_file = 'Creating Motivations file...'
# List of messages if there are no files found
no_file_list = [no_minions_file, no_rivals_file, no_nemeses_file, no_locations_file,
no_quest_items_file, no_motivations_file]
print(title, '\n', subtitle, sep ='')
print(program_description)
input(enter_to_continue)
menu_done = False
while menu_done == False:
# create lists from .csv files, and creates new files if
# there are no files already created
minions = get_lists.get_min_list(no_file_list, file_name_list)
rivals = get_lists.get_riv_list(no_file_list, file_name_list)
nemeses = get_lists.get_nem_list(no_file_list, file_name_list)
locations = get_lists.get_loc_list(no_file_list, file_name_list)
quest_items = get_lists.get_q_i_list(no_file_list, file_name_list)
motivations = get_lists.get_mot_list(no_file_list, file_name_list)
#create master list of lists that are created from the csv files
master_list = [minions, rivals, nemeses, locations, quest_items, motivations]
# Prints the main menu as 5 individual choices
menu.print_main_menu(main_menu_choices)
# Input for making the menu choice
token = input('\n' + menu_prompt)
# Choice 1 that lets the user add a new record to a file
if token == '1':
menu.add_record_to_file(master_list, add_record_list, add_rec_prompt_list,
add_again_prompt, file_name_list, header_list,
need_name, menu_prompt, title_list,
enter_choice)
# Choice 2 that lets the user edit a record in a file
elif token == '2':
menu.edit_file(master_list, edit_menu_choices, edit_records_list_name,
edit_type_prompts, header_list, edit_record_prompt_list,
file_name_list, not_found, menu_prompt, title_list,
enter_choice)
# Choice 3 that lets the user deactivate a record into a dump
# file
elif token == '3':
menu.deactivate_records(master_list, deactivate_menu_list, header_list,
file_name_list, dump_file_list, deactivate_record_prompt,
del_again_prompt, not_found, menu_prompt, title_list,
enter_choice)
# Choice 4 that lets the user createan adventure and define a name for
# for a new adventure file
elif token == '4':
menu.create_adventure(master_list, adv_cr_list, adv_cr_menu, menu_prompt,
must_have_file, enter_choice)
# Choice 5 that lets the user end the program
elif token == '5':
menu_done = True
# If the user doesnt make a choice from 1 through 5
else:
print(enter_choice)
main()
|
import matplotlib as mpl
class Controller:
def __init__(self, artist):
self.artist = artist
if not isinstance(artist, mpl.backend_bases.Artist):
raise TypeError("artist must be a Matplotlib artist")
self.bindings = {}
event = None
binding = None
while True:
print(
"Welcome to the Fovea controller interface!\n"
"This dynamic, interactive class allows you to bind\n"
"events of your choice to behavior in the Matplotlib window.\n"
"To start, enter the key or word to which you would like to bind\n"
"to Matplotlib/Fovea behavior. For mouse buttons enter one of\n"
" 1. <LeftClick>\n"
" 2. <RightClick>\n"
"To exit the controller interface while saving all current bindings,\n"
"type 'exit'.\n"
)
event = input()
if event == "exit":
break
print("Please enter the Matplotlib function call to be bound.")
binding = input()
if binding == "exit":
break
self.bindings[event] = binding
|
# Create three variables in a single a line and assign different values to them
# and make sure their data types are different. Like one is int, another one is float and the last one is a string
x=10;y=7.5;z="Hello"
print("The integer value is ", x, "and the float value is", y,"and the string value is", z)
|
# Write a program in Python to perform the following operator based task:
# ● Ask user to choose the following option first:
# ○ If User Enter 1 - Addition
# ○ If User Enter 2 - Subtraction
# ○ If User Enter 3 - Division
# ○ If USer Enter 4 - Multiplication
# ○ If User Enter 5 - Average
# ● Ask user to enter the 2 numbers in a variable for first and second for the first 4 options mentioned above.
# ● Ask user to enter two more numbers as first1 and second2 for calculating the average as soon as user choose an option 5.
# ● At the end if the answer of any operation is Negative print a statement saying “zsa”
# ● NOTE: At a time user can perform one action at a time.
x=int(input("Enter any number between1-5 Enter 1 - Addition.. Enter 2 - Subtraction..Enter 3 - Division.. Enter 4 - Multiplication..Enter 5 - Average:"))
var1=int(input("Enter the 1st number: "))
var2=int(input("Enter the 2nd number: "))
if x==1:
res = var1+var2
print(res)
if x==2:
print(var1-var2)
if x==4:
print(var1*var2)
if x==3:
print(var1/var2)
if x==5:
first1=int(input("Enter one more number "))
second2=int(input("Enter one last number "))
print((var1+var2+first1+second2)/4)
|
#!/usr/bin/python
if __name__ == "__main__":
nfood = open("non_food_items_jugaad.txt", "r")
food = open("food_items_jugaad.txt", "r")
count = 0
total = 0
for line in nfood:
count += 1
total += len(line)
avg = float(total)/count
print "nfood avg", avg
count = 0
total = 0
avg = 0
for line in food:
count += 1
total += len(line)
avg = float(total)/count
print "food avg", avg
nfood.close()
food.close()
|
# Design a store using OOP methodologies
from classes import Latlon
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name}, costs ${self.price}"
class Department:
# products will be list of tuples with signature (string, int)
def __init__(self, name):
self.name = name
self.products = [Product(p[0], p[1]) for p in products]
def __str__(self):
return f"No products available in the {self.name} department, yet."
# what does the store look like
# what attributes
# name
# location
# categories of products
# products
class Store:
def __init__(self, name, lat, lon, categories):
self.name = name
self.location = Latlon(lat, lon)
self.departments = [Departments(d) for d in departments]
# add an __str__ method so that we can observe our Store instance
def __str__(self):
return f"Store {self.name}, {self.location}, {self.departments}"
store = Store("LambdaStore", 44.13544, -121.123124, ["Clothing", "Cookware", "Books", "Sporting Goods"])
print(store)
# we want to add departments
# let's take input grom the user and have themspecify departments by the department's
# index in the departments list
selection = input("Select the number of department")
print("The user selected " + store.departments[int(selection)])
# wrap all this logic in a while loop so that we can keep giving selections
# instead of having re-run the program every time
while True:
slection = input("Select the number of a department or type 'exit' to leave: ")
if selection == "exit":
print("Thanks for shopping with us!")
Break
# add error handling so that when a user inputs a department for a non-existent
# department, we'll notify them that the department doesn't existent
try:
# caasting might cause an error
selection = int(selection)
if selection >= len(store.departments):
print("That's not a valid department")
elif selection >= 0 and selection < len(store.departments):
print(f"{store.departments[selection]}")
else:
print("Department numbers are positive")
except ValueError:
# the user didin't give us a value that could be cast as a number
print("Please enter your choise as a number")
|
# -*- coding: utf-8 -*-
# EMアルゴリズム(混合正規分布(一変量))
import sys
import os
import numpy as np
import random
import matplotlib.pyplot as plt
import scipy.stats as st
# 正規分布の個数
K = 3
# 正規分布一つあたりのデータ数
P = 500
# 全データ数
N = K*P
# 繰り返し回数
LOOP = 10
# データ,平均,標準偏差
data = []
average = []
sigma = []
# 平均,標準偏差の設定
for k in range(K):
a = (np.random.rand() - 0.5) * 10.0
s = np.random.rand() * 3.0
average = np.append( average , a )
sigma = np.append( sigma , s )
print( average , sigma )
# K個の正規分布を生成
for k in range(K):
data = np.append( data , np.random.normal(average[k],sigma[k],P) )
# ヒストグラムの表示
plt.figure()
plt.hist(data,bins=100,normed=True)
plt.title("K-Gaussian")
plt.xlim([-10,10])
plt.show()
plt.clf()
# Q値,平均値,標準偏差の初期化
Q = np.zeros((N, K),dtype=np.float64)
e_average = np.zeros(K,dtype=np.float64)
e_sigma = np.zeros(K,dtype=np.float64)
e_lamda = np.zeros(K,dtype=np.float64)
for k in range(K):
e_average[k] = random.choice(data)
e_sigma[k] = np.sqrt(np.var(data))
e_lamda[k] = 1/K
# EMアルゴリズム
for loop in range(LOOP):
# E-step
for i in range(N):
temp = np.zeros(K,dtype=np.float64)
sum_t = 0
for k in range(K):
temp[k] = st.norm.pdf( data[i] , e_average[k] , e_sigma[k] )
sum_t += ( temp[k] * e_lamda[k] )
for k in range(K):
Q[i][k] = ( temp[k] * e_lamda[k] ) / sum_t
# M-step
# 重みの更新
for k in range(K):
sum_Q = 0
for i in range(N):
sum_Q += Q[i][k]
e_lamda[k] = sum_Q / N
print( loop , ":lamda -> " , e_lamda )
# 平均値の更新
new_average = np.zeros(K,dtype=np.float32)
for k in range(K):
sum_q = 0
sum_q1 = 0
for i in range(N):
sum_q += Q[i][k] * data[i]
sum_q1 += Q[i][k]
new_average[k] = sum_q / sum_q1
print( loop , ":average -> " , new_average )
# 標準偏差の更新
new_sigma = np.zeros(K,dtype=np.float32)
for k in range(K):
sum_q = 0
sum_q1 = 0
for i in range(N):
sum_q += Q[i][k] * (data[i]-e_average[k])**2
sum_q1 += Q[i][k]
new_sigma[k] = np.sqrt( sum_q / sum_q1 )
print( loop , ":sigma -> " , new_sigma )
print( " ----- " )
# 平均値,標準偏差を更新
e_average = new_average.copy()
e_sigma = new_sigma.copy()
# 推定した正規分布
result_gaussian = np.zeros((K, N),dtype=np.float64)
# 推定した混合正規分布
result_gaussian_mixture = np.zeros(N,dtype=np.float64)
# グラフの表示
line = np.linspace(-10,10,N)
# 予測した混合正規分布の表示
for k in range(K):
for i in range(N):
result_gaussian[k][i] = st.norm.pdf(line[i], e_average[k], e_sigma[k])
result_gaussian_mixture[i] +=e_lamda[k] * result_gaussian[k][i]
# 元データの表示
plt.figure()
plt.hist(data,bins=100,normed=True)
# 混合正規分布の表示
plt.plot(line, result_gaussian_mixture )
plt.title("Gaussian Mixture")
plt.show()
plt.clf()
|
#coin sums
N = 200
S = [1,2,5,10,20,50,100,200]
def change():
change = [1] + [0] * N
for coin in S:
for i in range(coin, N+1):
change[i] += change[i-coin]
return change
if __name__ == '__main__':
print(change()[N])
|
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)+1)):
if n % i == 0:
return False
return True
def find_prime(k):
idx = 0
i = 0
while True:
i = i + 1
if is_prime(i):
idx = idx + 1
if idx == k:
return i
if __name__ == '__main__':
print find_prime(10001)
|
#Digit fifth powers
# set hand calculated upper limit ~ 6*9^5
UPPER_LIMIT = 356000
def digit_fifth_power_sums():
result = 0
for i in range(2,UPPER_LIMIT):
sum_of_powers = 0
number = str(i)
for n in number:
sum_of_powers += int(n) ** 5
if sum_of_powers == i:
result += sum_of_powers
return result
if __name__ == '__main__':
print("Sum of numbers in fifth power: %d" % digit_fifth_power_sums())
|
# Quadratic primes
def is_prime(n):
if n < 2:
return False
for i in range(2, int((n**.5)+1)):
if n % i == 0:
return False
return True
def find_consecutive_primes(a,b):
n = 0
while is_prime(abs((n**2) + (a*n) + (b))):
n += 1
return n
if __name__ == '__main__':
largest_count = 0
coeff_a = 0
coeff_b = 0
for a in range(-1000,1001):
for b in range(-1000,1001):
count = find_consecutive_primes(a,b)
if largest_count < count:
largest_count = count
coeff_a = a
coeff_b = b
#print("Largest prime count now %d with a: %d b: %d" % (largest_count, coeff_a, coeff_b))
print("Largest prime count: %d With coefficients a: %d and b: %d. Product of coefficients: %d" % (largest_count, coeff_a, coeff_b, (coeff_a*coeff_b)))
|
import sqlite3
from datetime import datetime, date
conn = sqlite3.connect('env.db')
c = conn.cursor()
#def main():
# print("Hello DB!")
# createEnv("env9")
# addEnvVM("env9","Kali_07","env_07")
#delEnvVM("env9","Kali_02")
#deleteEnv("env4")
# listEnv("env9")
# listAllEnv()
# conn.close()
def createEnv(env_name):
try:
c.execute('''CREATE TABLE %s (image_name text,network_name text,vm_timestamp)''' % env_name)
conn.commit()
except:
print("ERROR:Could not create environment")
def deleteEnv(env_name):
try:
c.execute('''DROP TABLE %s''' % env_name)
except:
print("ERROR: Could not delete environment")
def addEnvVM(env_name,vm_name,vm_net):
vm_create_time=datetime.now()
try:
c.execute(str('''INSERT INTO {} VALUES ('{}','{}','{}')''').format(env_name,vm_name,vm_net,vm_create_time))
conn.commit()
except:
print("ERROR: Could not add VM to environment")
def delEnvVM(env_name,vm_name):
try:
c.execute(str('''DELETE FROM {} WHERE image_name='{}';''').format(env_name,vm_name))
conn.commit()
except:
print("ERROR: Could not delete VM to environment")
def listEnv(env_name):
try:
c.execute("SELECT * FROM %s" % env_name)
print(c.fetchall())
except:
print("ERROR: Could not list environment")
def listAllEnv():
try:
#c.execute(".tables")
c.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(c.fetchall())
except:
print("ERROR: Could not list environments")
def listNets(env_name):
try:
c.execute("SELECT network_name FROM %s" % env_name)
return c.fetchall()
except:
print("ERROR: Could not list networks")
def selectLine(table,line):
## 0 == first line of output
print("test")
c.execute(str("SELECT * FROM {} LIMIT 1 OFFSET {}").format(table,line))
print(c.fetchall())
#if __name__ == "__main__":
# conn = sqlite3.connect('env.db')
# c = conn.cursor()
# print(listAllEnv())
# main()
|
def min1(*args):
res = args[0]
for arg in args[1:]:
if arg < res:
res = arg
return res
def min2(first, *rest):
for arg in rest:
if arg < first:
first = arg
return first
def min3(*args):
tmp = list(args)
tmp.sort()
return tmp[0]
print(min1(3,4,1,2))
|
import unittest
from cans import Cola
from customer import Customer
from coins import Quarter, Dime, Nickel, Penny
class TestGetWalletCoin(unittest.TestCase):
"""Tests for Customer's get_wallet_coin method"""
def setUp(self):
self.customer = Customer()
def test_can_return_quarter(self):
"""Pass in 'Quarter', method should return a Quarter instance"""
returned_coin = self.customer.get_wallet_coin('Quarter')
self.assertEqual(returned_coin.value, .25)
def test_can_return_dime(self):
"""Pass in 'Dime', method should return a Dime instance"""
returned_coin = self.customer.get_wallet_coin('Dime')
self.assertEqual(returned_coin.value, .10)
def test_can_return_nickel(self):
"""Pass in 'Nickel', method should return a Nickel instance"""
returned_coin = self.customer.get_wallet_coin('Nickel')
self.assertEqual(returned_coin.value, .05)
def test_can_return_penny(self):
"""Pass in 'Penny', method should return a Penny instance"""
returned_coin = self.customer.get_wallet_coin('Penny')
self.assertEqual(returned_coin.value, .01)
def test_no_string(self):
"""Passing in an empty string returns not valid."""
returned_coin = self.customer.get_wallet_coin(' ')
self.assertIsNone(returned_coin, None)
class TestAddCoinsToWallet(unittest.TestCase):
"""Tests for Customer's add_coinst_to_wallet method"""
def setUp(self):
self.customer = Customer()
def test_add_coinst_to_wallet(self):
""""Pass in a list of 3 coins, test that the len of the customer’s wallet’s money list went up by
3"""
array_size = len(self.customer.wallet.money)
self.customer.add_coins_to_wallet([Penny(), Penny(), Penny()])
self.assertEqual(len(self.customer.wallet.money), array_size + 3)
def test_empty_wallet_add_coinst_to_wallet(self):
""""Pass Empty wallet, test that the len of the customer’s wallet’s money stays the same"""
array_size = len(self.customer.wallet.money)
self.customer.add_coins_to_wallet([])
self.assertEqual(len(self.customer.wallet.money), array_size)
class TestAddCanToBackpack(unittest.TestCase):
"""Tests if Cola object is passed and testing the length of the customers backpack's purchased_cans list went up by 1"""
def setUp(self):
self.customer = Customer()
def test_backpack_one(self):
backpack = len(self.customer.backpack.purchased_cans)
self.customer.add_can_to_backpack(Cola())
self.assertEqual(len(self.customer.backpack.purchased_cans), backpack + 1)
print(len(self.customer.backpack.purchased_cans))
def test_backpack_two(self):
backpack = len(self.customer.backpack.purchased_cans)
self.customer.add_can_to_backpack(Cola())
self.assertEqual(len(self.customer.backpack.purchased_cans), backpack + 1)
print(len(self.customer.backpack.purchased_cans))
def test_backpack_three(self):
backpack = len(self.customer.backpack.purchased_cans)
self.customer.add_can_to_backpack(Cola())
self.assertEqual(len(self.customer.backpack.purchased_cans), backpack + 1)
print(len(self.customer.backpack.purchased_cans))
if __name__ == "__main__":
unittest.main()
|
# -*- coding: utf-8 -*-
"""
Advent of Code
Day 1 Challenge 1
"""
myfile = open("input.txt","r")
numbers = list()
for number in myfile:
mynum = int(number)
numbers.append(mynum)
#Find 2 numbers that sum to 2020
iter = 1
for num in numbers:
diff = 2020 - num
if diff in numbers:
print(num*diff)
for num2 in numbers[iter:]:
diff2 = diff - num2
if diff2 in numbers[iter:]:
print(diff2*num2*num)
|
"""Module containing base class representing human entity"""
from datetime import datetime
class Human:
"""Base class representing human"""
def __init__(self, **kwargs):
"""Constructor"""
if kwargs is not None:
self._birthdate = datetime.date(datetime.strptime(kwargs.get('birthdate', "Human must have birthdate"),
"%d-%m-%Y"))
self._name = kwargs.get('name', "Human must have name")
self._surname = kwargs.get('surname', "Human must have surname")
self._gender = kwargs.get('gender', "Human must have gender")
def __str__(self):
"""to string"""
return f"Name:{self._name}, {self._surname}"
def get_birthdate(self) -> datetime.date:
""":return humans` birthdate"""
return self._birthdate
def get_age(self) -> int:
""":return age of human"""
today = datetime.today()
return today.year - self._birthdate.year - ((today.month, today.day) <
(self._birthdate.month, self._birthdate.day))
def get_name(self) -> str:
""":return humans` name"""
return self._name
def get_surname(self) -> str:
""":return humans` surname"""
return self._surname
def get_gender(self) -> str:
""":return humans` gender"""
return self._gender
|
"""Module contains class that represent binary tree"""
class BinaryTree:
"""Binary tree representing class"""
def __init__(self, val=None):
"""Constructor"""
self.left = None
self.right = None
self.val = val
def insert(self, val):
"""adds new value to the tree"""
if not self.val:
self.val = val
return
if self.val == val:
return
if val < self.val:
if self.left:
self.left.insert(val)
return
self.left = BinaryTree(val)
return
if self.right:
self.right.insert(val)
return
self.right = BinaryTree(val)
def get_min(self):
"""searches for minimum value in the three"""
current = self
while current.left is not None:
current = current.left
return current.val
def get_max(self):
"""searches for maximum value in the three"""
current = self
while current.right is not None:
current = current.right
return current.val
def delete(self, val):
"""deletes value from the tree by value"""
if self is None:
return self
if val < self.val:
if self.left:
self.left = self.left.delete(val)
return self
if val > self.val:
if self.right:
self.right = self.right.delete(val)
return self
if self.right is None:
return self.left
if self.left is None:
return self.right
min_larger_node = self.right
while min_larger_node.left:
min_larger_node = min_larger_node.left
self.val = min_larger_node.val
self.right = self.right.delete(min_larger_node.val)
return self
def exists(self, val):
"""checks whether this value present in tree or not"""
if val == self.val:
return True
if val < self.val:
if self.left is None:
return False
return self.left.exists(val)
if self.right is None:
return False
return self.right.exists(val)
def inorder(self, vals):
"""orders values in three from min to max"""
if self.left is not None:
self.left.inorder(vals)
if self.val is not None:
vals.append(self.val)
if self.right is not None:
self.right.inorder(vals)
return vals
def find(self, value):
"""find a node in tree by value"""
node = self
while node:
if value < node.val:
node = node.left
elif value > node.val:
node = node.right
else:
return node
if __name__ == "__main__":
binary_tree = BinaryTree()
binary_tree.insert(56)
binary_tree.insert(26)
binary_tree.insert(2)
binary_tree.insert(103)
binary_tree.insert(-1)
binary_tree.insert(2)
print(binary_tree.inorder([]))
print(binary_tree.find(2).left.val)
binary_tree.delete(26)
print(binary_tree.inorder([]))
|
"""Module contains class representing undirected unweighted graph"""
from structures.doubly_linked_list import DoublyLinkedList
class Vertex:
"""Class that represent vertex of graph"""
def __init__(self, name, connected_to=None):
"""Constructor"""
self.connected_to = DoublyLinkedList()
if connected_to is not None:
for connection in connected_to:
self.append_neighbour(connection)
self.name = name
def __str__(self):
"""to string magic method"""
if self.connected_to.get_size() != 0:
s = ''
for connection in self.connected_to:
s += f"{self.name} -> {connection.get_name()} "
return s
return self.name
def get_name(self):
""":return name of vertex"""
return self.name
def append_neighbour(self, neighbour):
"""add neighbour to the vertex"""
self.connected_to.append(neighbour)
neighbour.connected_to.append(self)
def append_neighbours(self, neighbours_list):
"""add neighbours to the vertex"""
for neighbour in neighbours_list:
self.append_neighbour(neighbour)
def delete_neighbour(self, neighbour_name):
"""delete neighbour from the vertex"""
for neighbour in self.connected_to:
if neighbour.name == neighbour_name:
self.connected_to.remove_by_value(neighbour)
return
return "Not in neighbours list"
def show_neighbours(self):
"""shows neighbours of the vertex"""
if self.connected_to:
s = ""
for connection in self.connected_to:
s += f"{connection.get_name()} "
return s
return "No neighbours"
def get_neighbours(self):
""":return neighbour-vertex objects"""
if self.connected_to.get_size():
return self.connected_to
return None
class Graph:
"""Class representing undirected
unweighted graph"""
def __init__(self, name, vertices=None):
"""Constructor"""
self.vertices = DoublyLinkedList()
if vertices is not None:
for vertex in vertices:
self.vertices.append(vertex)
self.name = name
def __str__(self):
"""to string magic method"""
s = ''
for vertex in self.vertices:
s += vertex.__str__()
s += "\n"
return s
def add_vertex(self, vertex):
"""adds vertex too the graph"""
if isinstance(vertex, Vertex):
self.vertices.append(vertex)
return
raise TypeError('Is not vertex instance!')
def add_vertices(self, vertices_list):
"""adds vertices too the graph"""
for vertex in vertices_list:
self.add_vertex(vertex)
def find_vertex(self, vertex_name):
""":return vertex from graph by name"""
for vertex in self.vertices:
if vertex.name == vertex_name:
return vertex
return 'Vertex is not in graph'
def delete_vertex(self, vertex_name):
"""delete vertex from graph"""
for vertex in self.vertices:
if vertex.name == vertex_name:
self.vertices.remove_by_value(vertex)
for vertex in self.vertices:
vertex.delete_neighbour(vertex_name)
def get_vertices(self):
"""return all graph vertices as linked list"""
return self.vertices
if __name__ == "__main__":
a = Vertex('A')
b = Vertex('B')
c = Vertex('C')
d = Vertex('D')
e = Vertex('E')
f = Vertex('F')
g = Vertex('G')
h = Vertex('H', [d, a, f, c])
a.append_neighbours([b, c, g])
g.append_neighbours([e, f])
graph = Graph("G")
graph.add_vertices([a, b, c, d, e, f, g, h])
some_vertex = graph.find_vertex("A")
print(graph)
graph.delete_vertex("A")
print('\n')
print(graph)
|
"""Module containing singer entity"""
from main_classes.human import Human
from random import choice
class Singer(Human):
"""Class representing singer"""
_song_list = []
def __init__(self, **kwargs):
"""Constructor"""
if kwargs is not None:
self._salary = float(kwargs.get('salary', "Salary cannot be empty"))
self._song_list = kwargs.get('song_list', "No songs")
super().__init__(**kwargs)
def __str__(self):
"""to string"""
return f"Name:{self.get_name()}, {self.get_surname()}(singer)"
def get_salary(self) -> float:
""":return salary of the singer"""
return self._salary
def get_song_list(self) -> list:
""":return repertoire of a singer"""
return self._song_list
def set_song_list(self, song_list):
"""setting repertoire a singer"""
self._song_list = song_list
def sing_a_song(self):
"""setting random song for singer to sing"""
song = choice(self._song_list)
print(f"Singing song:{song}")
|
def main():
numbers = [1, 2, 3, 4, 5]
gen = (value**2 for value in numbers)
for n in gen:
if n == 9:
break
print(n)
square_values = list(gen)
print(square_values)
if __name__ == '__main__':
main()
|
def main():
i = 10
i += 1
print(type(i))
f = 4.5
print(type(f))
i = True
print(type(i))
i = "Hi there"
print("Hi" in i)
print(type(i))
i = 10
j = 10**2
print(i is j)
x = -5
y = 2
print(x // y)
print(x / y)
if __name__ == '__main__':
main()
|
def my_func(a, b):
try:
result = a / b
except ZeroDivisionError as e:
raise ValueError("Argument b can't be 0")
return result
def main():
try:
result = my_func(10, 0)
except ValueError as e:
print(e)
except ZeroDivisionError as e:
print(e)
else:
print(result)
finally:
print("We will always do this")
print("We are done")
if __name__ == '__main__':
main()
|
def func(n):
return n**2
def main():
numbers = [1, 2, 3, 4]
result = list(map(lambda n: n**2, numbers))
print(result)
if __name__ == '__main__':
main()
|
def func(x, y):
return x + y
def runner(f):
print(f(2, 3))
def main():
runner(lambda x, y: x if x < y else y)
f = lambda x, f: f(x*2)
r = f(10,lambda y: 2 * y)
print(r)
ff = lambda x: lambda y: y**x
s = ff(2)
c = ff(3)
print(s(3))
print(s(4))
print(c(3))
print(c(4))
if __name__ == '__main__':
main()
|
# Stephen Haugland and Shane Snediker
# Artificial Intelligence Spring 2020
# This file contains the agent class defining the little bots that will navigate the maze
import random # Used for randomly seeding DNA
import copy # Used to create deep copy of variables
import math # Used to calculate distance
# Agent class
# This class contains all data pertaining to the individual agents that will be navigating our maze
class Agent:
#########################################
#### Class Attributes
#########################################
current_orientation = 0 # Specifies which direction the agent is facing, utilizing unit circle degrees
previous_position = [1,20] # Store the agent's previous position to repaint black on the screen. In the form of [x,y]
current_position = [1,20] # Variable holding the agent's current position, which will begin at the maze entrance. In the form of [x,y]
DNA_length = 500 # Variable representing the length of an agent's DNA structure
fitness_score = 0 # Stores the agents overall fitness score computed after the final movement
DNA_mutate_strand = (DNA_length // 10) # A holder variable that captures an integer value representing 10 percent of an agent's DNA
agent_hit_wall = 0 # Variable that tracks how many time this agent hits the wall to assess a fitness penalty
#########################################
#### Class Methods
#########################################
# Agent constructor includes two implementations of agents
# One for the first generation, and one for subsequent generations
# Parameters: maze: a maze object that this agent will be connected to
# dna_length: an integer representing this agent's DNA sequence length
# DNA_array: a list of string values representing this agent's genes
def __init__(self, maze, dna_length, DNA_array = None):
# Overloading constructors in Python involves handling all possible
# instances of the constructor within 1 method
# We begin by establishing 2 variables that every agent will have
# An integer variable holding the length of their DNA structure
self.DNA_length = dna_length
# And a DNA array to hold their DNA sequence (which is really a list of actions that the agent will take)
self.DNA = []
# Now we start with the first implementation: the case where we are
# initializing the seed population by giving them a random DNA sequence
# This is the implementation that is used because when calling the constructor
# you do not include the DNA-array parameter
if DNA_array == None:
# generate 50 random actions/movements to seed the first generation
for _ in range(self.DNA_length):
self.DNA.append(random.choice(['L', 'F', 'R']))
# Now we turn to the secondary implementaiton for agents which happens
# during reproduction when a new child is born
else:
# Another constructor to be used in the crossover function for creating new agents
# This constructor takes an array of DNA resulting from reproduction between 2 parents
self.DNA = DNA_array # Give this agent his new DNA sequence
# spawn the agent at the start of the maze
self.current_position = copy.deepcopy(maze.MAZE_START)
self.previous_position = copy.deepcopy(maze.MAZE_START)
# Update the agent's orientation according to which direction it turns
# Parameters: dir: A char containing one of 3 directions ('L' for left, 'R' for right, or 'F' for straight forward)
def turn(self,dir):
# Degrees updated based on unit circle orientation
# If this turn is left, then we need to add 90 degrees to the agent's current orientation
if dir == 'L':
self.current_orientation += 90
# If this turn is right, then we need to subtract 90 degrees from the agent's current orientation
elif dir == 'R':
self.current_orientation -= 90
# If the agent turned a full 360 degrees, reset to 0
if self.current_orientation == 360 or self.current_orientation == -360:
self.current_orientation = 0
# Calculates the next position if movement were to be carried out
# Parameter: action: A char representing the agent's next directional movement
# Return: next_pos: A list containing the next maze coordinates where the agent will move in the form of [x,y]
def calculate_next_pos(self, action):
# Begin by setting next position variable equal to the agent's current position
# next_pos is an array with the first element tracking the x direction and the second element tracking the y direction
# So next_pos[0] adjustments move agent left and right, while next_pos[1] adjustments move agent up and down
# Start the next position at the current position and make modifications from there
next_pos = copy.deepcopy(self.current_position)
# If the agent is currently facing up/north, determine its next position based on its current action
if self.current_orientation == 90 or self.current_orientation == -270:
if action == 'F':
next_pos[1] -= 1
elif action == 'L':
next_pos[0] -= 1
elif action == 'R':
next_pos[0] += 1
# If the agent is currently facing down/south, determine its next position based on its current action
elif self.current_orientation == 270 or self.current_orientation == -90:
if action == 'F':
next_pos[1] += 1
elif action == 'L':
next_pos[0] += 1
elif action == 'R':
next_pos[0] -= 1
# If the agent is currently facing right/east, determine its next position based on its current action
elif self.current_orientation == 0 or self.current_orientation == -360 or self.current_orientation == 360:
if action == 'F':
next_pos[0] += 1
elif action == 'L':
next_pos[1] -= 1
elif action == 'R':
next_pos[1] += 1
# If the agent is currently facing left/west,determine its next position based on its current action
elif self.current_orientation == 180 or self.current_orientation == -180:
if action == 'F':
next_pos[0] -= 1
elif action == 'L':
next_pos[1] += 1
elif action == 'R':
next_pos[1] -= 1
# return the next position in the form [x,y]
return next_pos
# Function that moves the agent to its next position if a wall is not present
# Parameters: action_iterator: An integer to iterate through the agent's DNA structure
# maze: 2D maze array that the agent is navigating
# Return: changed_position: the next maze location where the agent will step to
def move(self, action_iterator, maze):
# Establish a boolean flag that stores whether or not the agent has changed position, assume no movement
changed_position = False
# Determine next position by capturing the next gene representing a directional movement
action = self.DNA[action_iterator]
# Calculate the next position of this agent based on the DNA instruction
next_position = self.calculate_next_pos(action)
# if agent makes it to exit, increase fitness score to incentivize getting there ASAP
if (self.current_position[0] == maze.MAZE_EXIT[0] and self.current_position[1] == maze.MAZE_EXIT[1]) or (next_position[0] == maze.MAZE_EXIT[0] and next_position[1] == maze.MAZE_EXIT[1]):
print("Agent made it to exit!!!!!!!!!!!!! ")
# for every round of movement before the end of the DNA, add 5 points per "saved" action
self.fitness_score += 5
# Check to see if the next grid location contains an obstacle, if not blocked move there
elif maze.MAZE_GRID[next_position[1]][next_position[0]] == 0:
# Set the flag to represent the agent's movement
changed_position = True
# since movement has occured, change previous position to current and update current to the next position
self.previous_position = copy.deepcopy(self.current_position)
self.current_position = copy.deepcopy(next_position)
# However, if the next position is occupied by an obstacle the agent can't move
else:
self.agent_hit_wall += 1
# Regardless of if the agents changed positions, update its orientation accordingly
self.turn(action)
# Return the flag status of this movement
return changed_position
# Function that gives definition to an agent's DNA mutation
# We choose to use a scrambled version of DNA mutation where
# we take a DNA strand that is a predetermined percentage of
# an agent's total DNA size and we scramble the contents of
# that strand and then put the scrambled strand back in place.
# Our current predetermined DNA mutation strand percentage
# (represented by DNA_mutate_strand) is 10%
# No parameters
# Return: self: the mutated agent
# def mutate(self):
# # We need to find a random starting index within this agent's DNA strand to begin the mutation
# # We declare a variable that captures a random integer. This random integer has to be
# # less than the difference between the length of the agent's DNA strand and the length
# # of the mutating strand so that we can mutate from any random index within the DNA sequence
# start_index = random.randint(0, (len(self.DNA) - self.DNA_mutate_strand))
# # Initialize an array that will hold the DNA sequence to be scrambled
# mutation_sequence = []
# # Now we begin filling our mutation array with the specific sequence
# # of DNA from this agent that will be scrambled
# # Iterate through this agent's DNA sequence for the length of the
# # predetermined mutation DNA sequence
# # We need our iterator to start at zero on account of array indices beginning at zero
# i = 0
# # Initialize a loop that will iterate once for every gene in the mutation strand
# for i in range(self.DNA_mutate_strand - 1):
# # Load the mutation sequence array with the agent's DNA sequnence
# # beginning at the random starting index
# mutation_sequence.append(self.DNA[(start_index + i)])
# # Now that we've captured the strand to be scrambled, we scramble it
# random.shuffle(mutation_sequence)
# # Now that the sequence has been scrambled, we can put it back
# k = 0
# # Initialize a loop that will iterate once for every gene in the strand that has now been mutated
# for k in range(self.DNA_mutate_strand - 1):
# # Find the place in the agent's DNA strand where the mutation sequence was pulled
# # and start at that index replacing indices with the scrambled values
# self.DNA[(start_index + k)] = mutation_sequence[k]
# # return the mutated agent
# return self
#-------- Alternative variation to our mutation function as of Monday 5-11 -----------------------------------
# Function that gives definition to an agent's DNA mutation
# In this implementation, we use a new DNA sequence version
# of DNA mutation where we take a DNA strand that is a
# predetermined percentage of an agent's total DNA size and
# we remove it, replacing it with a new random sequence of DNA.
# Our current predetermined DNA mutation strand percentage
# (represented by DNA_mutate_strand) is 10%
# No parameters
# Return: self: the mutated agent
def mutate(self):
# We need to find a random starting index within this agent's DNA strand to begin the mutation
# We declare a variable that captures a random integer. This random integer has to be
# less than the difference between the length of the agent's DNA strand and the length
# of the mutating strand so that we can mutate from any random index within the DNA sequence
start_index = random.randint(0, (len(self.DNA) - self.DNA_mutate_strand))
# Initialize an array that will hold the new DNA mutation sequence
mutation_sequence = []
# First let's create a brand new random sequence of DNA instructions of size DNA_mutate_strand
for _ in range(self.DNA_mutate_strand):
mutation_sequence.append(random.choice(['L', 'F', 'R']))
# Now we replace the mutation strand of the agent with the new mutated values
# We need our iterator to start at zero on account of array indices beginning at zero
i = 0
# Initialize a loop that will iterate once for every gene in the mutation strand
for i in range(self.DNA_mutate_strand - 1):
# Replace the current gene value with the new mutated value
self.DNA[(start_index + i)] = mutation_sequence[i]
# return the mutated agent
return self
# -------------------- END OF ALTERNATIVE MUTATION IMPLENTATION ---------------------
# Test function to display DNA
def print_DNA(self):
print(self.DNA)
# # Function that calculates an agent's fitness at the conclusion of a generation of maze navigating
# # Parameters: maze: 2D array that the agent is navigating
# def calculate_fitness(self, maze):
# # calculate distance from final agent position to maze exit
# # d = sqrt((mazeX - agentX)^2 + (mazeY-agentY)^2)
# # save operation complexity by not square rooting
# distance = (abs(maze.MAZE_EXIT[1] - self.current_position[1])) + (abs(maze.MAZE_EXIT[0] - self.current_position[0]))
# # arbitrary number chosen to subtract distance from to make fitter agents have higher scores
# score = 100 - distance
# self.fitness_score = score
#-------------------- Alternative variation to our fitness function as of 5-11 ---------------
# This variation penalizes an agent for hitting the wall and for not at least making
# it halfway across the maze
# Function that calculates an agent's fitness at the conclusion of a generation of maze navigating
# Parameters: maze: 2D array that the agent is navigating
def calculate_fitness(self, maze):
# Begin by tallying the positive fitness score by rewarding
# the movements of agents that avoid obstacles and traverse
# closer to the maze exit
# calculate distance from final agent position to maze exit
# d = sqrt((mazeX - agentX)^2 + (mazeY-agentY)^2)
# save operation complexity by not square rooting
#distance = math.sqrt(((maze.MAZE_EXIT[1] - self.current_position[1])** 2) + ((maze.MAZE_EXIT[0] - self.current_position[0])** 2 ))
distance = (abs(maze.MAZE_EXIT[1] - self.current_position[1])) + (abs(maze.MAZE_EXIT[0] - self.current_position[0]) )
# To avoid getting caught by a local minimum situation, let's give a bonus to
# agents that at least make it half way through the maze
if distance > 35:
distance -= 5
# Now we pick an arbitrary number to subtract our current fitness score (distance)
# from this number to ensure that fitness scores will increase in value.
# Because the distance calculated above favors smaller distances, we use this
# calculation to invert the values so that shorter distances from the maze exit
# are reflected with higher fitness scores
# Finally we need to punish the agent for hitting the wall
# We subtract from the agent's positive distance score a point for every time they hit a wall
# We've incremented each agent's member variable to track their collisions
#score = score - (.25 * self.agent_hit_wall)
self.fitness_score += (100 - distance)
#------------------- END OF ALTERNATIVE FITNESS FUNCTION DEFINITION -------------------------
|
def encrypt(text, key):
#enc=list()
result=""
for i in range(len(text)):
char = text[i]
#uppercase
if(char.isupper()):
result+=chr((ord(char)+(ord(key[i%len(key)])-ord("A"))-65)%26 + 65)
#lowercase
else:
result+=chr((ord(char)+(ord(key[i%len(key)])-ord("a"))-97)%26 + 97)
return result
def main():
text=str(input("Enter Message: "))
key=input("Enter String For Encryption: ")
s1 = encrypt(text, key)
print("Encrypted Message is : "+s1)
if __name__ == '__main__':
main()
|
T = input().strip()
while(not T.isdigit()):
T = input().strip()
i = 0
while(i < int(T)):
orgn_str = input().strip()
mid = int(len(orgn_str)/2)
left_str = orgn_str[:mid]
right_str = orgn_str[mid:]
left_str = left_str[::-1]
right_str = right_str[::-1]
strg = left_str + right_str
print(strg)
|
items = [
('Product1', 13),
('Product2', 18),
('Product3', 11)
]
#prices = list(map(lambda item: item[1], items))
prices = [item[1] for item in items]
#filtered = list(filter(lambda item: item[1] >= 12, items))
filtered = [item for item in items if item[1] >= 12]
print(prices)
print(filtered)
|
import csv
# 開啟csv檔案
with open('lesson6/mrt.csv', newline='', encoding='utf-8') as csvfile:
# 讀取csv檔案內容
rows = csv.reader(csvfile)
# 迴圈輸出每一列
for row in rows:
print(row) # list形式
with open('lesson6/mrt.csv', newline='', encoding='utf-8') as csvfile:
rows = csv.DictReader(csvfile)
for row in rows:
print(row) # dictionary形式
|
# 定義一個方程式sequential_add
# 方程式有兩個參數 n1 n2
# 算出n1 - n2之間數字的加總
# 印出結果在terminal
# 注意:不可以使用print
# 例子
# sequential_add(1,10) -> 回傳55
# sequential_add(5,10) -> 回傳45
# sequential_add(10,1000)-> 回傳500455
def sequential_add(n1,n2):
total=0
for i in range(n1,n2+1):
total=total+i
print(total)
sequential_add(1,10)
sequential_add(5,10)
sequential_add(10,1000)
|
# Python主要有兩種loops形式
# for loops
# while loops
# loops是在給定條件為True的情況下,會持續執行的迴圈
# a loop is used to execute a set of statements as long as a given condition is true
for i in range(5):
print(i)
# String
for c in "python":
print(c)
# list
my_list = ['Alice', 'Tobey']
for name in my_list:
print(name)
# dictionary
my_dict = {
'Name' : 'Alice',
'Job': 'Software Engineer',
'Hobby': 'Shopping'
}
# 只有key值 for default
for item in my_dict:
print(item)
# 用items來取得key-value pair
for k, v in my_dict.items():
print(f'key is {k} and value is {v}')
print('key is ' + k + ' and value is ' + v)
|
# 請指出以下code錯誤的部分
# 1
# print('Why won't this line of code print')
print("Why won't this line of code print")
# 2
# prnit('This line fails too!')
print('This line fails too!')
# 3
# print "I think I know how to fix this one"
print ("I think I know how to fix this one")
# 4
# input('Please tell me your name: ')
# print(name)
name = input('Please tell me your name: ')
print(name)
|
# 定義一個方程式square
# 方程式要輸入一個list
# 算出list裡面數字的平方和
# 印出結果在terminal
# 注意:不可以使用print
# 例子
# [1,2,3] -> 回傳14
# [10,11,12,13,14,15] -> 回傳955
# [10, 100, 1000, 10000]-> 回傳101010100
def square(list):
total=0
for i in list:
total=total+i**2
return total
print(square([1,2,3]))
print(square([10,11,12,13,14,15]))
print(square([10, 100, 1000, 10000]))
|
def multiply1(num1, num2):
total = num1 * num2
print(total)
return total
def multiply2(num1, num2):
total = num1 * num2
return 'Aloha'
def multiply3(num1, num2):
total = num1 * num2
return total
result = multiply1(5,6)
print(result)
#new_answer = result + 1
#print(new_answer)
|
# 使用方程式來畫星星!
# 1. 要求使用者輸入一個數字,存在變數裡
# 2. 定義方程式,將步驟1的數字帶入
# 3. 呼叫方程式,在terminal印出以下圖案
# 例:使用者輸入3
# 在terminal印出(不包括 #)
# *
# **
# ***
# 例:使用者輸入5
# 在terminal印出(不包括 #)
# *
# **
# ***
# ****
# *****
def draw(num):
for i in range(1,num+1):
row=''
for i in range(0,i):
row=row+'*'
print(row)
num= int(input('enter a number:'))
draw(num)
|
# Modules(https://docs.python.org/3/tutorial/modules.html)
# 用來儲存程式碼,要使用任何modules只要import便可以使用該module裡的程式碼
# Python Module Index: https://docs.python.org/3/py-modindex.html
# import math
# x = 10.47
# print(math.floor(x))
# print(math.ceil(x))
# print(math.factorial(5))
# ModuleNotFoundError: No module named 'camelcase'
# # $ pip3 install camelcase
import camelcase
c = camelcase.CamelCase()
txt = "hello world"
print(c.hump(txt))
|
# def multiply(num1, num2=10):
# total = num1 * num2
# return total
# x = 5
# y = 6
# 沒有輸入num2,則會使用default值10
# z = multiply(5)
# print(z)
# mini challenge
# 寫一個算出兩個數的平均的方程式
def avg ( v1, v2 ) :
return (v1+v2)/2
print(avg(10,20))
|
def m(to_move):
return int(to_move / 2)
class pos:
def __init__(self, val, x, y):
self.val = val
self.x = x
self.y = y
all_spots = {}
origin = pos(1, 0, 0)
all_spots[origin.val] = origin
to_move = 2
def move_left(spaces, starting_pos):
start_val = starting_pos.val
start_x = starting_pos.x
start_y = starting_pos.y
for i in range(spaces):
start_val += 1
start_x -= 1
temp = pos(start_val, start_x, start_y)
all_spots[start_val] = temp
def move_right(spaces, starting_pos):
start_val = starting_pos.val
start_x = starting_pos.x
start_y = starting_pos.y
for i in range(spaces):
start_val += 1
start_x += 1
temp = pos(start_val, start_x, start_y)
all_spots[start_val] = temp
def move_up(spaces, starting_pos):
start_val = starting_pos.val
start_x = starting_pos.x
start_y = starting_pos.y
for i in range(spaces):
start_val += 1
start_y += 1
temp = pos(start_val, start_x, start_y)
all_spots[start_val] = temp
def move_down(spaces, starting_pos):
start_val = starting_pos.val
start_x = starting_pos.x
start_y = starting_pos.y
for i in range(spaces):
start_val += 1
start_y -= 1
temp = pos(start_val, start_x, start_y)
all_spots[start_val] = temp
def main():
"""Make a big old thing of numbers"""
i = 1
while(max(all_spots.keys()) < 277678):
move_right(i, all_spots[max(all_spots.keys())])
move_up(i, all_spots[max(all_spots.keys())])
move_left(i+1, all_spots[max(all_spots.keys())])
move_down(i+1, all_spots[max(all_spots.keys())])
i += 2
print(all_spots[277678].x, all_spots[277678].y)
if __name__ == '__main__':
main()
|
import sys
import random
if len(sys.argv) <= 2:
print "Please enter a filename and a percentage"
exit(1)
filename = sys.argv[1]
percent = int(sys.argv[2])
file = open(filename)
for line in file:
r = random.randint(0,100)
if r < percent:
print line,
|
"""
Intro to Python Lab 1, Task 2
Complete each task in the file for that task. Submit the whole folder
as a zip file or GitHub repo.
Full submission instructions are available on the Lab Preparation page.
"""
"""
Read file into texts and calls.
It's ok if you don't understand how to read files
You will learn more about reading files in future lesson
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
HINT: Build a dictionary with telephone numbers as keys, and their
total time spent on the phone as the values. You might find it useful
to write a function that takes a key and a value and modifies a
dictionary. If the key is already in the dictionary, add the value to
the key's existing value. If the key does not already appear in the
dictionary, add it and set its value to be the given value.
"""
def add_time(num, time):
if num in num_time:
num_time[num] += int(time) # call[3] is string
else:
num_time[num] = int(time)
num_time = {} # telephone_number : during_time
for call in calls:
add_time(call[0], call[3])
add_time(call[1], call[3])
sorted_dict = sorted(num_time.items(), key=lambda d: d[1], reverse=True)
print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(sorted_dict[0][0], sorted_dict[0][1]))
|
"""
Consider the following numbers (where n! is factorial(n)):
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
Which will win: 1 / n! or (1! + 2! + 3! + ... + n!)?
Are these numbers going to 0 because of 1/n! or to infinity due to the sum of factorials or to another number?
Task
Calculate (1 / n!) * (1! + 2! + 3! + ... + n!) for a given n, where n is an integer greater or equal to 1.
To avoid discussions about rounding, return the result truncated to 6 decimal places, for example:
1.0000989217538616 will be truncated to 1.000098
1.2125000000000001 will be truncated to 1.2125
Hint
You could try to simplify the expression.
"""
import math
def going(n):
return float(str((1 / math.factorial(n)) * sum([math.factorial(x) for x in range(1, n + 1)]))[:8])
|
l = [1,2,3,4,5,6,7,8,9]
l.append(0)
print(l)
l.insert(4,55)
print(l)
s =[11,22,33]
l.extend(s)
print(l)
print(s)
print(l+s)
print(l)
print(s)
#删除下标删除
print(l.pop(1))
print(l)
print(l.pop())
print(l)
print(l.pop(-3))
#根据内容删除
l.remove(55)
print(l)
#修改列表中数据
l[2]=0
print(l)
|
import math
# graph = {'a': {'b': 10, 'c': 3},
# 'b': {'d': 2, 'c': 1},
# 'c': {'b': 4, 'd': 8, 'e': 2},
# 'd': {'e': 7, },
# 'e': {'d': 9}
# }
graph = {'a': {'b': 5, 'c': 1},
'b': {'a': 5, 'c': 2, 'd': 1},
'c': {'a': 1, 'b': 2, 'd': 4, 'e': 8},
'd': {'b': 1, 'c': 4, 'e': 3, 'f': 6},
'e': {'c': 8, 'd': 3},
'f': {'d': 6}
}
def dijkstra(graph, start, goal):
# 每个点到起始点的最小距离,类似于大小为1*n的数组
shortest_distance = {}
# 记录祖先点
predecessor = {}
# 复制graph并进行点的遍历
unseenNodes = graph
infinity = math.inf
# 记录路径
path = []
# 初始化距离
for node in unseenNodes:
shortest_distance[node] = infinity
shortest_distance[start] = 0
# 判断字典是否为空,即点是否遍历完成
while unseenNodes:
minNode = None
# 第一个循环是为了比较大小,找出shortest_distance最小的结点minNode,即为下一步分析的结点
for node in unseenNodes:
if minNode is None:
minNode = node
elif shortest_distance[node] < shortest_distance[minNode]:
minNode = node
# 第二个循环是为了update数据,以minNode为出发点,shortest_distance[minNode]是到minNode这个
# 结点已经走过的距离,weight是从minNode往下一个结点childNode走的距离,shortest_distance[chi
# ldNode]是指上一轮循环中得出的从起点到childNode的距离,若本轮数值比上一轮小,则替换
for childNode, weight in graph[minNode].items():
if weight + shortest_distance[minNode] < shortest_distance[childNode]:
shortest_distance[childNode] = weight + shortest_distance[minNode]
predecessor[childNode] = minNode
# minNode作为已经走过的点,在循环结束时应当pop出去
unseenNodes.pop(minNode)
currentNode = goal
while currentNode != start:
try:
path.insert(0, currentNode)
currentNode = predecessor[currentNode]
except KeyError:
print('Path not reachable')
break
path.insert(0, start)
if shortest_distance[goal] != infinity:
print('Every node shortest distance to ' + start + ' is ' + str(shortest_distance))
print(goal + ' shortest distance to ' + start + ' is ' + str(shortest_distance[goal]))
print('And the path is ' + str(path))
dijkstra(graph, 'a', 'f')
|
#!/usr/bin/env python3
# 列表:list 有序的集合,可以随时添加和删除其中的元素
classmates = ['Michael', 'Bob', 'Tracy']
print("classmates = %s ,len(classmates) = %d" % (classmates, len(classmates)))
# 用索引来访问list中每一个位置的元素, 超出索引范围报错IndexError
print("classmates[0] = ", classmates[0])
# -1 做索引直接获取最后一个元素 依次递推 -2倒数第二个
print("classmates[-1] = ", classmates[-1])
# list是 可变 有序表,所以可以往list末尾追加元素
classmates.append('Adam')
print("classmates = %s ", classmates)
# 插入元素到指定位置
classmates.insert(1, "Jack")
print("classmates = %s ", classmates)
#删除list末尾的元素
classmates.pop()
print("classmates = %s ", classmates)
#修改
classmates[1] = 'Sarah'
print("classmates = %s ", classmates)
# list中可以存不同的数据类型
L = ['Apple', 123, True]
print('L = ', L)
# list中的元素也可以是list
s = ['python', 'java', ['asp', 'php'], 'scheme']
print('s = ', s)
print("len(4) = ", len(s))
M = []
print("M = %s, len(M) = %d" % (M, len(M)))
# 有序表tuple,与list非常类似,但tuple一旦初始化就不能修改,没有append()、insert()这样的方法,也不能赋值
roommates = ('Michael', 'Bob', 'Tracy')
# 仍可以使用 roommates[0]、roommates[-1] 来访问
print("roommates[1] = ", roommates[1])
# 定义一个tuple时,要在定义的时候就把元素确定下来
t = (1, 2)
print("t = ", t)
# 定义一个空的tuple
p = ()
print("p = ", p)
# 定义只有一个元素的tuple时, 加一个逗号,避免与算数意义上的括号冲突
q = (1,)
print("q = ", q)
# 一种 "可变的" tuple
w = ('a', 'b', ['A', 'B'])
print('w = ', w)
w[2][0] = 'X'
w[2][1] = 'Y'
print('w = ', w)
# tuple 中指向的list并没有变,变得是list的内容
|
# import required packages
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, LSTM, Bidirectional, Conv1D, MaxPooling1D, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras import datasets
from tensorflow.keras.utils import to_categorical
# import train test split, numpy and pandas
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
import pickle
from sklearn.preprocessing import MinMaxScaler
# YOUR IMPLEMENTATION
# Thoroughly comment your code to make it easy to follow
# getting new data frame with lookback into 3 previous days
def sequence(data, dates):
features = data.columns[1:]
print(features)
# setting names of columns of dataframe
names = []
# loop over previous 3 days
for j in range(1,4):
# get all the 4 features for each day
names += [f+'(t-{})'.format(j) for f in features]
# add target column to the dataframe
names.append('target(t)')
# create a dataframe with column name list designed in above loop
df_new = pd.DataFrame(columns= names, index= dates[:len(data)-3])
# loop over all the days having 3 previous days
for i in range(len(data)-3):
# list to store values of each row (day)
cols = []
# loop for getting previous 3 days data
for j in range(1,4):
# getting every feature from each day
for f in features:
# adding value of jth previous day and f feature to cols list
cols.append(data[f][i+j])
# setting open price of current day as target variable
cols.append(data[' Open'][i])
# add the data to new dataframe
df_new.loc[dates[i]]= cols
# returning the new dataframe
return(df_new)
# calculate rmse of data
def rmse(actual, pred):
error = 0
for i in range(len(actual)):
diff = (actual[i] - pred[i])**2
error += diff
error = tf.math.sqrt(error/len(actual))
return error
def main():
'''# 1. load your training data'''
# read the csv file
data = pd.read_csv(os.path.join('data','q2_dataset.csv'))
# getting date column
dates = data['Date']
# extract the 4 features volume, open, low and High
features = [' Volume', ' Open', ' High', ' Low']
# getting columns required to save data to csv file
cols = ['Date',' Volume', ' Open', ' High', ' Low']
# selecting only required column
data = data[cols]
# get data to save to csv
data_csv = sequence(data, dates)
# splitting the data into train and test data
train, test = train_test_split(data_csv, test_size = 0.3, random_state = 42)
# saving train data
train.to_csv(os.path.join('data',"train_data_RNN.csv"))
# saving test data
test.to_csv(os.path.join('data',"test_data_RNN.csv"))
'''loading training data & preprocessing'''
# reading train data
train_data = pd.read_csv(os.path.join('data','train_data_RNN.csv'))
# column names of input features
col_names = train_data.columns[1:-1]
# getting input and output data
X = train_data[col_names].values
y = np.ravel(train_data['target(t)'])
y = y.reshape(y.shape[0],1)
# splitting the data in train & validation
X_train, X_val, y_train, y_val = train_test_split(X,y, test_size = 0.2, random_state = 21)
# prepricessing
scaler1 = MinMaxScaler()
scaler2 = MinMaxScaler()
# normalising the data
X_train_norm = scaler1.fit_transform(X_train)
y_train_norm = scaler2.fit_transform(y_train)
# saving the two scalers into pkl file
pickle.dump(scaler1, open(os.path.join('data', "scaler1.pkl"), "wb" ) )
pickle.dump(scaler2, open(os.path.join('data', "scaler2.pkl"), "wb" ) )
# transforming validation data
X_val_norm = scaler1.transform(X_val)
y_val_norm = scaler2.transform(y_val)
# makinng inputs ready for LSTM
X_train_norm = X_train_norm.reshape(X_train_norm.shape[0],3,4)
X_val_norm = X_val_norm.reshape(X_val_norm.shape[0], 3, 4)
'''# 2. Train your network'''
# initialise sequetial model
model = Sequential()
# add LSTM layer
model.add(LSTM(units=70, input_shape = (X_train_norm.shape[1],X_train_norm.shape[2]) ))
# add dense layer
model.add(Dense(1))
# compile model
model.compile(optimizer='adam', loss='mean_squared_error')
# fit model on train and validate
history = model.fit(X_train_norm, y_train_norm, epochs=200, batch_size=8, validation_data = (X_val_norm, y_val_norm), verbose=1)
'''predicting the output from training data and validation data'''
y_train_pred = model.predict(X_train_norm)
y_val_pred = model.predict(X_val_norm)
'''inverse transform the predicted value to get value in actual scale'''
y_train_pred = scaler2.inverse_transform(y_train_pred)
y_val_pred = scaler2.inverse_transform(y_val_pred)
print('RMSE loss on training data: {}'.format(rmse(y_train, y_train_pred)))
print('RMSE loss on validation data: {}'.format(rmse(y_val, y_val_pred)))
'''plot for training loop'''
# plots for accuracy and loss for training
fig, ax = plt.subplots(1,1, figsize=(7,4))
# summarize history for loss
plt.plot(tf.math.log(history.history['loss']))
plt.plot(tf.math.log(history.history['val_loss']))
plt.title('Log loss vs epoch with normalised data')
plt.ylabel('log loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper right')
fig.set_facecolor('white')
plt.show()
'''save your model'''
model.save(os.path.join('models','20848879_RNN_model'))
if __name__ == "__main__":
main()
|
"""
1. if someBooleanValueIsTrue:
# Do this
else:
# Do that
Note:
The indented line
The lack of a value for the else statement
else is dependent on if
Examples from basic programs:
1.
print("Please enter the password: ")
password = input()
if password == 'hunter1':
print("Access granted!")
else:
print("Access denied.")
2.
bankAccountBalance = 10
print("Banco Popular:")
print("Please enter the password for your account: ")
password = input()
if password == 'hunter1':
print("Access granted!")
if bankAccountBalance < 50:
print("That's not a lot of money in your account')
if bankAccountBalance > 50:
print("Wow! That's a lot of money in your account!')
Challenges for Pablo:
carSpeed = 50 # mph
speedLimit = 60 # mph
Create a program that given two variables: carSpeed and speedLimit, checks if the car is speeding or not. If the
car is speeding, print a message that says it is, otherwise print a message that says it isn't
Create a program that gets two inputs from the user and adds them together. Tell the user if the sum of the two
numbers is greater than 100.
The elif statement:
Like the else statement, but checks something first.
Example:
if name == 'Christopher':
# do something
elif name == 'Pablo':
# do something
elif name = 'Shrek':
# do something
else:
print("Name not found")
"""
|
import speech_recognition as sr
import time
from respond import respond
from talk import speak
import os
#The Recognizers for Speech Data
r = sr.Recognizer() #-> General
wake = sr.Recognizer() #-> Wake word
#Clears Screen after each output
def clear():
os.system("cls||clear")
class wakey:
def activate():
with sr.Microphone() as source:
print('I am going to sleep...say "Hello Alpha" in order to get me working')
print('Sleeping...zzzzz....zzzzz')
while True:
# audio = r.listen(source)
# wake_word = ""
# try:
# wake_word = r.recognize_google(audio)
# except sr.UnknownValueError:
# pass
# except sr.RequestError:
# speak("Sorry, my Speech service is down!")
wake_word = str(input())
if ("alpha" in wake_word.lower()):
break
return wake_word
#Function to Record Audio
# def rec_audio(ask=False):
# #Open the Microphone
# with sr.Microphone() as source:
# if ask:
# speak(ask)
# print("Listening...")
# audio = r.listen(source)
# voice_data = ""
# #Error Handling
# try:
# voice_data = r.recognize_google(audio)
# except sr.UnknownValueError:
# speak("Sorry, I did not get that!")
# voice_data = '-1_sr_error'
# except sr.RequestError:
# speak("Sorry, my Speech service is down!")
# voice_data = '-1_sr_error'
# return voice_data
def rec_audio():
print("Listening...")
voice_data = str(input())
return voice_data
#Allows Alpha to stay on,
time.sleep(3)
speak("How can I help you")
check = 1
while(check in [0,1,2]):
if(check == 1):
voice_data = rec_audio()
if(voice_data == "-1_sr_error"):
continue
elif(check == 2):
wakey.activate()
check = 1
continue
else:
check = 1
continue
check = respond(voice_data.lower())
clear()
|
subscription = str(input("Please sign up for Programmer's Toolkit Monthly Subsciption from Platinum, Gold, Silver, Bronze or Free Trial:"))
if subscription == "Platinum":
print("Platinum subscription is $60 with a monthly gift of programming books!")
elif subscription == "Gold":
print("Gold subscription is $50 with a monthly gift of figurines!")
elif subscription == "Silver":
print("Silver subscription is $40 with a monthly gift of t-shirts!")
elif subscription == "Bronze":
print("Bronze subscription is $30 with a monthly gift of stickers!")
else:
print("Free trial subscription is free for 30 days with no monthly gift!")
|
import csv
import pandas as pd
def readCSV(readFileName, writeFileName):
df = pd.read_csv(readFileName)
# 初期の前処理
df.dropna() # 欠損値(行)を消すパターン
# df.dropna(axis=1) # 欠損値(列)を消すパターン
for colName in df:
df[colName] = df[colName].fillna(0) # 「0」による穴埋め
colName = 'emp_length'
df[colName] = df[colName].mask(df[colName] == 'n/a', '0')
# term: 2値化
df['term'] = df['term'].map(lambda x: 1 if x == ' 60 months' else 0)
# int_rate: 「%」の削除
df['int_rate'] = df['int_rate'].map(lambda x: x[0:len(x) - 1])
# grade, sub_grade: アルファベットの数値化
grades = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
df['grade'] = df['grade'].map(lambda x: grades.index(x))
df['sub_grade'] = df['sub_grade'].map(lambda x: str(grades.index(x[0:1])) + str(x[1:2]))
# emp_length: 勤続年数の数値値
df['emp_length'] = df['emp_length'].map(lambda x: x[0:1] if x.find('+') == -1 and x.find('<') == -1 else 10 if x.find('+') else 0)
# earliest_cr_line: 「日付」の数値化
monthDist = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'}
df['earliest_cr_line'] = df['earliest_cr_line'].map(lambda x: x[4:8] + monthDist[x[0:3]])
# revol_util: 「%」の削除
df['revol_util'] = df['revol_util'].map(lambda x: x[0:len(x) - 1] if str(x).find('%') > -1 else x)
# 【不要な列の削除】
# ---実験1---> 除去する変数(0.0005以下)
# 除去方針:地域系は、1地域当たりのサンプル数が少ないため、排除
del df['zip_code'] #0.00000 <(米国の)郵便番号の先頭3桁>
# 除去方針:職業系は、1職業当たりのサンプル数が少ないため、排除
del df['emp_title'] # <>
# 除去方針:口座系は基本的に排除
del df['acc_now_delinq'] #0.00007 <借手が遅延している口座数>
del df['num_sats'] #0.00024 <満足できる口座数>
del df['num_tl_120dpd_2m'] #0.00007 <120日以上延滞中の口座数(過去2ヶ月間更新)>
del df['num_tl_30dpd'] #0.00003 <30日以上延滞中の口座数(過去2ヶ月間更新)>
# 除去方針:correct to target <= 0.0005
del df['pymnt_plan'] #0.00000 <支払計画の設定の有無>
del df['open_acc'] #0.00029 <借手クレジットファイルの未締クレジットライン数>
del df['open_rv_12m'] #0.00032 <過去12ヶ月のリボ取引数>
del df['chargeoff_within_12_mths'] #0.00009 <12ヶ月以内の貸倒償却件数>
del df['num_il_tl'] #0.00031 <割賦勘定の数>
del df['num_op_rev_tl'] #0.00037 <オープンリボルビングアカウントの数>
del df['pub_rec_bankruptcies'] #0.0003 <公的な倒産件数>
# ---実験2---> 除去する変数(0.005以下)
# 除去方針:地域系は、1地域当たりのサンプル数が少ないため、排除
del df['addr_state'] #0.00186 <(米国の)州>
# 除去方針:年月系は基本的に排除
del df['earliest_cr_line'] #0.0021 <借り手の与信限度額の設定月>
del df['emp_length'] #0.0014 <継続雇用年数>
del df['mo_sin_rcnt_tl'] #0.00105 <最近の口座開設後の月数>
del df['mo_sin_old_il_acct'] #0.00155 <最古の割賦口座開設後の月数>
del df['mths_since_rcnt_il'] #0.00175 <最近の割賦口座開設後の月数>
del df['mo_sin_old_rev_tl_op'] #0.00294 <最古のリボ口座開設後の月数>
del df['mo_sin_rcnt_rev_tl_op'] #0.00077 <直近のリボ口座開設後の月数>
del df['mths_since_last_delinq'] #0.00233 <最後の延滞からの月数>
del df['mths_since_last_major_derog'] #0.00294 <最近の90日以上延滞からの月数>
del df['mths_since_recent_bc'] #0.00083 <銀行口座開設からの経過月数>
del df['mths_since_recent_bc_dlq'] #0.00233 <直近の銀行カード延滞以降の月数>
del df['mths_since_recent_inq'] #0.00071 <直近の銀行カード遅延以降の月数>
del df['mths_since_recent_revol_delinq'] #0.00194 <直近の回転の延滞以降の月間>
# 除去方針:口座系は基本的に排除
del df['num_bc_tl'] #0.00253 <銀行口座数>
del df['num_actv_bc_tl'] #0.00067 <有効な銀行口座数>
del df['num_bc_sats'] #0.00065 <優良な銀行口座数>
del df['num_tl_op_past_12m'] #0.00075 <過去12ヶ月間の開設口座数>
del df['num_tl_90g_dpd_24m'] #0.00178 <過去24ヶ月間の、90日以上延滞した口座数>
del df['open_il_12m'] #0.00215 <過去12ヶ月の開設割賦口座数>
del df['open_il_24m'] #0.00129 <過去24ヶ月の開設割賦口座数>
# 除去方針:correct to target <= 0.005
# 取引数系
del df['open_il_6m'] #0.00167 <アクティブ割賦取引数>
del df['inq_fi'] #0.00115 <個人金融の信用調査の件数>
del df['inq_last_6mths'] #0.00282 <過去6ヶ月間の信用調査の件数>
del df['inq_last_12m'] #0.00077 <過去12ヶ月間の信用調査の件数>
del df['acc_open_past_24mths'] #0.0008 <過去24ヶ月間に開かれた取引数>
del df['open_rv_24m'] #0.0007 <過去24ヶ月間のリボ取引数>
del df['num_rev_tl_bal_gt_0'] #0.0018 <残高が0以上のリボ取引数>
del df['num_actv_rev_tl'] #0.00165 <アクティブなリボ取引数>
del df['pct_tl_nvr_dlq'] #0.00276 <非延滞取引率>
del df['total_cu_tl'] #0.00082 <金融取引件数>
del df['open_acc_6m'] #0.00153 <過去6ヶ月間のオープントレード数>
# 金銭系
# del df['annual_inc'] #0.00296 <自己申告の年間収入>
del df['delinq_2yrs'] #0.00385 <30日以上延滞金額>
del df['loan_amnt'] #0.00422 <借り手の申請ローン額>
del df['max_bal_bc'] #0.00286 <全てのリボ最大残高>
del df['delinq_amnt'] #0.00025 <借り手の延滞中口座の未払額>
del df['revol_bal'] #0.00224 <リボ残高総額>
del df['total_bal_il'] #0.00283 <全割賦勘定の現合計残高>
del df['total_bal_ex_mort'] #0.00246 <住宅ローンを除く総クレジット残高>
del df['total_il_high_credit_limit'] #0.00276 <割賦限度総額>
# その他
del df['purpose'] #0.00266 <資金用途のカテゴリ>
del df['title'] #0.00317 <ローンのタイトル>
del df['il_util'] #0.00197 <クレジット限度額に対する現在の合計残高の比率>
del df['mths_since_last_record'] #0.00193 <最後の公的記録>
del df['pub_rec'] #0.00124 <軽蔑的な公的記録数>
del df['num_accts_ever_120_pd'] #0.0013 <支払期日120日以上のアカウント数>
del df['num_rev_accts'] #0.00218 <リボアカウント数>
del df['tax_liens'] #0.0012 <税務上の抵当権数>
del df['total_acc'] #0.00183 <借り手のクレジットライン数>
# ---実験3---> 手動による調整
del df['mort_acc'] #<住宅ローン口座の数>
# del df['all_util'] #<全取引での与信限度のバランス> ... targetと高い相関
del df['avg_cur_bal'] #<全ての口座の平均残高>
# del df['bc_util'] #<銀行残高 / 与信限度額> ... targetと低い相関
del df['tot_cur_bal'] #<全口座の合計残高>
# del df['dti'] #<債務 / 収入> ... targetと低い相関
del df['installment'] #<ローン発生時の借り手の月額支払い> ※?
del df['term'] #<ローン支払い回数>
# del df['tot_hi_cred_lim'] #<貸付限度総額> ... targetと低い相関
# del df['total_bc_limit'] #<銀行カードの貸付限度総額> ... targetと低い相関
# del df['revol_util'] #<現在のリボ残高 / リボ与信限度額> ... ?
del df['total_rev_hi_lim'] #<総リボクレジット限度額>
del df['initial_list_status'] #<ローンの初期リスティングステータス>
del df['percent_bc_gt_75'] #<>
# ---ここまで残ったカラム(比較的強い相関がある変数)---> 計13変数
# <correct to targetの値に基づき、後ろ向き法で残った変数(高い相関)>
# int_rate (ローンの金利)
# grade (ローングレード)
# sub_grade (ローンの副次グレード)
# verification_status (申告所得額の検証の有無)
# all_util (全取引での与信限度のバランス)
# bc_open_to_buy (リボ銀行カードでの購入可能最大額)
# home_ownership (自宅の所有状況)
# <correct to targetの値に基づき、後ろ向き法で残った変数(低い相関)>
# dti (債務 / 収入)
# bc_util (銀行残高 / 与信限度額)
# revol_util (現在のリボ残高 / リボ与信限度額)
# tot_hi_cred_lim (貸付限度総額)
# total_bc_limit (銀行カードの貸付限度総額)
# <自己判断に基づき、前向き法で加えた変数>
# annual_inc (自己申告の年間収入)
df.to_csv(writeFileName, index=None)
readCSV('training_data.csv', 'output.csv')
|
startNum = 13
x = startNum
x = 3
y = x
print(x)
coLen = 0;
while coLen < 1000000:
x = y
coLen = 0
while (x > 2):
if x % 2 == 0:
x = x//2
print(x)
coLen += 1
if x % 2 != 0:
x = 3 * x + 1
print(x)
coLen += 1
y += 1
print(1)
print ("Longest Collatz length is %d" % coLen)
print ("Starting number is %d." % y)
|
class GameItem:
def __init__(self, display_name=None):
self.unique_id = self.generate_id()
if not display_name:
self.display_name = str(self.unique_id)
def generate_id(self):
"""
TODO: mechanism for ensuring every generated ID is unique/psuedorandom
:return:
"""
return 0
class PLayerStatus:
ON_DECK = 1
SHOOTING = 2
REDEMPTION = 3
SOLIDARITY = 4
SITTING_OUT = 5
class Player(GameItem):
"""
Represents a user/player. Maps to any objects it uses for easy access
"""
def __init__(self, display_name):
super(GameItem).__init__(display_name)
self.table = None
self.original_seat = None
self.current_seat = None
self.player_status = None
self.num_turns = None
self.num_win = None
self.num_loss = None
self.num_drink = None
self.num_redemptions = None
class Table(GameItem):
"""
Represents a table. Maps to any objects it uses for easy access
"""
def __init(self, display_name):
super(GameItem).__init__(display_name)
self.players = []
self.seats = []
self.player_id_to_player_map = {}
self.player_seat_map = {}
self.shot_player_map = {}
self.num_shots = None
self.round_count = None
self.current_streak_count = None
class Seat(GameItem):
"""
Represents a seat at a table. Maps to any objects it uses for easy access
"""
def __init__(self):
super(GameItem).__init__()
self.left = None
self.right = None
self.cur_player = None
|
from sys import argv
script, first, third = argv
print("Here is your script", script)
print("Here is your first variable", first)
second = input("Please enter a second variable: ")
print(f"Here is the input variable {second}, and here is your last variable: {third}")
|
"""
"""
import collections
__all__ = ['ConcreteSet']
class ConcreteSet(collections.MutableSet):
"""
Set-class, used by Union and Optional.
Holds types, subject to set-theoretic operations.
Will eventually be used by Intersection and Not.
"""
def __init__(self, *data):
self.data = set()
for elm in data:
self.add(elm)
def __contains__(self, other):
return other in self.data
def __iter__(self):
return iter(self.data)
def __len__(self):
return len(self)
def add(self, value):
self.data.add(self.__validate__(value))
def remove(self, value):
self.data.remove(value)
#-----
def __validate__(self, value):
"""Default validation is a passthrough.
Override to add validation."""
return value
|
"__main__: generate the list from sys.argv"
import sys
from .assassin import generate
def main(length : int = 3):
"print a textual representation of a cycle of given length (default 3)"
for assassin, victime, action in generate(limit=length):
print(f'{assassin = }')
print(f'{victime = }')
print(f'{action = }\n')
if len(sys.argv) >= 2:
main(int(sys.argv[1]))
else:
main(3)
|
import sys
import time
def get_primos() :
i = 1
j = 1
while j < 1001 :
if is_primo(i) :
print("Primo numero ", j," : ",i)
j += 1
i += 1
return True
def is_primo(n) :
for i in range(3,n//2,2) :
if n%i == 0 :
return False
return True
def split_digits_sum(n) :
sum = 0
digits = map(int,str(n))
for i in digits :
sum = sum + i
return sum
#print('Aquí van unos cuantos números primos...')
#get_primos()
if len(sys.argv) < 2 :
print("Introduce el número que quieres comprobar")
else :
start = time.time()
if is_primo(int(sys.argv[1])) :
print("Primo!!!")
else :
print("No primo")
end = time.time()
print(end - start)
|
def merge_sort(list_):
len_ = len(list_)
if len_ <= 1:
return
mid = len_ // 2
first = list_[mid:]
second = list_[:mid]
merge_sort(first)
merge_sort(second)
i, j, k = 0, 0, 0
while j < len(first) and k < len(second):
if first[j] and second[k]:
if first[j] < second[k]:
list_[i] = first[j]
j += 1
else:
list_[i] = second[k]
k += 1
i += 1
while j < len(first):
list_[i] = first[j]
j += 1
i += 1
while k < len(second):
list_[i] = second[k]
k += 1
i += 1
|
# For random number generation
# https://cryptography.io/en/latest/random-numbers/
import os
# Library for hashBackend (openssl)
# https://cryptography.io/en/latest/hazmat/backends/
from cryptography.hazmat.backends import openssl
# Lirary for Hash functions like SHA-2 family, SHA-3 family, Blake2, and MD5
# https://cryptography.io/en/latest/hazmat/primitives/cryptographic-hashes/
from cryptography.hazmat.primitives import hashes
# Returns a random lowercase character using os.urandom
def get_rand_lowercase():
# rand_int is geneated the same was as length but with the range 97 - 122
# this range specifies the ascii values for lowercase letter in decimal
rand_int = int.from_bytes(os.urandom(1), byteorder="big")
rand_int = rand_int % (122 - 97 + 1) + 97
# convert rand_int to a char to get random character
return chr(rand_int)
# Returns a string with a length in range(min_length, max_length)
# length is randomly generated but within specified range
def get_random_string(min_length, max_length):
# empty string that will hold random characters and will eventually be returned
return_str = ""
# randomly generated byte which is then converted to an int
length = int.from_bytes(os.urandom(1), byteorder="big")
# modify length to be within the range(min_length, max_length)
length = length % (max_length - min_length + 1) + min_length
for i in range(length):
# get a random lowercase character
rand_char = get_rand_lowercase()
# append the random character to the return string
return_str = return_str + rand_char
return return_str
def gen_password_file(min_length, max_length, num_of_accounts):
# Display arguments to the console
print("Min length:", min_length)
print("Max length:", max_length)
print("Generating", num_of_accounts, "account(s)")
# Create/Open the password files
password_file0 = open("accounts0.txt", "w") # Plaintext
password_file1 = open("accounts1.txt", "w") # Hashed
password_file2 = open("accounts2.txt", "w") # Salted Hash
for i in range(num_of_accounts):
# Create username "userN" where N = range(0, num_accounts)
username = "user" + str(i)
# Create random password
password = get_random_string(min_length, max_length)
# Get salt
salt = get_random_string(1, 1)
# Append salt to password to get salted password
salted_password = password + salt
# Display details to the console
print("Username:\t", username)
print("Password:\t", password)
print("Salt:\t\t", salt)
# Encode passwords in ascii for hashing purposes
byte_password = password.encode("ascii")
byte_salted_password = salted_password.encode("ascii")
# Hash the password w/out salt
digest0 = hashes.Hash(hashes.SHA256(), backend=openssl.backend)
digest0.update(byte_password)
hash_password = digest0.finalize()
hash_password = hash_password.hex()
# Hash the password with salt
digest0 = hashes.Hash(hashes.SHA256(), backend=openssl.backend)
digest0.update(byte_salted_password)
salted_hash_password = digest0.finalize()
salted_hash_password = salted_hash_password.hex()
# Display hashes to the console
print("Hashword:\t", hash_password)
print("Salted:\t\t", salted_hash_password)
# Writing plaintext passwords
password_file0.write(username + "," + password + "\n")
# Writing hashed passwords
password_file1.write(username + "," + hash_password + "\n")
# Writing salted hash passwords
password_file2.write(username + "," + salted_hash_password + "," + salt + "\n")
def generate_accounts():
acceptable_input = False
while not acceptable_input:
# Get required values for account generation
min_length = int(input("Enter min password length: "))
max_length = int(input("Enter max password length: "))
num_of_accounts = int(input("Enter # of accounts to generate: "))
# Validate input is acceptable
if min_length <= 0 or min_length > max_length:
print("Min password length must be greater than 0 and less than max password length")
if max_length <= 0 or max_length > 64:
print("Max password length must be greater than 0 and less than 64")
if num_of_accounts < 0 or num_of_accounts > 1000:
print("Number of accounts to be generated must be greater than 0 and less than or equal to 1000")
else:
acceptable_input = True
gen_password_file(min_length, max_length, num_of_accounts)
if __name__ == "__main__":
generate_accounts()
|
from abc import ABC, abstractmethod
from Elevator.wrappers import printlog
# abc can not be instantiated itself, subclasses need to implement all abstract methods (override) but can provide
# custom logic via super()
# abc is a form of interface checking more strict than hasattr(), we get error upon instantiation
class ElevatorABC(ABC):
def __init__(self):
# distance between each floor in terms of m
self.distance = 3
self._available_floors = range(0, 16)
@abstractmethod
def stats(self):
# this method will be provided by inheriting classes
print('abstract base class method printing')
@property
@abstractmethod
def floor(self):
# this property will be provided by inheriting classes
print('abstract base class property printing')
pass
class Elevator(ElevatorABC):
def __init__(self, *, speed=None):
super().__init__()
if speed is not None:
# default speed of elevator in terms of m/s
self.speed = speed
else:
self.speed = 1.2
self._floor = 0
self.total_time_elapsed = 0
self.total_distance = 0
# all floors visited will be kept in the log sequentially
self.log_floor = []
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count <= len(self.log_floor):
result = self.log_floor[self.count]
self.count +=1
return result
else:
raise StopIteration
@property
def floor(self):
# print('Getting value')
return self._floor
@floor.setter
def floor(self, destination):
# current_floor = self._floor
# print(current_floor)
if destination not in self._available_floors:
print(f'Available floors are {min(self._available_floors)} to {max(self._available_floors)}')
raise Exception
else:
# print(f'Setting value to {destination}')
self._floor = destination
@classmethod
def slow_elevator(cls):
slow_speed = 1
return cls(speed=slow_speed)
@printlog
def go_to_floor(self, destination):
current_floor = self.floor
self.floor = destination
if destination == current_floor:
print(f'You are already on floor {self.floor}')
else:
if destination > current_floor:
print(f'Ascending to: {self.floor}')
elif destination < current_floor:
print(f'Descending to: {self.floor}')
print(f'Congratulations, you arrived at floor {self.floor}')
self.total_time_elapsed += (abs(current_floor - self.floor) * self.distance) / self.speed
self.total_distance += abs(current_floor - destination) * self.distance
self.log_floor.append(destination)
def stats(self):
super().stats()
print(f'{self.__class__.__name__} travelled {self.total_distance} meters in {self.total_time_elapsed} seconds. \n'
f' All floors visited: {self.log_floor}')
# contains as much info about obj as possible to create an accurate representation of the obj
def __repr__(self):
return '{!s}({!r},{!r},{!r})'.format(self.__class__.__name__, self.floor, self.total_time_elapsed, self.total_distance)
# human readable definition of the object.
def __str__(self):
return '{} is currently on floor: {}. It has travelled for {} meters'.format(self.__class__.__name__, self.floor, self.total_distance)
class SmallElevator(Elevator):
# demonstrates inheritance
def __init__(self, *, name=None):
# call __init__ on subclass as seen by the superclass
super().__init__()
self.speed = 1.1
self._available_floors = range(0, 9)
# name is an optional keyword argument, created as an attribute only when given.
# Demonstrates added functionality to subclass without breaking existing function calls
if name is not None:
self.name = name
# override parent's __repr__ method (Default Implementation of __repr__)
def __repr__(self):
return '<{0}.{1} object at {2}>'.format(self.__module__, type(self).__name__, hex(id(self)))
def stats(self):
if hasattr(self, 'name'):
print(f'{self.name} travelled {self.total_distance} meters in {self.total_time_elapsed} seconds. \n'
f' All floors visited: {self.log_floor}')
else:
super(SmallElevator, self).stats()
# todo: multiple inheritance, encapsulation?
|
class enum(object):
"""Just plug in a dict to give a mapping of strings to other values."""
def __init__(self, enumdict=None):
self.enum_dict = enumdict
def run(self, val):
if self.enum_dict:
self.enum_dict.get(val, None)
|
#Man-Shaped Pinata
import sys
men = {
1:"""
-----
| |
|
|
|
|
|
----------
""",
2:"""
-----
| |
| O
|
|
|
|
----------
""",
3:"""
-----
| |
| O
| |
|
|
|
----------
""",
4:"""
-----
| |
| O
| /|
|
|
|
----------
""",
5:"""
-----
| |
| O
| /|\\
| |
|
|
----------
""",
6:"""
-----
| |
| O
| /|\\
| |
| /
|
----------
""",
7:"""
-----
| |
| O
| /|\\
| |
| / \\
|
----------
"""}
print("\n" * 100)
print("""Enter a word to initiate the game. Enter \"q\" to exit the program.
While guessing, enter \"quit\" to exit the program.""")
while(True):
text = input()
if(text == "q"):
sys.exit()
word = list(text)
length = len(word)
guessed = []
state = 1
health = 1
print("\n" * 100)
while(state == 1):
print("\n" * 100, men[health], "Word: ", end = "")
#printing censored word
for i in range (0,length):
if(word[i] in guessed):
print(word[i], " ", end = "")
else:
print("_ ", end = "")
print("\n")
#end game conditions
check = True
for i in range (0,length):
if(word[i] not in guessed):
check = None
break
if(check):
state = 2
break
if(health == 7):
state = 0
break
#accept a guess,
print("Guess: ", end = "")
guess = input()
if(guess == "quit"):
sys.exit()
#add guessed letter to list of guesses, check if it was correct
if(guess not in guessed):
guessed.append(guess)
if(guess not in word):
health += 1
#win/lose conditions
if(state == 0):
print("You lost. Type in another word to play again.")
if(state == 2):
print("You won! Type in another word to play again.")
|
class Node(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.left = None
self.right = None
self.size = 1
class Binery_Tree(object):
def __init__(self):
self.node = None
self.size = 0
def insert(self, tree, node):
if tree.node is None:
tree.node = node
tree.size = tree.size + 1
else:
if tree.node.x > node.x:
if tree.left is not None:
tree.insert(tree.left, node)
else :
tree.left = node
tree.size = tree.size + tree.left.size
if tree.noded.x < node.x:
if tree.right is not None:
tree.insert(tree.right, node)
else :
tree.right = node
tree.size = tree.size + tree.right.size
def delete(self, node):
x = [72, 57, 74, 64]
y = [50, 67, 55, 60]
def getTree(x, y):
if x is None or y is None:
return None
tree = Binery_Tree()
for i in range(0, len(n)-1):
tree.insert(Node(x[i], y[i]))
if tree.x > x[i+1] and tree.y > y[i+1]:
continue
elif tree.x < x[i+1] and tree.y < y[i+1]:
tree.swapNode(tree.root, Node(x[i+1], y[i+1])
else:
tree.insert(Node(x[i+1], y[i+1]))
return tree
|
'''1.在一个二维数组中(每个一维数组的长度相同),
每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,
判断数组中是否含有该整数。
'''
#二分查找
def Find(target, array):
# write code here
for i in array:
for x in i:
if target == x:
return True
else:
continue
return False
a = []
for i in range(5):
a.append([i])
for y in range(1, 5):
a[i].append(i + y)
print(Find(5,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]))
'''
2.请实现一个函数,将一个字符串中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.
则经过替换之后的字符串为We%20Are%20Happy。
'''
def replaceSpace(s):
# s1 = s.split(' ')
# s2 = ('%20').join(s1)
return s.replace(' ','%20')
print(replaceSpace('hello world'))
'''
3.
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
'''
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if listNode is None:
return []
return self.printListFromTailToHead(listNode.next) + [listNode.val]
a = []
b = [1, 3]
print(a+b)
|
# Luyện tập cách xây dựng hàm, sử dụng hàm, các lệnh vẽ, tùy chỉnh bút vẽ trong thư viện turtle.
import turtle
t = turtle.Turtle()
def home_draw(x,y):
t.pencolor("blue")
for j in range(2):
for k in range(1,3):
t.fillcolor("pink")
t.begin_fill()
t.penup()
if(j==0):
t.goto(x*(k-1),0)
else:
t.goto(x*(k-1),y)
t.pendown()
for i in range(2):
t.forward(x)
t.left(90)
t.forward(y)
t.left(90)
t.end_fill()
a = (x/3)+x*(k-1)
b = (y/3)+j*y
t.penup()
t.goto(a,b)
t.pendown()
t.fillcolor("white")
t.begin_fill()
for i in range(2):
t.forward(x/3)
t.left(90)
t.forward(y/3)
t.left(90)
t.end_fill()
t.penup()
t.goto(x,0)
t.pendown()
t.penup()
t.goto(x*j,y)
t.pendown()
t.penup()
t.goto(x*2,0)
t.pendown()
t.fillcolor("pink")
t.begin_fill()
for i in range(2):
t.forward(x*1.5)
t.left(90)
t.forward(y)
t.left(90)
t.end_fill()
for r in range(2):
t.fillcolor("brown")
t.begin_fill()
t.penup()
t.goto(x*2+(x*1.5/4)*(r+1),0)
t.pendown()
for s in range(2):
t.forward((x*1.5)/4)
t.left(90)
t.forward(y/2)
t.left(90)
t.end_fill()
home_draw(100,150)
|
#Hiển thị ngày trong tuần
# 1: Monday
# 2: Tuesday
# 3: Wednesday
# 4: Thursday
# 5: Friday
# 6: Saturday
# 7: Sunday
Number = int(input("Vui lòng nhập 1 số trong khoảng từ (1~7):"))
if(Number == 0 or Number > 7):
print("error, out of range")
elif(Number==1):
print("Monday")
elif(Number==2):
print("Tuesday")
elif(Number==3):
print("Wednesday")
elif(Number==4):
print("Thursday")
elif(Number==5):
print("Friday")
elif(Number==6):
print("Saturday")
else:
print("Sunday")
|
def take_input():
books_no, lib_no, total_days = map(int, input().split())
book_scores = list(map(int, input().split()))
list_of_lib = []
def sortonscore(val):
return book_scores[val]
for i in range(lib_no):
lib_info = tuple(map(int,input().split()))
lib_books = list(map(int, input().split()))
#lib_books has a list of the book ids for the books in that lib
# sort this according to their scores ->
lib_books.sort(key=sortonscore,reverse=True)
list_item_to_add = [lib_info, lib_books]
list_of_lib.append(list_item_to_add)
return books_no,list_of_lib, total_days
#list_of_lib = [ [(5,2,2),[0,1,2,3,4]], [(4,3,1),[3,2,5,0]] ]
#books_to_scan = [1,2,3,6,5,4]
booksno,list_of_lib, total_days = take_input()
books_to_scan = list(range(0,booksno))
# [ (no_of_books,time_signup,scanning_rate),[bookslist..] ]
# check minimum number of days for signup
lib_no_and_signup_time=[]
i=0
for lib in list_of_lib:
signup_time=lib[0][1]
lib_no_and_signup_time.append((i,signup_time))
i+=1
def sortSecond(val):
return val[1]
lib_no_and_signup_time.sort(key=sortSecond)
days_passed=0
lib_already_signed_up = []
for item in lib_no_and_signup_time:
if(books_to_scan == []):
break
shipping_rate = list_of_lib[item[0]][0][2]
no_books_in_lib = list_of_lib[item[0]][0][0]
books_in_lib = list_of_lib[item[0]][1]
if((set(books_in_lib)&set(books_to_scan)) and days_passed+item[1]<=total_days ):
lib_already_signed_up.append([item[0]])
days_passed+=item[1]
days_remaining = total_days-days_passed
if(no_books_in_lib <= (days_remaining * shipping_rate)):
#scan all books blindly
lib_already_signed_up[-1].append(books_in_lib) #results in a list of lists. [[lib_idx, books_scanned]]
#remove respective books from book list needed
for book in books_in_lib:
if book in books_to_scan:
books_to_scan.remove(book)
else:
#compare book in lib with books_list_needed
commonbooks = []
for book in books_in_lib:
if book in books_to_scan:
commonbooks.append(book)
#sort books in descending order according to book score
#remove days_remaining*shipping_rate no. of books
lib_already_signed_up[-1].append(books_in_lib[0:days_remaining*shipping_rate])
for book in books_in_lib[0:days_remaining*shipping_rate]:
if book in books_to_scan[0:days_remaining*shipping_rate]:
books_to_scan.remove(book)
#remove respective books from book list needed
else:
break
no_of_lib_signedup = len(lib_already_signed_up)
print(no_of_lib_signedup)
for lib in lib_already_signed_up:
print(str(lib[0]) + ' ' + str(len(lib[1])))
for book in lib[1]:
print(book, end=' ')
print()
|
# The python interpreter goes through your code line by line, and tries to make
# sense of it. If it sees a line prefixed with # it ignores it. This is called
# a COMMENT, and is just used to provide more information to other humans
# reading your code.
# However, if it sees a line that is not a comment, it will try to parse it:
# if it succeeds, i. e. the line of code uses proper key words and syntax, it
# executes the line. For example, the following line prints to the console:
print("Hello World")
print("-----------")
# Feel free to change replace "Hello World" with something else.
# Let's begin with VARIABLES: think of variables in python as a bucket which
# has a label (variable name) and may or may not have a content. The bucket is
# not specific to what it can contain, and it's contents can be read and
# changed. Below, we are creating a variable a, and filling it with a number,
# then printings its contents, changing its contents with a different number
# and printing it again. Filling the bucket is then called ASSIGNING a value to
# a variable.
print("Let's print variables:")
a = 5
print(a)
a = 9
print(a)
# We are free to use whatever names we want for our variables as long as it
# doesn't contain spaces. Feel free to change the variable name in the example
# below.
bucket = 11
print(bucket)
# If we want to use text in python, we need to differentiate it from variable
# names. So if we want to deal with variable names, we just type its name
# directly. If we want to actually use text, we surround it by "". This is then
# called a string, and we can use it in variables just like numbers.
bucket = "bucket"
print(bucket)
print("-----------")
# Next are FUNCTIONS, which are a set of statements that we want to execute in
# the same sequence frequently. We declare them as follows, where function_name
# again can't contain spaces. Notice how the statements it contains are
# indented, this is quite important. As soon as the indentation ends, the
# interpreter considers function declaration complete. Notice how the "Let's
# look at functions"-print statement is not part of the function.
def function_name():
print(a)
print(bucket)
print("function_name() finishes")
print("Let's look at functions:")
# Just declaring the function saves the sequence of statements for us to call
# later. To run it, we need to call the function:
print("Calling function_name() twice...")
function_name()
function_name()
print("-----------")
# Functions can be PARAMETRISED, which means giving the statements it contains
# access to variables:
print("Let's look at parameters:")
def function_with_parameters(parameter, another_parameter):
print(parameter)
print(another_parameter)
# If you then call the parametrised function, you can give it values that the
# statements it contains can use under the name you gave the parameters when
# declaring the function.
function_with_parameters(13, 17)
# You can also pass it variables you defined outside of the function. In this
# case, the function reads the values in the variables you give it, and makes
# it available for the statements it contains under the parameter name.
function_with_parameters(a, bucket)
print("-----------")
# On top of that, functions can have RETURN values, which is useful if you
# don't just want to group print statements, but perform actual computation
# and organise your code. When the function is called, it finishes as soon
# as it reaches a return statement and makes the value of the return
# statement available where the function is called.
print("Let's look at return values:")
def function_with_return_value(parameter, another_parameter):
return parameter + another_parameter
result = function_with_return_value(10,13)
print(result)
# Finally, the IF statement allows you to structure the code with conditions.
# There are many different conditions that you can check, but let's consider
# >, == and <. Notice how we use = for assigning values to variables, and == to
# make a comparison between values or variables.
test_value = 29
if test_value > 31:
print("It's not brobdingnagian")
if test_value < 31:
print("It's elephantine")
if test_value == 29:
print("It's gargantuan")
|
# This is the skeleton for exercise-2. The goal is to change the fizzbuzz()
# function so that it returns the string "fizz", if the number passed as an
# argument is divisible by 3, "buzz" if it is divisible by 5, and "fizzbuzz"
# if it is divisible by 3 and 5. You can use the predefined
# computer_remainder() function.
def compute_remainder(number, divisor):
return number % divisor
def fizzbuzz(number):
# your code goes here
# don't forget to replace the return statement below as appropriate
return number
# this part below prints the result of the fizzbuzz function for the first 45
# numbers
for number in range(0,46):
print(str(number) + " : " + str(fizzbuzz(number)))
|
import numpy as np
# --------------------------------------------------
# Example 1
# load a colour image and put it into a 3D numpy array
# -------------------------------------------------
# Example 2
# assume that arr is an n-dimensional numpy array
# apply a function to all elements of the array
# parr = np.log(arr / (1.0 - arr))
# truncate the values in arr by some maxval
# maxval = 1
# arr[arr > maxval] = maxval
# ----------------------------------------------------
# Example 3
# class definition of a multivariate Gaussian (fixed dimension = 3)
class GaussMVD:
""" Multivariate normal distribution """
dim = 3
# ===============================================
def __init__(self):
self.mean = np.zeros(GaussMVD.dim, dtype=np.float64)
self.cov = np.eye(GaussMVD.dim, dtype=np.float64)
self.det = np.linalg.det(np.matrix(self.cov))
self.normc = 1.0 / np.sqrt(np.power((2.0 * np.pi), GaussMVD.dim) * self.det)
# ===============================================
def modify(self, mean, cov):
if not ((mean.shape == (GaussMVD.dim,)) and (cov.shape == (GaussMVD.dim, GaussMVD.dim))):
raise Exception("Gaussian: shape mismatch!")
self.mean = np.array(mean, dtype=np.float64)
self.cov = np.array(cov, dtype=np.float64)
self.det = np.linalg.det(np.matrix(self.cov))
self.normc = 1.0 / np.sqrt(np.power((2.0 * np.pi), GaussMVD.dim) * self.det)
return None
# ===============================================
def compute_probs(self, arr):
""" compute probabilities for an array of values """
inv_cov = np.asarray(np.linalg.inv(np.matrix(self.cov)))
darr = arr - self.mean
varr = np.sum(darr * np.inner(darr, inv_cov), axis=-1)
varr = - varr * 0.5
varr = np.exp(varr) * self.normc
return varr
# ===============================================
def estimate(self, arr, weight):
""" estimate parameters from data (array of values & array of weights) """
eweight = weight[..., np.newaxis]
wsum = np.sum(weight)
dimlist = list(range(len(arr.shape) - 1))
dimtup = tuple(dimlist)
# estimate mean
mean = np.sum(eweight * arr, axis=dimtup) / wsum
# estimate covariance
darr = arr - mean
cov = np.tensordot(darr, darr * eweight, axes=(dimlist, dimlist)) / wsum
self.modify(mean, cov)
return None
# ===============================================
def compute_distance(self, mvgd):
""" Bhattacharyya distance """
ccov = (self.cov + mvgd.cov) / 2.0
inv_ccov = np.asarray(np.linalg.inv(np.matrix(ccov)))
d_ccov = np.linalg.det(np.matrix(ccov))
cmean = self.mean - mvgd.mean
v1 = np.dot(cmean, np.tensordot(inv_ccov, cmean, 1)) / 8.0
v2 = np.log(d_ccov / np.sqrt(self.det * mvgd.det)) / 2.0
return v1 + v2
# ===============================================
def write(self):
print("Mean, covariance:")
print(repr(self.mean))
print(repr(self.cov))
|
l = list()
while s:= input():
l.append(s)
prev = set()
for i, s in enumerate(l):
post = set()
for j in range(i+1, len(l)):
post |= set(l[j])
if not (set(s) & (prev | post)):
print(s)
prev |= set(s)
|
a, b, c, = eval(input())
if a>0 and b>0 and c>0 and a+b>c and b+c>a and c+a>b :
print("Possible")
else:
print("Impossible")
|
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("spark-demo").getOrCreate()
"""# DataFrame
## Read the CSV file into a DataFrame
"""
bankProspectsDF = spark.read.csv("bank_prospects.csv",header=True)
"""## Remove the record with unknow value in country column"""
bankProspectsDF1 = bankProspectsDF.filter(bankProspectsDF['country'] != "unknown")
"""## Cast the String datatype to Integer/Float"""
from pyspark.sql.types import IntegerType,FloatType
bankProspectsDF2 = bankProspectsDF1.withColumn("age", bankProspectsDF1["age"].cast(IntegerType())).withColumn("salary", bankProspectsDF1["salary"].cast(FloatType()))
"""## Replace Age and Salary with average values of their respective column
import mean from sql.fuctions
"""
from pyspark.sql.functions import mean
"""### Calculate "mean" value of the age"""
mean_age_val = bankProspectsDF2.select(mean(bankProspectsDF2['age'])).collect()
mean_age = mean_age_val[0][0]
"""### Calculate mean salary value"""
mean_salary_val = bankProspectsDF2.select(mean(bankProspectsDF2['salary'])).collect()
mean_salary = mean_salary_val[0][0]
"""### Replace missing age with average value"""
bankbankProspectsDF3 = bankProspectsDF2.na.fill(mean_age,["age"])
"""### Replace missing age with salary value"""
bankbankProspectsDF4 = bankbankProspectsDF3.na.fill(mean_salary,["salary"])
"""## Write the transformed file to a new csv file"""
bankbankProspectsDF4.write.format("csv").save("bank_prospects_transformed")
|
class Employee():
def __init__(self,name,mname,salary):
self.name = name
self.mname = mname
self.salary = salary
emp=Employee("John","Moses",34566)
print("Employees deatils:\n")
print("name:{}, manager name:{}, sal:{}".format(emp.name,emp.mname,emp.salary))
|
lenght = input("请输入长:")
width = input("请输入宽:")
lenght_num = int (lenght)
width_num = int(width)
i = 1
j = 1
while i<=width_num:
print("*"*lenght_num)
i=i+1
|
class Cat:
#属性
def __init__(self,new_name,new_age):
self.name = new_name
self.age = new_age
#方法
def eat(self):
print("吃")
def drink(self):
print("喝")
def introduce(self):
print("%s的年龄是%d"%(self.name,self.age))
#创建一个对象
tom = Cat("汤姆",40)
tom.eat()
tom.drink()
#给tom添加属性
#tom.name = "汤姆"
#tom.age = 40
#print("%s的年龄是%d"%(tom.name,tom.age))
tom.introduce()
lanmao = Cat("蓝猫",10)
#lanmao.name = "蓝猫"
#lanmao.age = 10
lanmao.eat()
lanmao.drink()
lanmao.introduce()
|
ticket = 1 #1表示有车票
knifeLength = 50#cm
if ticket == 1:
print("通过车票检查,进入车站,接下来安检")
if knifeLength <=10:
print("通过了安检,进入到候车亭")
else:
print("安检没通过")
else:
print("没买票,不能进站")
|
class Node:
def __init__(self, val):
self.ainz = None
self.ooal = None
self.gown = val
class Tree:
def __init__(self):
self.root = None
def getRoot(self):
return self.root
def add(self, val):
if(self.root == None):
self.root = Node(val)
else:
self._add(val, self.root)
def _add(self, val, node):
if(val < node.gown):
if(node.ainz != None):
self._add(val, node.ainz)
else:
node.ainz = Node(val)
else:
if(node.ooal != None):
self._add(val, node.ooal)
else:
node.ooal = Node(val)
def find(self, val):
if(self.root != None):
return self._find(val, self.root)
else:
return None
def _find(self, val, node):
if(val == node.gown):
return node
elif(val < node.gown and node.ainz != None):
self._find(val, node.ainz)
elif(val > node.gown and node.ooal != None):
self._find(val, node.ooal)
def deleteTree(self):
self.root = None
def printTree(self):
if(self.root != None):
self._printTree(self.root)
def _printTree(self, node):
if(node != None):
self._printTree(node.ainz)
print str(node.gown) + ' '
self._printTree(node.ooal)
tree = Tree()
tree.add('Albedo')
tree.add('Demiurge')
tree.add('Cocytus')
tree.add('Shallter')
tree.add('Garguantua')
tree.add('Aura')
tree.add('Mare')
tree.add('Garguantua')
tree.add('Victim')
tree.add('Pandoras Actor')
tree.printTree()
print (tree.find('Albedo')).gown
print tree.find('Momongga')
tree.deleteTree()
tree.printTree()
|
for x in "Python":
print(x)
for x in range(5):
print(x)
for x in range(0, 10, 2):
print(x)
|
import sys
with open(sys.argv[1], "r") as f:
data = f.read().split("\n")
numbers = list(map(int, data))
def insum(num, numbers):
for i, x in enumerate(numbers):
for y in numbers[:i] + numbers[i+1:]:
if x + y == num: return True
return False
def part1(nums):
for i, e in enumerate(nums[25:]):
if not insum(e, nums[i:i+25]): return e
print(part1(numbers))
def part2(nums):
invalid = part1(numbers)
i, j = 0, 0
while (s := sum(nums[i:j+1])) != invalid:
if s < invalid: j += 1
elif s > invalid: i += 1
return min(nums[i:j+1]) + max(nums[i:j+1])
print(part2(numbers))
|
# Background
class Background(object):
def __init__(self, constant=0.0, prefactor=0.0, alpha=-2.0, prefactor2=0.0, alpha2=-1.5):
''' This is a background of type:
constant + prefactor*q^alpha + prefactor2*q^alpha2
Nothing special, but since it is so common an object is left for bookkeeping.
'''
self.constant=constant
self.prefactor=prefactor
self.alpha=alpha
self.prefactor2=prefactor2
self.alpha2=alpha2
def update(self, constant=0.0, prefactor=0.0, alpha=-2.0, prefactor2=0.0, alpha2=-1.5):
''' Routine to update if necessary.
'''
self.constant=constant
self.prefactor=prefactor
self.alpha=alpha
self.prefactor2=prefactor2
self.alpha2=alpha2
def __call__(self, q):
''' Returns the background. '''
return self.prefactor*( q**(self.alpha) ) + self.prefactor2*( q**(self.alpha2) ) + self.constant
|
'''
lab7 while loop
'''
#3.1
i=0
while i<=5:
if i !=3:
print(i)
i= i+1
#3.2
i= 1
result =1
while i<=5:
result = result *i
i = i+1
print(result)
#3.3
i= 1
result = 0
while i<=5:
result = result +i
i = i+1
print(result)
#3.4
i= 3
result =1
while i<=8:
result = result *i
i = i+1
print(result)
#3.5
i= 4
result =1
while i<=8:
result = result *i
i = i+1
print(result)
#3.6
num_list = [12,32,43,35]
while num_list:
num_list.remove(num_list[0])
print(num_list)
|
import sys
import heapq
def fractional_knapsack(capacity, cost_and_volumes):
order = [(-c / v, v) for c, v in cost_and_volumes]
heapq.heapify(order)
total_cost = 0
while order and capacity:
c_per_v, v = heapq.heappop(order)
can_take = min(v, capacity)
total_cost -= c_per_v * can_take
capacity -= can_take
return total_cost
def main():
reader = (tuple(map(int, line.split())) for line in sys.stdin)
n, capacity = next(reader)
cost_and_volumes = list(reader)
ans = fractional_knapsack(capacity, cost_and_volumes)
print("{:.3f}".format(ans))
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.