text stringlengths 37 1.41M |
|---|
"""
Call two arms equally strong if the heaviest weights they each are able to lift are equal.
Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.
Given your and your friend's arms' lifting capabilities find out if you two are equally strong.
"""
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
yourStongest = max(yourLeft, yourRight)
yourWeakest = min(yourLeft, yourRight)
friendsStrongest = max(friendsLeft, friendsRight)
friendsWeakest = min(friendsLeft, friendsRight)
return (yourStongest == friendsStrongest) and (yourWeakest == friendsWeakest)
if __name__ == "__main__":
def test(value, expect):
test = areEquallyStrong(value[0],value[1],value[2],value[3]);
if test != expect:
print("MISTAKE %s != %s (value was \"%s\")"%(test, expect, value))
else:
print("CORRECT %s == %s (value was \"%s\")"%(test, expect, value))
print("TESTS:")
test([20,15,5,20], False)
test([15,10,15,9], False)
test([15,10,15,10], True)
test([10,15,15,10], True)
|
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
#Getting data to test
digits = datasets.load_digits()
#Algorithm used, gamma = 'size of leap(refer to yt tutorial p.2)'
clf = svm.SVC(gamma=0.0001, C=100)
#Printing length of dataset
print(len(digits.data))
#Training based on dataset
x,y = digits.data[:-10], digits.target[:-10]
clf.fit(x,y)
#Printing and predicting
print 'Prediction: ',clf.predict(digits.data[-6])
#Showing the prediction using matplotlib
plt.imshow(digits.images[-6], cmap=plt.cm.gray_r, interpolation="nearest")
plt.show()
|
import unittest
from src.customer import Customer
from src.pub import Pub
from src.drink import Drink
class TestCustomer(unittest.TestCase):
def setUp(self):
self.customer1 = Customer("sadie", 30.00, 30)
self.customer2 = Customer('matt', 0.00, 14)
self.drink1 = Drink('beer', 4.50, 5)
self.drink2 = Drink('cider', 4.00, 8)
list_of_drinks = [self.drink1, self.drink2]
self.pub = Pub('codeclan arms', 100.00, list_of_drinks)
def test_customer_name(self):
self.assertEqual("sadie", self.customer1.name)
def test_has_wallet(self):
self.assertEqual(30.00, self.customer1.wallet)
def test_check_enough_money__has_enough(self):
affordability_check = self.customer1.check_enough_money(self.drink1)
self.assertEqual(True, affordability_check)
def test_check_enough_money__does_not_has_enough(self):
affordability_check = self.customer2.check_enough_money(self.drink1)
self.assertEqual(False, affordability_check)
def test_money_left_wallet(self):
self.pub.sell_a_drink('beer', self.customer1)
self.assertEqual(25.50, self.customer1.wallet)
def test_check_drink_exists__does(self):
drink_that_youre_looking_for = self.pub.get_drink_by_name('beer')
existence_check = self.pub.check_drink_exists(drink_that_youre_looking_for)
self.assertEqual(True, existence_check )
def test_check_drink_exists__doesnot(self):
drink_that_youre_looking_for = self.pub.get_drink_by_name('wine')
existence_check = self.pub.check_drink_exists(drink_that_youre_looking_for)
self.assertEqual(False, existence_check)
def test_buy_a_drink__drink_exists(self):
self.pub.sell_a_drink('beer', self.customer1)
self.assertEqual(25.50, self.customer1.wallet)
self.assertEqual(104.50, self.pub.till)
def test_buy_a_drink__drink_does_not_exists(self):
self.pub.sell_a_drink('wine', self.customer1)
self.assertEqual(30.00, self.customer1.wallet)
self.assertEqual(100.00, self.pub.till)
def test_customer_has_age(self):
self.assertEqual(30, self.customer1.age)
def test_customer_has_drunkenness_level(self):
self.assertIsNotNone(self.customer1.drunkenness_level)
# @unittest.skip("Delete this line to run the test")
def test_customer_gets_drunk__one_drink(self):
self.customer1.drink_drink(self.drink1)
self.assertEqual(5, self.customer1.drunkenness_level)
# @unittest.skip("Delete this line to run the test")
def test_customer_gets_drunk__multiple_drinks(self):
self.customer1.drink_drink(self.drink1)
self.customer1.drink_drink(self.drink2)
self.assertEqual(13, self.customer1.drunkenness_level)
|
import sys
#take in the desired index of fibonacci number as a command
#line arg
if len(sys.argv)!=2:
print("Please enter the desired index of fibonacci number"
" as a command line argument")
n1 = int(sys.argv[1])
def recursiveFib(n):
if n == 1 or n == 2:
return 1
else:
return recursiveFib(n-1) + recursiveFib(n-2)
print("Fibonacci(%d) is : %d" % (n1, recursiveFib(n1)))
|
a = float(input()); b = a*a; c = b*b; d = c*c
print("{:.3f}".format(d * b))
|
import scipy.stats as stats
import numpy as np
from data import Data
def read_data(fdir, fname, vector_size):
"""
Opens the file using that Data class members and reads in the data.
Data is stores as a list of tuples: [(val1, val2), (val1, val2)]
Tuple value 1 is the vector (list)
Tuple value 2 is the label for the vector (int)
"""
with open(fdir+fname, 'r') as f:
data = f.readlines()
data = [ x.strip().split(' ') for x in data ] # strip \n and split using ' '
data = [ [float(y) for y in x] for x in data ] # convert all values to ints
data = [ (np.array(x[:vector_size]), x[vector_size]) for x in data ] # convert to tuple
return data
class D_Node(object):
"""
A decision tree node. Contains a list of the node's data set, calculates its entropy,
and can be used to generate the most information gaining split. Assumes all data vectors
are the same size
"""
def __init__(self, data_set, build_subtree = False, depth = 1, tree = None):
self.data_set = data_set
self.depth = depth
self.vector_size = len(data_set[0][0])
self.left_child = None
self.right_child = None
self.entropy = self._calculate_entropy()
if not self.is_pure:
self.feature, self.threshold = self._select_feature_and_threshold()
if build_subtree:
less_than = [tup for tup in self.data_set if tup[0][self.feature] <= self.threshold]
greater_than = [tup for tup in self.data_set if tup[0][self.feature] > self.threshold]
self.left_child = D_Node(less_than, build_subtree = True, depth = depth + 1)
self.right_child = D_Node(greater_than, build_subtree = True, depth = depth + 1)
def _select_feature_and_threshold(self):
thresholds = [self._best_threshold_for_feature(i) for i in range(self.vector_size)]
min_entropy_threshold = None
best_feature = None
for feature_index, threshold_tuple in enumerate(thresholds):
if threshold_tuple[0] is None or threshold_tuple[1] is None:
continue
curr_threshold, curr_entropy = threshold_tuple
if best_feature is None:
min_entropy_threshold = threshold_tuple
best_feature = feature_index
elif curr_entropy < min_entropy_threshold[1]:
min_entropy_threshold = threshold_tuple
best_feature = feature_index
return best_feature, min_entropy_threshold[0]
def _calculate_entropy(self, data_set_in = None):
"""
Calculates the entropy of this node's dataset, as well as determining whether
or not the data set is pure. If it's pure, then it's a leaf node.
"""
if data_set_in is None:
data_set = self.data_set
else:
data_set = data_set_in
# Count the occurences of each label in the dataset
unique_labels, counts = np.unique([tup[1] for tup in data_set], return_counts=True)
if len(unique_labels) > 1 and data_set_in is None:
self.is_pure = False
self.decision = max(unique_labels, key= lambda l : counts[unique_labels.tolist().index(l)])
elif len(unique_labels == 1) and data_set_in is None:
self.is_pure = True
self.decision = unique_labels[0]
# Normalize the list of counts into a list of probabilities.
probabilities = counts.astype('float') / len(data_set)
return stats.entropy(probabilities)
def _best_threshold_for_feature(self, feature_index):
"""
Calculates which threshold minimizes the entropy of the resultant subsets,
given that we are splitting based on feature 'feature_index'
"""
feature_values = [(vector[0][feature_index], vector[1]) for vector in self.data_set]
unique_values = np.unique([tup[0] for tup in feature_values])
# TODO? ADD FIX FOR EXACT DATAPOINT WITH DIFFERENT LABELS, IE
# [([2], 1), ([2], 0), ([1], 0), ([1], 0)]
best_threshold = None
min_entropy = None
for i in range(1, len(unique_values)):
threshold = (unique_values[i] + unique_values[i - 1]) / 2.0
less_than = [tup for tup in feature_values if tup[0] <= threshold]
greater_than = [tup for tup in feature_values if tup[0] > threshold]
p_less_than = len(less_than) / float(len(feature_values))
p_greater_than = len(greater_than) / float(len(feature_values))
cond_entropy = p_less_than*self._calculate_entropy(less_than) + p_greater_than*self._calculate_entropy(greater_than)
if best_threshold is None:
best_threshold = threshold
min_entropy = cond_entropy
elif cond_entropy < min_entropy:
best_threshold = threshold
min_entropy = cond_entropy
return (best_threshold, min_entropy)
def classify(self, data_in):
if self.is_pure:
return self.decision
if data_in[self.feature] <= self.threshold:
return self.left_child.classify(data_in)
else:
return self.right_child.classify(data_in)
def __str__(self):
if self.is_pure:
return '%d: Selecting %d' % (self.depth, self.decision)
else:
return '%d: Is Feature %d <= %f (Majority %d)' % (self.depth, self.feature + 1, self.threshold, self.decision)
class D_Tree(object):
"""
A full decision tree, with the root
"""
def __init__(self, data_set):
self.data_set = data_set
self.root = D_Node(data_set, build_subtree = True, tree = self)
def classify(self, data_in):
n = self.root
while n:
if n.is_pure:
return n.decision
if data_in[n.feature] <= n.threshold:
n = n.left_child
else:
n = n.right_child
def error(self, validation_data, pruning_node = None):
total = len(validation_data)
hits = 0.0
misses = 0.0
for vector, label in validation_data:
n = self.root
while n:
# If this is the node we are testing for pruning,
# stop the classification here and predict the majority
# label in n
if n is pruning_node and n is not None:
if n.decision == label:
hits += 1.0
else:
misses += 1.0
break
if n.is_pure:
if n.decision == label:
hits += 1.0
else:
misses += 1.0
break
if vector[n.feature] <= n.threshold:
n = n.left_child
else:
n = n.right_child
return (misses / total)
def prune_tree(self, validation_data, prune_once = True):
bfs_queue = [tree.root]
tree_error = self.error(validation_data)
while bfs_queue:
n = bfs_queue[0]
pruned_error = self.error(validation_data, n)
if pruned_error < tree_error:
print str(n)
print pruned_error, '<', tree_error
n.is_pure = True
n.left_child = None
n.right_child = None
tree_error = pruned_error
if prune_once:
return
if not n.is_pure:
bfs_queue.append(n.left_child)
bfs_queue.append(n.right_child)
bfs_queue.pop(0)
if __name__ == '__main__':
training_data = read_data(Data.fdir, Data.training, Data.vector_size)
test_data = read_data(Data.fdir, Data.testing, Data.vector_size)
validation_data = read_data(Data.fdir, Data.validate, Data.vector_size)
tree = D_Tree(training_data)
print 'Training Error: %f' % tree.error(training_data)
print 'Testing Error: %f' % tree.error(test_data)
tree.prune_tree(validation_data)
print 'Training Error: %f' % tree.error(training_data)
print 'Testing Error: %f' % tree.error(test_data)
tree.prune_tree(validation_data)
print 'Training Error: %f' % tree.error(training_data)
print 'Testing Error: %f' % tree.error(test_data)
|
def lineEncoding(s):
current = s[0]
amount = 1
encoded = ""
for char in s[1::]:
if char != current:
if amount == 1:
encoded += current
else:
encoded += str(amount) + current
current, amount = char, 1
else:
amount += 1
return encoded + str(amount) + current if amount > 1 else encoded + current
# https://app.codesignal.com/arcade/intro/level-11/o2uq6eTuvk7atGadR
# Given a string, return its encoding defined as follows:
# First, the string is divided into the least possible number of disjoint substrings consisting of identical characters
# --- for example, "aabbbc" is divided into ["aa", "bbb", "c"].
# Next, each substring with length greater than one is replaced with a
# concatenation of its length and the repeating character
# --- for example, substring "bbb" is replaced by "3b"
# Finally, all the new strings are concatenated together in the same order and a new string is returned.
# My solution is basically to start the current character at the first position and to move forward with a for loop
# through the string. When the next character is not equivalent to the current, the amount and current character are
# concatenated to the encoded string. However, if the amount was only 1 it will only concatenate char to
# the encoded string.
|
import re
'''
字符串切割
'''
str1 = "good good study"
print(str1.split())
print(re.split(r' +', str1))
'''
re.finditer函数
(pattern, string ,flags=0)
flags :标志位,用于控制正则表达式匹配方式
功能:扫描整个字符串,返回迭代器
'''
str3 = "good good study, good is nice,good is handsome"
d = re.finditer(r'(good)',str3)
while True:
try:
l = next(d)
print(d)
except StopIteration as e:
break
'''
字符串替换和修改
sub(pattern, repl, string, count=0, flags=0)
subn(pattern, repl, string, count=0, flags=0)
pattern:正则表达式
repl:用来替换的字符串
string:目标字符串
count:最多替换次数
功能:在目标字符串中以正则表达式的规则匹配字符串,再把它们替换为指定的字符串
区别:sub返回值类型与原类型相同,subn返回一个元组
'''
str4 = "good good study, good is nice,good is handsome"
# print(re.sub(r'(good)','beauty',str4))
print(re.subn(r'(good)','beauty',str4))
re.subn()
'''
分组:
概念:除了简单的判断是否匹配之外,正则表达式还有提取子串的功能,
用()表示的就是提取分组,内部的?P<first>是取名字为first
'''
str5 = "010-52364158"
m = re.match(r'(?P<first>\d{3})-(\d{8})',str5)
#使用序号获取对应组的信息,group(0)代表原始字符串
print(m.group(0))
print(m.group(1))
print(m.group('first'))
print(m.group(2))
#查看匹配的各组的情况
print(m.groups())
'''
编译:当我们使用正则表达式时,re模块会干两件事
1、编译正则表达式,如果正则表达式本身不合法,会报错
2、用编译后的正则表达式去匹配对象
compile(pattern, flags=0)
pattern要编译的表达式
'''
pat = r"^(1(([34578]\d)|(47))\d{8})"
re_telephone = re.compile(pat)
#此时re_telephone成为re的对象,可以使用re的所有方法
re_telephone.match('1630222222')
#re模块的调用和对象的调用
# re.match(pattern, str)
# re_telephone.match(str)
# re.reseach(pattern, str)
# re_telephone.reseach(str)
# re.findall(pattern, str)
# re_telephone.findall(str)
|
#递归遍历目录
import os
def getAllDir(path,sp=''):
fileList = os.listdir(path)
sp += ' '
for fileName in fileList:
fileAbsPath = os.path.join(path,fileName)
if os.path.isdir(fileAbsPath):
print(sp + 'dir:' + fileName)
getAllDir(fileAbsPath,sp)
else:
print(sp + 'file name:' +fileName)
getAllDir('D:\\ruanjian')
#深度遍历,栈模拟递归,深度根据栈先进后出的特点,先遍历一个文件的所有目录,再遍历同级其他目录
import os
def getAllDirDE(path):
stack = []
stack.append(path)
#处理栈,当栈为空结束循环
while len(stack) !=0 :
#从栈里取数据
dirPath = stack.pop()
#目录下所有文件
fileList = os.listdir(dirPath)
#处理每个文件,是目录继续压栈
for fileName in fileList:
fileAbsPath = os.path.join(dirPath,fileName)
if os.path.isdir(fileAbsPath):
print('目录:' + fileAbsPath)
stack.append(fileAbsPath)
else:
print('普通文件:'+ fileAbsPath)
getAllDirDE('D:\\ruanjian')
#队列模拟递归遍历目录,广度遍历
import os
import collections
def getAllDirQU(path):
queue = collections.deque()
#进队
queue.append(path)
while len(queue) != 0:
dirPath = queue.popleft()
#找出所有文件
filesList = os.listdir(dirPath)
for fileName in filesList:
fileAbsPath = os.path.join(dirPath,fileName)
if os.path.isdir(fileAbsPath):
print('目录:'+ fileAbsPath)
queue.append(fileAbsPath)
else:
print('普通文件:' + fileAbsPath)
getAllDirQU('D:\\ruanjian')
|
'''Python商业爬虫案例实战第15讲:自动生成Word报告实战 by 王宇韬'''
#如果下面的内容被我注释掉了,大家可以选中,然后ctrl+/(Spyder中的快捷键是ctrl+1)取消注释
'''15.1节:Python创建Word基础 - 基础知识1'''
'''1.python-dox初了解'''
import docx
# 创建内存中的word文档对象
file = docx.Document()
# 写入若干段落
file.add_paragraph('螃蟹在剥我的壳,笔记本在写我')
file.add_paragraph('漫天的我落在枫叶上雪花上')
file.add_paragraph('而你在想我')
# 保存,得首先创建出保存文件夹
file.save('D:\\我的文档\\三行情书.docx')
print('Word生成完毕!')
'''2.python-docx库的基础知识'''
# 1.创建Word文档
import docx
file = docx.Document()
# 2.添加标题
file.add_heading('三行情书2', level=0)
# 3.添加段落文字
file.add_paragraph('我喜欢你')
file.add_paragraph('上一句话是假的')
file.add_paragraph('上一句话也是假的')
# 4.添加图片
file.add_picture('D:\\我的文档\\三行情书.jpg')
# 5.添加分页符
file.add_page_break()
# 6.添加表格
table = file.add_table(rows=1, cols=3)
table.cell(0,0).text = '克制' # 第一行第一列
table.cell(0,1).text = '再克制' # 第一行第二列
table.cell(0,2).text = '"在吗"' # 第一行第三列
# 7.文档保存
file.save('D:\\我的文档\\三行情书2.docx')
print('三行情书2生成完毕')
# 8.读取Word文档
file = docx.Document('D:\\我的文档\\三行情书.docx') # 打开文件demo.docx
content = []
for paragraph in file.paragraphs:
print(paragraph.text) # 打印各段落内容文本
content.append(paragraph.text)
content = ' '.join(content) # 其中单引号里的空格表示利用空格进行连接
print(content)
|
#递归遍历目录
import os
def getAllDir(path,sp=''):
fileList = os.listdir(path)
sp += ' '
for fileName in fileList:
fileAbsPath = os.path.join(path,fileName)
if os.path.isdir(fileAbsPath):
print(sp + 'dir:' + fileName)
getAllDir(fileAbsPath,sp)
else:
print(sp + 'file name:' +fileName)
# getAllDir('D:\\ruanjian')
#深度遍历,栈模拟递归,深度根据栈先进后出的特点,先遍历一个文件的所有目录,再遍历同级其他目录
import os
def getAllDirDE(path):
stack = []
stack.append(path)
#处理栈,当栈为空结束循环
while len(stack) !=0 :
#从栈里取数据
dirPath = stack.pop()
#目录下所有文件
fileList = os.listdir(dirPath)
#处理每个文件,是目录继续压栈
for fileName in fileList:
fileAbsPath = os.path.join(dirPath,fileName)
if os.path.isdir(fileAbsPath):
print('目录:' + fileAbsPath)
stack.append(fileAbsPath)
else:
print('普通文件:'+ fileAbsPath)
# getAllDirDE('D:\\ruanjian')
#队列模拟递归遍历目录,广度遍历
import os
import collections
def getAllDirQU(path):
queue = collections.deque()
#进队
queue.append(path)
while len(queue) != 0:
dirPath = queue.popleft()
#找出所有文件
filesList = os.listdir(dirPath)
for fileName in filesList:
fileAbsPath = os.path.join(dirPath,fileName)
if os.path.isdir(fileAbsPath):
print('目录:'+ fileAbsPath)
queue.append(fileAbsPath)
else:
print('普通文件:' + fileAbsPath)
getAllDirQU('D:\\pyfile\\PythonSuperMario-master\\PythonSuperMario-master')
|
import tkinter
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title('heheh')
#设置大小和位置
win.geometry('400x400+200+20')
#进入消息循环
'''
Label :标签控件可以显示文本
'''
#win 父窗体
#Label 控件
# label = tkinter.Label(win, text="good",
# bg = "pink",
# fg = "red",
# font = ('黑体',15),
# width = 100,
# height = 10,
# wraplength = 10,
# justify = "left")
# #显示出来
# label.pack()
#Button控件
# def func():
# print('hahahah')
#
# button1 = tkinter.Button(win, text='按钮',command=func, width=10, height=10)
# button1.pack()
# button1 = tkinter.Button(win, text='按钮',command=win.quit, width=10, height=10)
# button1.pack()
'''
Entry:输入控件
用于显示简单文本内容
'''
#绑定变量
# e = tkinter.Variable()
# #show 密文显示 show = '*'
# entry = tkinter.Entry(win,textvariable=e)
# entry = tkinter.Entry(win,show='*')
# entry.pack()
# e.set('hahahhhh')
'''
点击按钮输入输出框中内容
'''
# def showInfo():
# print(entry.get())
# entry = tkinter.Entry(win)
# entry.pack()
# button = tkinter.Button(win, text='按钮', command=showInfo)
# buttom.pack()
'''
文本控件,用于显示多行文本
'''
#height显示行数
#创建滚动条
# scroll = tkinter.Scrollbar()
# text = tkinter.Text(win, width=30, height=4)
#
# #side放在窗体的那一侧,fill填充
# scroll.pack(side = tkinter.RIGHT, fill=tkinter.Y)
# text.pack(side=tkinter.LEFT, fill=tkinter.Y)
# #关联滚动条和text文件
# scroll.config(command=text.yview)
# text.config(yscrollcommand=scroll.set)
#
# str = '''snkjsnvjksdbvskjdfsd
# aslkfndjksnfkdjs
# sdknfkjsdhahdjuk'''
# text.insert(tkinter.INSERT,str)
'''
CheckButton多选框控件
'''
# def update():
# message = ""
# if hobby1.get() == True:
# message += "money\n"
# if hobby2.get() == True:
# message += "power\n"
# if hobby3.get() == True:
# message += "beauty\n"
# #清除text中的所有内容
# text.deleta(0.0, tkinter.END)
# #显示选中内容
# text.insert(tkinter.INSERT,message)
#
# #布尔型,要绑定的变量
# hobby1 = tkinter.BooleanVar()
# #多选框
# check1 = tkinter.Checkbutton(win,text="money", variable=hobby1,command=update)
# check1.pack()
#
# hobby2 = tkinter.BooleanVar()
# check2 = tkinter.Checkbutton(win,text="power", variable=hobby2,command=update)
# check2.pack()
#
# hobby3 = tkinter.BooleanVar()
# check3 = tkinter.Checkbutton(win,text="beauty", variable=hobby3,command=update)
# check3.pack()
#
# text = tkinter.Text(win, width=50, height = 5)
# text.pack()
'''
Radiobutton单选框
'''
# def update():
# print(r.get())
#
# r = tkinter.StringVar()
# radio1 = tkinter.Radiobutton(win, text="one", value="good", variable = r, command=update)
# radio1.pack()
#
# r = tkinter.IntVar()
# radio2 = tkinter.Radiobutton(win, text="one", value=1, variable = r, command=update)
# radio2.pack()
'''
Listbox1列表框控件,可以包含一个或多个文本框,(下拉选项框)
作用:在listbox控件的小窗口显示一个字符串
'''
# lb = tkinter.Listbox(win, selectmode=tkinter.BROWSE)
#
# lb.pack
# for item in ['good', 'nice', 'money','power', 'beauty']:
# #按顺序添加
# lb.insert(tkinter.END, item)
#
# #在开始添加
# lb.insert(tkinter.ACTIVE,'money')
# #将列表当成一个元素添加
# lb.insert(tkinter.END,['heheh','hahah'])
# #删除,参数1为开始索引,参数2为结束索引,如果不指定参数2,只删除第一个索引的内容
# lb.delete(1,3)
# lb.delete(1)
#
# #选中2-4
# lb.select_set(2,4)
# #取消选中
# lb.select_clear(2,4)
# #获取列表中的元素个数
# print(lb.size())
# #获取值
# print(lb.get(2,4))
#
# #当前选中的索引项
# print(lb.curselection())
#
# #判断一个选项是否被选中
# print(lb.selection_include(1))
'''
Listbox2列表框控件,可以包含一个或多个文本框,(下拉选项框)
作用:在listbox控件的小窗口显示一个字符串
'''
#不随鼠标变动而变动
# lbv = tkinter.StringVar()
# lb = tkinter.Listbox(win, selectmode=tkinter.SINGLE, listvariable=lbv)
# lb.pack()
# for item in ['111','222','333']:
# lb.insert(tkinter.END, item)
#
# #打印当前列表中的选项
# print(lbv.get())
#
# lbv.set(('1','2','3'))
# #绑定事件
# def myPrint(event):
# print(lb.get(lb.curselection()))
# lb.bind("<Double-Button-1>", myPrint)
'''
Listbox3支持shift和ctrl
'''
#EXTENDED 可以使listbox支持shift和ctrl
# lb = tkinter.Listbox(win, selectmode=tkinter.EXTENDED, listvariable=lbv)
# lb.pack()
# for item in ['111','222','333']:
# lb.insert(tkinter.END, item)
#
# sc = tkinter.Scrollbar(win)
# sc.pack(side=tkinter.RIGHT,fill=tkinter.Y)
# lb.configure(yscrollcommand=sc.set)
# lb.pack(side=tkinter.LEFT,fill=tkinter.BOTH)
# sc['command']=lb.yview
'''
Listbox3支持自动多选(无需按住shift和ctrl)
'''
# EXTENDED 可以使listbox支持shift和ctrl
# lb = tkinter.Listbox(win, selectmode=tkinter.MULTIPLE, listvariable=lbv)
# lb.pack()
# for item in ['111', '222', '333']:
# lb.insert(tkinter.END, item)
#
# sc = tkinter.Scrollbar(win)
# sc.pack(side=tkinter.RIGHT, fill=tkinter.Y)
# lb.configure(yscrollcommand=sc.set)
# lb.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
# sc['command'] = lb.yview
'''
Scale供用户通过拖拽指示器改变变量的值,可以水平HORIZONTAL也可以竖直VERTICAL
'''
# scale = tkinter.Scale(win, from_ = 0, to = 100, orient = tkinter.HORIZONTAL, tickinterval = 10, length=200)
# scale.pack()
#
# #设置值
# scale.set(20)
# #取值
# def showNum:
# print(scale.get())
# tkinter.Button(win,text = "按钮", command=showNum).pack()
'''
Spinbox数值范围控制
'''
#绑定变量
# v = tkinter.SpringVar()
#
# #increment 步长
# #values项显示值的元组
# sp = tkinter.Spinbox(win, from_=0, to = 100, increment=5, textvariable = v)
# sp.pack()
#
# #设置值
# v.set(20)
# #取值
# print(v.get(10))
'''
Menu 顶层菜单,没有get选项时,可以添加变量
'''
#创建菜单条
# menubar = tkinter.Menu(win)
# win.config(menu=menubar)
# menu1 = Menu(menubar, tearoff=False)
#
# #向菜单选项中添加内容
# def func():
# print('hhh')
#
# for item in ['C','C++','Python','Java','PHP', 'quit']:
# if item == 'quit':
# menu1.add_separator()
# menu1.add_command(label=item, command=win.quit)
# else:
# menu1.add_command(label=item, command=func)
#
# #向菜单条上添加菜单选项
# menubar.add_cascade(lable='语言', menu=menu1)
#
# menu2 = = Menu(menubar, tearoff=False)
# menu1.add_command(label='red')
# menu1.add_command(label='blue')
# menubar.add_cascade(lable='颜色', menu=menu2)
'''
Menu鼠标右键菜单
'''
menubar = tkinter.Menu(win)
menu = tkinter.Menu(menubar, tearoff = False)
for item in ['C','C++','Python','Java','PHP', 'quit']:
if item == 'quit':
menu1.add_separator()
menu1.add_command(label=item, command=win.quit)
else:
menu1.add_command(label=item)
menubar.add_cascade(label = '语言', menu=menu)
def showMenu(event):
menubar.post(event.x_root, event.y_root)
win.bind("<Button-3>",showMenu)
'''
Combobox下拉控件
'''
from tkinter import ttk
#绑定变量
cv = tkinter.StringVar()
com = ttk.Combobox(win, textvariable=cv)
com.pack()
#设置下拉数据
com['value'] = ('济南','济宁','潍坊')
#设置默认值
com.current(0)
#绑定事件
def func(event):
print(com.get())
com.bind('<<ComboboxSelected>>',func)
'''
Frame控件,框架控件
在屏幕上显示一个矩形区域,多作为容器控件
'''
frm = tkinter.Frame(win)
frm.pack()
#left
frm_l = tkinter.Frame(frm)
tkinter.Lable(frm_l,text='左上',bg='pink').pack(side=tkinter.TOP)
tkinter.Lable(frm_l,text='左下',bg='blue').pack(side=tkinter.TOP)
frm_l.pack(side=tkinter.LEFT)
#Right
frm_r = tkinter.Frame(frm)
tkinter.Lable(frm_r,text='左上',bg='red').pack(side=tkinter.TOP)
tkinter.Lable(frm_r,text='左下',bg='yellow').pack(side=tkinter.TOP)
frm_r.pack(side=tkinter.RIGHT)
'''
表格数据
'''
from tkinter import ttk
tree = ttk.Treeview(win)
#定义列
tree['columns'] = ('姓名','年龄','身高','体重')
#设置列,不显示列
tree.column('姓名', width=100)
tree.column('年龄', width=100)
tree.column('身高', width=100)
tree.column('体重', width=100)
#设置表头,显示列
tree.heading('姓名',text='姓名-name')
tree.heading('年龄',text='年龄-age')
tree.heading('身高',text='身高-height')
tree.heading('体重',text='体重-weight')
#添加数据顺序是0,1,
tree.insert("", 0, text='line1',values=('lulu','23','175','56'))
tree.insert("", 1, text='line2',values=('luyu','24','171','66'))
'''
树状数据,类似于目录
'''
from tkinter import ttk
tree = ttk.Treeview(win)
tree.pack()
#添加一级树枝
treeF1 = tree.insert("", 0, '中国', text= 'China', values=('F1'))
treeF2 = tree.insert("", 1, '美国', text= 'USA', values=('F2'))
treeF3 = tree.insert("", 2, '英国', text= 'UK', values=('F3'))
#添加二级树枝
treeF1_1 = tree.insert(treeF1,0,'上海',text = '上海')
treeF1_2 = tree.insert(treeF1,1,'北京',text = '北京')
treeF1_3 = tree.insert(treeF1,2,'济南',text = '济南')
'''
绝对布局
'''
label1 = tkinter.Label(win,text='good',bg='blue')
label2 = tkinter.Label(win,text='nice',bg='red')
label3 = tkinter.Label(win,text='cool',bg='black')
#绝对布局,窗体改变对控件没影响
label1.place(x=10, y=10)
label2.place(x=50, y=50)
label3.place(x=100, y=100)
'''
相对布局
'''
label1 = tkinter.Label(win,text='good',bg='blue')
label2 = tkinter.Label(win,text='nice',bg='red')
label3 = tkinter.Label(win,text='cool',bg='black')
#相对布局
label1.pack(fill=tkinter.Y, side = tkinter.LEFT)
label2.pack(fill=tkinter.X, side = tkinter.TOP)
label3.pack(fill=tkinter.Y, side = tkinter.RIGHT)
'''
表格布局
'''
label1 = tkinter.Label(win,text='good',bg='blue')
label2 = tkinter.Label(win,text='nice',bg='red')
label3 = tkinter.Label(win,text='cool',bg='black')
label4 = tkinter.Label(win,text='hand',bg='yellow')
#表格布局
label1.grid(row=0,column=0)
label1.grid(row=0,column=1)
label1.grid(row=1,column=0)
label1.grid(row=1,column=1)
'''
鼠标点击事件,<Button-1>左键,<Button-2>中键,<Button-3>右键,<Double-Button-1>左键双击,<Double-Button-3>右键双击
'''
def func(event):
print(event.x, event.y)
button1 = tkinter.Button(win,text='左击')
button1.bind('<Double-Button-1>',func)
button1.pack()
'''
鼠标移动事件
'''
label = tkinter.Label(win, text='hhh')
label.pack()
def func(event):
print(event.x,event.y)
label.bind('<B1-Motion>',func)
'''
鼠标释放事件
'''
label = tkinter.Label(win,text='hhh')
label.pack()
def func(event):
print(event.x,event.y)
label.bind('<ButtonReleased-1>',func)
'''
进入事件<Enter>,离开<Leave>
'''
label = tkinter.Label(win,text='hhh')
label.pack()
def func(event):
print(event.x,event.y)
label.bind('<Enter>',func)
'''
响应所有按键事件
'''
label = tkinter.Label(win,text='hhh')
#设置焦点
label.focus_set()
label.pack()
def func(event):
print('event.char = ',event.char)
print('event.keycode = ',event.keycode)
label.bind('<Key>',func)
'''
相应特殊按键事件
'''
label = tkinter.Label(win,text='hhh')
#设置焦点
label.focus_set()
label.pack()
def func(event):
print('event.char = ',event.char)
print('event.keycode = ',event.keycode)
label.bind('<Shift_L>',func)
win.mainloop()
|
'''2 正则表达式详解'''
#如果下面的内容被我注释掉了,大家可以选中,然后ctrl+/(Spyder中的快捷键是ctrl+1)取消注释后运行
'''2.1 findall方法'''
import re
content = 'Hello 123 world'
result = re.findall('\d\d\d',content)
print(result)
import re
content = 'Hello 123 world 456 华小智python基础教学135'
result = re.findall('\d\d\d',content)
print(result)
a1 = result[0] #注意列表的一个元素的序号是0
print(a1)
a2 = result[1]
print(a2)
a3 = result[2]
print(a3)
a = type(result[0])
print(a)
for i in result:
print(i)
|
'''
排序:冒泡,选择 快速,插入,计数器
sorted 排序,默认升序
'''
#普通排序
list1 = [6,5,4,1,3,1]
list2 = sorted(list1)
print(list1)
print(list2)
#按绝对值大小排序
list3 = [6,-5,4,-1,3,1]
list4 = sorted(list3, key=abs)
print(list3)
print(list4)
#降序
list5 = [6,5,4,1,3,1]
list6 = sorted(list5, reverse=True)
print(list5)
print(list6)
#字母排序,按长度排序
list7 = ['a','c','h','b']
def myLen(str):
return len(str)
list8 = sorted(list7, key=myLen)
print(list7)
print(list8)
|
'''
概念:一种保存数据的格式
作用:可以保存本地的json文件,也可以将json进行数据传输,将json称为轻量级的传输方式
json文件的组成:
{} 代表字典
[] 代表列表
: 代表键值对
, 分隔两个部分
'''
import json
jsonStr = '{"name":"heheh", "gae":18, "hobby":"sleep"}'
print(jsonStr)
#将python数据类型的对象转成json格式的字符串
jsonData = json.loads(jsonStr)
print(jsonData)
print(type(jsonData))
print(jsonData['name'])
#将json格式字符串转成python数据类型的对象
jsonData2 = {'name':'heheh', 'gae':18, 'hobby':'sleep'}
jsonStr2 = json.dumps(jsonData2)
print(jsonStr2)
print(type(jsonStr2))
#读取本地的json文件
path1 = r"******.json"
with open(path1, 'rb') as f:
data = json.load(f)
print(data)
print(type(data))
#写本地json
path2 = r"****.json"
with open(path2,'w') as f:
json.dump(jsonData2, f)
|
'''Python商业爬虫案例实战第8节:舆情监控实战进阶2 by 王宇韬'''
#如果下面的内容被我注释掉了,大家如果想运行的话,可以选中,然后ctrl+/(Spyder中的快捷键是ctrl+1)取消注释
'''8.2节:新浪微博文章爬取实战'''
import requests
import re
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
def weibo2(company):
url = 'https://s.weibo.com/weibo?q=' + company + '&Refer=article_weibo'
res = requests.get(url, headers=headers, timeout=10).text
# print(res)
p_name = '<a href=".*?" class="name" target="_blank" nick-name="(.*?)"'
name = re.findall(p_name, res)
p_content = '<p class="txt" node-type="feed_list_content" nick-name=".*?>(.*?)</p>'
content = re.findall(p_content, res, re.S)
# print(name)
# print(len(name))
# print(content)
# print(len(content))
for i in range(len(name)):
content[i] = content[i].strip()
content[i] = re.sub(r'<.*?>', '', content[i])
print(str(i + 1) + '.' + content[i] + '——来自:' + name[i])
companys = ['华能信托','阿里巴巴','万科集团','百度','腾讯','京东']
for i in companys:
try:
weibo2(i)
print(i + '该公司新浪微博综合爬取成功')
except:
print(i + '该公司新浪微博综合爬取失败')
|
from utils.exceptions import InsufficientStorage
class Heap(object):
"""
An array heap implementation with log(n) insert, O(1) lookup for the root and log(n) deletion
of the root.
"""
def __init__(self, cmp, max_size):
self.cmp = cmp
self.heap = [None for _ in xrange(max_size + 1)]
self.max_size = max_size
self.leaf_ptr = 1
def insert(self, elem):
if self.get_size() == self.max_size:
raise InsufficientStorage('Heap full')
self.heap[self.leaf_ptr] = elem
self.leaf_ptr += 1
self._rebalance_leaf()
def pop_root(self):
root = self.heap[1]
self.heap[1], self.heap[self.leaf_ptr - 1] = self.heap[self.leaf_ptr - 1], None
self.leaf_ptr -= 1
self._rebalance_root()
return root
def get_root(self):
return self.heap[1]
def get_size(self):
return self.leaf_ptr - 1
def _rebalance_leaf(self):
i = self.leaf_ptr - 1
while i > 1 and self.cmp(self.heap[i], self.heap[i / 2]) < 0:
self.heap[i], self.heap[i / 2] = self.heap[i / 2], self.heap[i]
i /= 2
def _rebalance_root(self):
i = 1
while i < self.leaf_ptr:
j = i * 2
if i * 2 < self.leaf_ptr and i * 2 + 1 < self.leaf_ptr:
if self.cmp(self.heap[i * 2], self.heap[i * 2 + 1]) > 0:
j = i * 2 + 1
elif i * 2 >= self.leaf_ptr:
break
if self.cmp(self.heap[i], self.heap[j]) > 0:
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
else:
break
i = j
|
# coding=utf-8
"""Main executable module for mkpassphrase, installed as `mkpassphrase`."""
from __future__ import absolute_import, division, print_function
import argparse
import math
import os
import sys
def main():
"""Command-line entry point."""
import mkpassphrase as MP
from mkpassphrase import api, internal
wordlists = sorted(internal.WORD_LISTS)
parser = argparse.ArgumentParser(description="Generate a passphrase.")
parser.add_argument(
"-n",
"--num-words",
type=int,
metavar="NUM_WORDS",
help="Number of words in passphrase "
"(the default is enough words to reach a security level of {} bits)".format(
internal.ENTROPY_DEFAULT
),
)
parser.add_argument(
"-s",
"--entropy",
type=int,
metavar="ENTROPY",
help="Target entropy bits "
"(the default is {} bits)".format(internal.ENTROPY_DEFAULT),
)
parser.add_argument(
"-w",
"--word-list",
type=str,
metavar="WORD_LIST",
choices=wordlists,
help="Use built-in wordlist (eff-large [default], eff1, or eff2)",
)
parser.add_argument(
"-f",
"--word-file",
type=str,
metavar="WORD_FILE",
help="Word file path (one word per line)",
)
parser.add_argument(
"-l",
"--lowercase",
action="store_false",
dest="random_case",
default=True,
help="Lowercase words (the default is to capitalize the first letter"
"of each word with probability 0.5 and use lowercase "
"for all other letters)",
)
parser.add_argument(
"-p",
"--pad",
metavar="PAD",
default="",
help="Pad passphrase using PAD as prefix and suffix "
"(the default is no padding)",
)
parser.add_argument(
"-d",
"--delimiter",
dest="delimiter",
default=" ",
metavar="DELIMITER",
help="Use DELIMITER to separate words in passphrase "
"(the default is a space character)",
)
parser.add_argument(
"-t",
"--times",
dest="times",
type=int,
default=1,
metavar="TIMES",
help="Generate TIMES different passphrases "
"(the default is to generate 1 passphrase)",
)
parser.add_argument("-V", "--version", action="store_true", help="Show version")
parser.add_argument(
"-q",
"--quiet",
action="store_true",
help="Print just the passphrase (the default "
"is to also show the security-level of the generated passphrase(s))",
)
args = parser.parse_args()
if args.version:
print("%s %s" % (MP.__name__, MP.__version__))
sys.exit(0)
if args.num_words is not None and args.num_words < 1:
parser.exit("--num-words must be positive if provided")
if args.times < 1:
parser.exit("--times must be positive if provided")
if args.word_list and args.word_file:
parser.exit("only one of --word-list and --word-file is allowed")
if args.word_file and not os.access(args.word_file, os.R_OK):
parser.exit("word file does not exist or is not readable: %s" % args.word_file)
params = vars(args)
quiet = params.pop("quiet", False)
times = params.pop("times", 1)
params.pop("version", None)
# use the default wordlist if no list or file was provided
if not args.word_file and not args.word_list:
params["word_list"] = internal.WORD_LIST_DEFAULT
passphrases, entropy = api.mkpassphrase(count=times, **params)
if times == 1:
passphrases = [passphrases]
for passphrase in passphrases:
print(passphrase)
if not quiet:
print()
print("{}-bit security level".format(int(math.floor(entropy))))
if __name__ == "__main__":
main()
|
class calculator:
def fibonacci(x, y=1):
if(x > 1):
y *= x
x = x - 1
fibonacci(x, y)
else:
print('fibonacci result: ', x)
import caclulator
calculator.fibonacci(8) |
class Room():
name = ""
description = None
linked_rooms = {}
character = None
item = None
def __init__(self, room_name):
self.name = room_name
def set_character(self, new_character):
self.character = new_character
def get_character(self):
return self.character
def set_name(self, new_name):
self.name = new_name
def get_name(self):
return self.name
def set_description(self, new_description)
self.description = new_description
def get_description(self):
return self.description
def set_item(self, new_item):
self.item = new_item
def get_item(self):
return self.item
def describe(self):
print( self.description )
def link_room(self, room_to_link, direction):
self.linked_rooms[direction] = room_to_link
# comment later
print( self.name + " linked rooms: " + repr(self.linked_rooms))
def get_details():
print(self.get_name())
print('-' * 15)
print(self.get_description())
for direction in self.linked_rooms:
room = self.linked_rooms[direction]
print('THe {} is {}.'.format(room.get_name(), direction))
def move(self, direction):
if direction in self.linked_rooms
return self.linked_room[direction]
else:
print("You can't go that way!")
return self
|
import sys
sys.path.append('../doubly_linked_list')
from doubly_linked_list import DoublyLinkedList
"""
Queue operates on a First In, First Out basis. Meaning, one end is used for insertion, and the other is used for the deletion
Typically this will use at least two pointers. Queue always uses "enqueue" and "dequeue". Queue is the more complex version for shifting things around. Enqueuing adds something to the read and dequeuing pushes that item from the front. (Insert / Delete).
The pointers need to have access to both the rear and front of the data list.
Think of it like this for queue:
A person is in line for movie tickets. The person in the front, will get a ticket first before the person in the back, who will receive theirs last.
Time complexity: O(1) - constant.
### access / finding in lists is more difficult. removing things from the middle.
"""
class Queue:
def __init__(self):
self.size = 0
# Why is our DLL a good choice to store our elements?
# time complexity > * (it's constant)
self.storage = DoublyLinkedList()
def enqueue(self, value):
self.size += 1
self.storage.add_to_head(value)
def dequeue(self):
if self.len() > 0:
self.size -= 1
value = self.storage.tail.value
self.storage.remove_from_tail()
return value
def len(self):
return self.storage.__len__()
|
if __name__ == "__main__":
# food = ['rice','beans']
# food.append('broccoli')
# food.extend(['bread', 'pizza'])
# print(food [0:2])
# print(food[4])
# food = ("eggs,fruit,orange juice")
# breakfast = food.split(',')
# print(len(breakfast))
numlist = []
while True:
input_list = input('Enter a number: ')
if input_list == 'stop':
break
else:
numlist.append(float(input_list))
min_input = min(numlist)
max_input = max(numlist)
average_input =sum(numlist) / len(numlist)
print(f'average: {average_input} max: {max_input} min: {min_input}')
|
#!/usr/bin/python
import os
import sys
string1 = "abba"
if str(string1) == str(string1)[::-1]: print True
else: print False
|
#!/usr/bin/python
import os
import sys
from itertools import permutations
def checkPalindrome(string1):
perms = [''.join(p) for p in permutations(string1)]
for item in perms:
if item == item[::-1]:
# print "Given String "+string1+" can be used to create a palindrome"
return True
return False
string1 = raw_input("Enter string: ")
print checkPalindrome(string1)
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from Methods import util
# Functions for Exploratory data analysis
def CalculateClassBalance(df, target = None, get=False):
"""
Count the number of occurence of each class.
- df (pandas dataframe): dataframe containing the data.
- target (string/number): Name of the target column (feature). If none,
the target feature is considered to be the last one.
- get (bool): if True, the function returns a dict with the classes balance
Return (dict)
"""
if target is None:
labels = df.iloc[:,-1]
else:
labels = df[target]
# Calculate number of occurences for each class and total ocurrences
balance = dict()
total = 0
for label in labels.unique():
balance[label] = (labels == label).sum()
total += balance[label]
# Transform values to percentage
valueInPercent = np.array(list(balance.values())) / total
valueInPercent = valueInPercent * 100
balanceInPercent = dict(zip(balance.keys(), valueInPercent))
# Show values
print('Number of ocurrences for each class:')
for label in balance.keys():
print('Class %s: %.2f%% (%d)' %(label, balanceInPercent[label], balance[label]))
if (get):
return balance
def NumberOfNansInEachColumns(df):
"""
Count the number of Not a Number (NaNs) on each column (feature).
- df (pandas dataframe): dataframe containing the data.
"""
total = len(df)
dfNans = df.isnull().sum()
dfNansInPercent = (dfNans * 100) / total
print('Number of Nans in each column')
for column in dfNans.index:
print('%s : %.2f %% (%d)' %(column, dfNansInPercent[column], dfNans[column]))
def UniqueValuesOnEachColumn(df, showValues=False):
"""
Show how many unique values are there on each column(feature).
- df (pandas dataframe/ pandas Series): Data.
- showValues (bool): tells if each unique value of each column show be showed.
Return (dict): Dicionary wit the number of unique values for each column
"""
uniqueValues = dict()
print('Frequency of each unique value:')
if isinstance(df, pd.Series):
uniqueValues[df.name] = len(df.unique())
print('- %s : %d unique values' %(df.name, len(df.unique())))
if showValues:
total = len(df)
occurrences = dict()
occurrencesInPercent = dict()
for value in df.unique():
occurrences[value] = (df == value).sum()
occurrencesInPercent[value] = (occurrences[value] * 100.0) / total
print("\t%s : %.2f%% (%d)" %(str(value), occurrencesInPercent[value], occurrences[value]))
else: # df is assumed to be pandas dataframe
for column in df.columns:
uniqueValues[column] = len(df[column].unique())
print('- %s : %d unique values' %(column, len(df[column].unique())))
if showValues:
total = len(df)
occurrences = dict()
occurrencesInPercent = dict()
for value in df[column].unique():
occurrences[value] = (df == value).sum()
occurrencesInPercent[value] = (occurrences[value] * 100.0) / total
print("\t%s : %.2f%% (%d)" %(str(value), occurrencesInPercent[value], occurrences[value]))
return uniqueValues
def PlotCodeFrequency(codes, labels, save = False, path ='', filename = 'img'):
"""
Plot the frequency of each code on the dataset and also which ones are DI or DP.
- codes (pandas Series, list, numpy array): codes of each sample.
- labels (pandas Series, list, numpy array): labels of each sample.
- save (bool): tells if the plot should be saved.
- path (string): path where to save the figure.
- filename (string): name of the figure image file to be saved.
"""
DI = 0
DP = 1
df=pd.DataFrame()
df['labels'] = labels
df['codes'] = codes
freq_di = dict()
freq_dp = dict()
total = len(df)
N=0
toPercentage = lambda value,total: (value * 100.0) / total
codigosExistentes = list(df['codes'].unique())
codigosExistentes.sort()
for c in codigosExistentes:
freq_di[c] = toPercentage(((df['codes'] == c) & (df['labels'] == DI)).sum(), total)
freq_dp[c] = toPercentage(((df['codes'] == c) & (df['labels'] == DP)).sum(), total)
N += 1
ind = np.arange(N)
width = 0.5
fig = plt.figure(figsize=(11, 5))
dp_bar = plt.bar(ind, list(freq_dp.values()), width, figure=fig)
di_bar = plt.bar(ind, list(freq_di.values()), width, bottom=list(freq_dp.values()), figure=fig)
minorTicks = MultipleLocator(1)
plt.ylabel('Porcentagem (%)')
plt.xlabel('Códigos')
plt.title('Frequência de cada código no dataset')
plt.xticks(ind, tuple(freq_di.keys()))
plt.yticks(np.arange(0, 25, 5))
plt.axes().yaxis.set_minor_locator(minorTicks)
plt.legend((di_bar[0], dp_bar[0]), ('DI', 'DP'))
plt.grid(True, which='both', axis='y')
plt.show()
if(save):
util.CheckAndCreatePath(path)
util.SaveFigure(fig, path, filename)
|
arr = []
while True:
a = input("Enter string: ")
if a == "Generate":
break
arr.append(a)
for j in arr:
print(f"<p>{j}</p>")
|
import os
with open("file.txt", "r") as file:
# file.write(input("\n"))
files = file.readline()
print(files)
file.close()
# os.remove("file.txt") # to remove file
# os.mkdir("name")
|
# Linear Algebra 1.1):
import numpy as np
A = np.array([[1,2,3],[2,7,4]]) # matrix
print
print 'Matrix A:'
print A # output matrix
print
print 'Dimension of matrix A:',A.shape # output dimensions
print
# Output for 1.1):
# >>> runfile('/Users/swatisharma/Documents/LA1p1.py', wdir='/Users/swatisharma/Documents')
#
# Matrix A =
# [[1 2 3]
# [2 7 4]]
#
# Dimension of matrix A: (2, 3)
#__________________________________________________________________
# Linear Algebra 1.2):
import numpy as np
B = np.array([[1,-1],[0,1]]) # matrix
print
print 'Matrix B ='
print B # output matrix
print
print 'Dimension of matrix B:',B.shape # output dimensions
print
# Output for 1.2):
# >>> runfile('/Users/swatisharma/Documents/LA1p2.py', wdir='/Users/swatisharma/Documents')
#
# Matrix B =
# [[ 1 -1]
# [ 0 1]]
#
# Dimension of matrix B: (2, 2)
#__________________________________________________________________
# Linear Algebra 1.3):
import numpy as np
C = np.array([[5,-1],[9,1],[6,0]]) # matrix
print
print 'Matrix C ='
print C # output matrix
print
print 'Dimension of matrix C:',C.shape # output dimensions
print
# Output for 1.3):
# >>> runfile('/Users/swatisharma/Documents/LA1p3.py', wdir='/Users/swatisharma/Documents')
#
# Matrix C =
# [[ 5 -1]
# [ 9 1]
# [ 6 0]]
#
# Dimension of matrix C: (3, 2)
#______________________________________________________________________
# Linear Algebra 1.4):
import numpy as np
D = np.array([[3,-2,-1],[1,2,3]]) # matrix
print
print 'Matrix D ='
print D # output matrix
print
print 'Dimension of matrix D:',D.shape # output dimensions
print
# Output for 1.4):
# >>> runfile('/Users/swatisharma/Documents/LA1p4.py', wdir='/Users/swatisharma/Documents')
#
# Matrix D =
# [[ 3 -2 -1]
# [ 1 2 3]]
#
# Dimension of matrix D: (2, 3)
#_____________________________________________________________________
# Linear Algebra 1.5):
# Linear Algebra 1.5):
import numpy as np
u = np.array([[6,2,-3,5]]) # matrix
print
print 'Matrix u ='
print u # output matrix
print
print 'Dimension of matrix u:',u.shape # output dimensions
print
# Output for 1.5):
# >>> runfile('/Users/swatisharma/Documents/LA1p5.py', wdir='/Users/swatisharma/Documents')
#
# Matrix u =
# [[ 6 2 -3 5]]
#
# Dimension of matrix u: (1, 4)
#__________________________________________________________________
# Linear Algebra 1.6):
import numpy as np
w = np.array([[1],[8],[0],[5]]) # matrix
print
print 'Matrix w ='
print w # output matrix
print
print 'Dimension of matrix w:',w.shape # output dimensions
print
# Output for 1.6):
# >>> runfile('/Users/swatisharma/Documents/LA1p6.py', wdir='/Users/swatisharma/Documents')
#
# Matrix w =
# [[1]
# [8]
# [0]
# [5]]
#
# Dimension of matrix w: (4, 1)
#_____________________________________________________________________
# Linear Algebra 2.1):
import numpy as np
u = np.array([6,2,-3,5])
v = np.array([3,5,-1,4])
matsum = u + v
print
print 'u + v = ',matsum
print
# Output for 2.1):
# >>> runfile('/Users/swatisharma/Documents/LA2p1TEST.py', wdir='/Users/swatisharma/Documents')
#
# u + v = [ 9 7 -4 9]
#____________________________________________________________________
# Linear Algebra 2.2):
import numpy as np
u = np.array([6,2,-3,5])
v = np.array([3,5,-1,4])
matdiff = u - v
print
print 'u - v = ',matdiff
print
# Output for 2.2):
# >>> runfile('/Users/swatisharma/Documents/LA2p1TEST.py', wdir='/Users/swatisharma/Documents')
#
# u - v = [ 3 -3 -2 1]
#_____________________________________________________________________
# Linear Algebra 2.3):
import numpy as np
u = np.array([6,2,-3,5])
alpha = 6
matmul = 6*u
print
print 'alpha(u) = ',matmul
print
# Output for 2.3):
# >>> runfile('/Users/swatisharma/Documents/LA2p1TEST.py', wdir='/Users/swatisharma/Documents')
#
# alpha(u) = [ 36 12 -18 30]
#_____________________________________________________________________
# Linear Algebra 2.4):
import numpy as np
u = np.array([6,2,-3,5])
v = np.array([3,5,-1,4])
matdot = np.dot(u,v)
print
print 'u dot v = ',matdot
print
# Output for 2.4):
# >>> runfile('/Users/swatisharma/Documents/LA2p1TEST.py', wdir='/Users/swatisharma/Documents')
#
# u dot v = 51
________________________________________________________________________
# Linear Algebra 2.5):
import numpy as np
u = np.array([6,2,-3,5])
matmag = np.linalg.norm(u)
print
print '||u|| = ',matmag
# Output for 2.5):
# >>> runfile('/Users/swatisharma/Documents/LA2p5.py', wdir='/Users/swatisharma/Documents')
#
# ||u|| = 8.60232526704
#______________________________________________________________________
# Linear Algebra 3.1):
import numpy as np
A = np.array([[1,2,3],[2,7,4]])
C = np.array([[5,-1],[9,1],[6,0]])
matsum = A + C
print
print 'A + C =', matsum
# Output for 3.1): NOT POSSIBLE!
# >>> runfile('/Users/swatisharma/Documents/LA3p1.py', wdir='/Users/swatisharma/Documents')
#
# ValueError: operands could not be broadcast together with shapes (2,3) (3,2)
#_______________________________________________________________
# Linear Algebra 3.2):
import numpy as np
A = np.array([[1,2,3],[2,7,4]])
C = np.array([[5,-1],[9,1],[6,0]])
CTr = np.transpose(C)
matdiff = A - CTr
print
print 'A - CTranspose ='
print matdiff
# Output for 3.2):
# >>> runfile('/Users/swatisharma/Documents/LA3p2.py', wdir='/Users/swatisharma/Documents')
#
# A - CTranspose =
# [[-4 -7 -3]
# [ 3 6 4]]
#______________________________________________________
# Linear Algebra 3.3):
import numpy as np
C = np.array([[5,-1],[9,1],[6,0]])
CTr = np.transpose(C)
D = np.array([[3,-2,-1],[1,2,3]])
matsum = CTr + (3*D)
print
print 'CTranspose + 3D ='
print matsum
# Output for 3.3):
# >>> runfile('/Users/swatisharma/Documents/LA3p3.py', wdir='/Users/swatisharma/Documents')
#
# CTranspose + 3D =
# [[14 3 3]
# [ 2 7 9]]
#____________________________________________
# Linear Algebra 3.4):
import numpy as np
A = np.array([[1,2,3],[2,7,4]])
B = np.array([[1,-1],[0,1]])
matmul = B.dot(A)
print
print 'BA ='
print matmul
print
# Output for 3.4):
# >>> runfile('/Users/swatisharma/Documents/LA3p4.py', wdir='/Users/swatisharma/Documents')
#
# BA =
# [[-1 -5 -1]
# [ 2 7 4]]
#_____________________________________________
# Linear Algebra 3.5):
import numpy as np
A = np.array([[1,2,3],[2,7,4]])
ATr = np.transpose(A)
B = np.array([[1,-1],[0,1]])
matmul = B.dot(ATr)
print
print 'B(A Transpose) =', matmul
print
# Ouptput for 3.5): NOT POSSIBLE!
# >>> runfile('/Users/swatisharma/Documents/LA3p5.py', wdir='/Users/swatisharma/Documents')
#
# ValueError: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)
#_____________________________________________
# Linear Algebra 3.6):
import numpy as np
B = np.array([[1,-1],[0,1]])
C = np.array([[5,-1],[9,1],[6,0]])
matmul = B.dot(C)
print
print 'BC =', matmul
print
# Output for 3.6): NOT POSSIBLE!
# >>> runfile('/Users/swatisharma/Documents/LA3p6.py', wdir='/Users/swatisharma/Documents')
#
# ValueError: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)
#_______________________________________________
# Linear Algebra 3.7):
import numpy as np
B = np.array([[1,-1],[0,1]])
C = np.array([[5,-1],[9,1],[6,0]])
matmul = C.dot(B)
print
print 'CB ='
print matmul
print
# Output for 3.7):
# >>> runfile('/Users/swatisharma/Documents/LA3p7.py', wdir='/Users/swatisharma/Documents')
#
# CB =
# [[ 5 -6]
# [ 9 -8]
# [ 6 -6]]
#_________________________________________
# Linear Algebra 3.8):
import numpy as np
B = np.array([[1,-1],[0,1]])
#matmul1 = B.dot(B)
#matmul2 = matmul1.dot(matmul1)
matpow = np.linalg.matrix_power(B,4)
print
print 'B^4 ='
print matpow
print
# Output for 3.8):
# >>> runfile('/Users/swatisharma/Documents/LA3p8.py', wdir='/Users/swatisharma/Documents')
#
# B^4 =
# [[ 1 -4]
# [ 0 1]]
#________________________________________________
# Linear Algebra 3.9):
import numpy as np
A = np.array([[1,2,3],[2,7,4]])
ATr = np.transpose(A)
matmul = A.dot(ATr)
print
print 'A(A Transpose) ='
print matmul
print
# Output for 3.9):
# >>> runfile('/Users/swatisharma/Documents/LA3p9.py', wdir='/Users/swatisharma/Documents')
#
# A(A Transpose) =
# [[14 28]
# [28 69]]
#____________________________________________________
# Linear Algebra 3.10):
import numpy as np
D = np.array([[3,-2,-1],[1,2,3]])
DTr = np.transpose(D)
matmul = DTr.dot(D)
print
print '(D Transpose)D ='
print matmul
print
# Output for 3.10):
># >> runfile('/Users/swatisharma/Documents/LA3p10.py', wdir='/Users/swatisharma/Documents')
#
# (D Transpose)D =
# [[10 -4 0]
# [-4 8 8]
# [ 0 8 10]]
|
# -*- coding: utf-8 -*-
# The football.csv file contains the results from the English Premier League.
# The columns labeled 'Goals' and 'Goals Allowed' contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
# The below skeleton is optional. You can use it or you can write the script with an approach of your choice.
# Team,Games,Wins,Losses,Draws,Goals,Goals Allowed,Points
import csv
def get_team_with_smallest_diff(data):
smallest_difference = None
team = None
# Read data using DictReader
try:
with open(data, 'rb') as f:
reader = csv.DictReader(f)
for row in reader:
# Calculate team difference. Goals allowed might be higher than Goals. Return absolute value
team_difference = abs(int(row['Goals']) - int(row['Goals Allowed']))
if team_difference < smallest_difference or smallest_difference is None:
smallest_difference = team_difference
team = row['Team']
except Exception as err:
print 'Cannot read file: ' + str(err)
return team
|
import math
from math import atan
a = float(input("Введите a:"))
b = float(input("Введите b:"))
G = (9 * (20 * (b ** 2) - 31 * a * b + 12 * (b ** 2))) / (10 * (a ** 2) - 17 * a * b + 6 * (b ** 2))
print('A = {}.\nB = {}.\nРезультат: {}'.format(a,b,G))
a = float(input("Введите a:"))
b = float(input("Введите b:"))
F = - atan (7 * (a ** 2) - 2 * a * b - 9 * (b ** 2))
print('A = {}.\nB = {}.\nРезультат: {}'.format(a,b,F))
a = float(input("Введите a:"))
b = float(input("Введите b:"))
Y = - atan (2 * (a ** 2) + (a * b) - 3 * (b ** 2))
print('A = {}.\nB = {}.\nРезультат: {}'.format(a,b,Y))
|
a1=int(input())
fact=1
if(a1>0):
for i in range(1,a1+1):
fact=fact*i
print(fact)
elif(a1==0):
fact=1
print(fact)
else:
print("invalid")
|
t=int(input())
if t%2==0:
print("Even")
elif t%2==1:
print("Odd")
else:
print("Invalid")
|
'''
implementation of a simple linear layer
'''
import torch
import math
from Module import Module
from Param import Parameters
class Linear(Module):
def __init__(self, input_size, output_size):
super(Linear,self).__init__()
type = torch.float32
#use Xavier initialization
std = math.sqrt(2./(input_size+output_size))
self.weights = Parameters(torch.empty(output_size,input_size,dtype= type).normal_(0,std))
self.bias = Parameters(torch.zeros(output_size,dtype=type))
self.result = Parameters(torch.empty(output_size,dtype=type))
self.input = Parameters(torch.empty(input_size,dtype=type))
def forward(self,x):
"""perform the forward pass for a fully connected linear layer of sizes input_size -> output_size
Parameters
----------
x : input tensor of size [number_of_training_points,input_size]
training data points in minibatch
Returns
-------
torch float64 tensor
result of the forward pass of dimension [number_of_training_points,output_size]
"""
#we check if we have a single datapoint entry, in which case we do not have to worry about the dimensions
if len(x.shape)>1:
self.input.value = x
#not needed anymore, shape taken care of, automatic broadcasting will work
## #expand the bias vector so it matches the size of the mini batches
## #B = self.bias.value.repeat(1,self.input.value.t().shape[1]).view(-1,self.bias.value.shape[0]).t()
#do the actual forward pass
self.result.value = x.matmul(self.weights.value.t()) + self.bias.value
#self.result.value = self.result.value.t()
else:
self.input.value = x
self.result.value = torch.mv(self.weights.value,self.input.value) + self.bias.value
return self.result.value
def backward(self, derivative):
""" backward operation for fully connected layer
Parameters
----------
derivative : tensor
supposing the layer returns x_(i+1) and takes as input x_i, derivative
is dloss/dx_(i+1)
Returns
-------
tensor
return dloss/dx_i so that the next layer can perform backward propagation
"""
#add a new dimension if necessary so that the derivative is a matrix not a vector
if len(derivative.shape) == 1:
if self.weights.value.shape[0] == 1:
derivative = derivative.view(derivative.shape[0],1)
else:
derivative = derivative.view(1,derivative.shape[0])
if len(self.input.value.shape) == 1:
x_i = self.input.value.view(1,self.input.value.shape[0])
else:
x_i = self.input.value
# derivative with respect to the weights: dloss/dw
self.weights.grad += torch.mm(derivative.t(),x_i)
#derivative with respect to the bias: dloss/dbias
self.bias.grad += derivative.sum(0)
#derivative if the loss with respect to the input of the layer: dloss/dx_i pass it to the next layer
next_derivative = torch.mm(derivative,self.weights.value)
return next_derivative
def zero_grad(self):
'''
Set all the parameters' gradient to 0.
'''
self.weights.grad.zero_()
self.bias.grad.zero_()
def param(self):
return self.weights, self.bias
def __str__(self):
return "Linear(in_features= {}, out_features= {})".format(self.weights.value.shape[1],
self.weights.value.shape[0])
|
texto = "Teste de testo"
#retorna o tamanho da string
print(len(texto))
for i in range(0,len(texto)):
print (i)
print(texto[i])
#replace
texto = texto.replace("Teste","Testes")
print (texto)
#count
print(texto.count('a'))
#procura a primeira aparição e retorna a posição
print(texto.find("st"))
#separa a string, caso sem parametro, separa as plavras por espaço
#também é possivel separar logo no input retornando uma lista, com .split()
print(texto)
texto = texto.split();
print(texto)
#como o valor retornado é uma lista, pode-se usar como parmetro no for, assim pode-se procurar coisas epecificas
for i in texto:
if i=="de":
print("A palvra de existe no texto")
#função join funciona da mesma forma que a função split, mas coloca determinado elemento junto de várias cópias da string
#função upper() coloca tudo em caixa alta
texto = "Teste de testo"
print(texto.upper())
print(texto.lower())
print(texto.capitalize())
# a função title coloca tods as primeiras letras como maiusculas
print(texto.title())
#swapcase troca maiusculas e minlusculas
print(texto.swapcase())
#existe isupper islower e istitle, e isalnum retorna bool se alfa numerico, isalpha e isdigit e isspace
#melhor form de printar algo -e com range(0,-1), ou string[0,-1] mias o passo
|
money = int(input())
per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0}
per_cent2 = per_cent.values()
print(per_cent2)
deposit = []
deposit.append(per_cent['ТКБ'] * money / 100)
deposit.append(per_cent['СКБ'] * money / 100)
deposit.append(per_cent['ВТБ'] * money / 100)
deposit.append(per_cent['СБЕР'] * money / 100)
print(deposit)
print('Максимальная сумма, которую вы можете заработать', max(deposit))
|
'''
module: clusters.py
use: contains functions associated clustering / unsupervised learning
'''
import numpy as np
from kmeans import kplusplus
from utils import getSimilarityArray
def getDegreeArray(sim_array): #convert array W into respective Degree array, Dii = sum(i=1 to n) Wij
'''
Purpose:
Computes the Degree array 'D' in the spectral clustering process from the similarity array
Dii = \sum_{i=1}^n Wij, ie the sum of each row of the similarity array
Inputs:
sim_array - Similarity array Wij retrieved from getSimilarityArray()
Outputs:
D - degree array (described in Purpose
'''
D = np.zeros((sim_array.shape[0],sim_array.shape[0]))
for i in range(0,sim_array.shape[0]):
D[i,i] = np.sum(sim_array[i,:])
return D
def getLaplacian(W,D):
'''
Purpose:
Returns the Laplacian of the similarity array W and the degree array D
For use with spectral clustering
Inputs:
W - similarity array from getSimilarityArray()
D - degree array from getDegreeArray
Outputs:
L = D-W, the laplacian
'''
return D-W
def getLaplacianBasis(features,similarity_method='exp',k_nn=5):
'''
Purpose:
Returns orthogonal basis for Laplacian embedding of features. Essentially the full spectral clustering algorithm before the actual clustering
Inputs:
features - n examples by k features ndarray (n>k preferred)
similarity_method - method to use for computing the similarity array:
--'exp' computes W[i,j] = exp(-||xi - xj||^2 / 2)
--'norm' computes W[i,j] = ||xi - xj||^2
--'chain' is specifically for the 'chain' generateData type
k_nn - number of nearest neighbors to consider in similarity array
num_clusters - number of clusters for kmeans++ to sort the data into
Outputs:
U - orthogonal basis returned by the svd of the laplacian with columns corresponding to the most significant singular values at the lowest indices
'''
W = getSimilarityArray(features,similarity_method,k_nn)
D = getDegreeArray(W)
L = getLaplacian(W,D)
U,s,V = np.linalg.svd(L,full_matrices=0)
return U
def spectralClustering(features,similarity_method='exp',k_nn=5,basis_dim=2,num_clusters=2):
'''
Purpose:
Performs spectral clustering into 'num_clusters' clusters on data defined in the ndarray 'features'
Inputs:
features - n examples by k features ndarray (n>k preferred)
similarity_method - method to use for computing the similarity array:
--'exp' computes W[i,j] = exp(-||xi - xj||^2 / 2)
--'norm' computes W[i,j] = ||xi - xj||^2
--'chain' is specifically for the 'chain' generateData type
k_nn - number of nearest neighbors to consider in similarity array
basis_dim - number of svd basis vectors to consider for input to kmeans++ algorithm
num_clusters - number of clusters for kmeans++ to sort the data into
Outputs:
labels - 1 by n array of assigned cluster labels for each feature example
centers - cluster centers array (basis_dim by num_clusters) representing each of the k cluster centers
'''
#W = getSimilarityArray(features,similarity_method,k_nn)
#D = getDegreeArray(W)
#L = getLaplacian(W,D)
#U,s,V = np.linalg.svd(L,full_matrices=0)
U = getLaplacianBasis(features,similarity_method=similarity_method,k_nn=k_nn)
U = U[:,-1*basis_dim:]
labels, centers = kplusplus(U.T,num_clusters)
return labels, centers, U
|
#Programa informa o consumo do veiculo
km=int(input("Digite quantos quilometros foram percorridos ?"))
L=int(input("Quantos litros foram gastos ?"))
C=km/L
print("O consumo é de",C,"km/l")
|
#Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo
# compreendido por eles.
n1 = int(input("Digite numero inicial: "))
nf = int(input("Digite numero final: "))
while n1 < nf:
print(n1)
n1=n1+1
|
'''Programa de Raciocínio Lógico e Matemático
Professor: Agnaldo Cieslak
Alunos: Erika Klein e Emmanuel Rodrigues
ADS 1n/ SENAC
'''
print ("Construa a Tabela Verdade para a fórmula abaixo:")
print ("p v (q ^ r) <-> (p v q) ^ (p v r)")
print ("Digite os valores v ou f para cada proposição:")
print (" ")
print (" ")
print ("Conectivo “e”: (Conjunção)")
print ("Proposições compostas em que está presente o conectivo “e” são ditas CONJUNÇÕES.")
print ("Simbolicamente, esse conectivo pode ser representado por “^”. Então, se temos a sentença:")
print ("Ex: “Emmanuel é estudante e Erika é Bióloga.")
print ("Poderemos representá-la apenas por: p^q. onde: p = Emmanuel é estudante e q = Erika é Bióloga.")
print ("Como se revela o valor lógico de uma proposição conjuntiva? Da seguinte forma:")
print ("Uma conjunção só será verdadeira, se ambas as proposições componentes forem também verdadeiras.")
print (" ")
print (" ")
print ("Conectivo “ou”: (Disjunção)")
print ("Recebe o nome de DISJUNÇÃO toda proposição composta em que as partes estejam unidas pelo conectivo 'ou'.")
print ("Simbolicamente, representaremos esse conectivo por “v”. Portanto, se temos a sentença:")
print ("Ex: “Emmanuel é estudante ou Erika é Bióloga.")
print ("Poderemos representá-la apenas por: pvq. onde: p = Emmanuel é estudante ou q = Erika é Bióloga.")
print ("Uma disjunção será falsa quando as duas partes que a compõem forem ambas falsas! E nos demais casos, a disjunção será verdadeira! .")
print (" ")
print (" ")
print (" Conectivo “ ... se e somente se ...”: (Bicondicional) ")
print ("A estrutura dita bicondicional apresenta o conectivo “se e somente se”, separando as duas sentenças simples.")
print ("Trata-se de uma proposição de fácil entendimento. Se alguém disser: “Emmanuel fica alegre se e somente se Erika sorri.”")
print ("É o mesmo que fazer a conjunção entre as duas proposições condicionais: ")
print ("Emmanuel fica alegre somente se Erika sorri e Erika sorri somente se Emmanuel fica alegre.")
print ("Haverá duas situações em que a bicondicional será verdadeira:")
print ("Quando conseqüentemente forem ambos verdadeiros, ou quando forem ambos falsos")
print ("Nos demais casos, a bicondicional será falsa.")
print (" ")
print (" ")
print ("Tautologia é uma proposição composta formada por duas ou mais proposições p, q, r, ...")
print ("Será dita uma Tautologia se ela for sempre verdadeira, independentemente dos valores lógicos das proposições que a compõem.")
print ("Em palavras mais simples: para saber se uma proposição composta é uma Tautologia, construiremos a sua tabela-verdade!")
print ("Daí, se a última coluna da tabela-verdade só apresentar verdadeiro (e nenhum falso), então estaremos diante de uma Tautologia.")
print (" ")
print ("Tabela verdade")
print (" ")
print (" TAUTOLOGIA ")
print ("p | q | r | (q ^ r) | (p v q) | (p v r) | p v (q ^ r)| (p v q)^(p v r) | p v (q ^ r) <--> (p v q) ^(p v r)")
print ("__________________________________________________________________________________________________________")
print ("v | v | v | v | v | v | v | v | Verdadeiro" )
print ("__________________________________________________________________________________________________________")
print ("v | v | f | f | v | v | v | v | Verdadeiro" )
print ("________________________________________________________________________________________________________ _")
print ("v | f | v | f | v | v | v | v | Verdadeiro" )
print ("__________________________________________________________________________________________________________")
print ("v | f | f | f | v | v | v | v | Verdadeiro" )
print ("__________________________________________________________________________________________________________")
print ("f | v | v | v | v | v | v | v | Verdadeiro" )
print ("__________________________________________________________________________________________________________")
print ("f | f | v | f | f | v | f | f | Verdadeiro")
print ("__________________________________________________________________________________________________________")
print ("f | v | f | f | v | f | f | f | Verdadeiro")
print ("__________________________________________________________________________________________________________")
print ("f | f | f | f | f | f | f | v | Verdadeiro")
print ("__________________________________________________________________________________________________________")
print (" ")
print (" ")
x="s"
while x=="s":
def erro(letras):
i=1
while i != 0:
y = input(letras)
if y != 'v' and y != 'f':
print("Valor inválido. Digite v ou f")
else:
i=0
return y
p = erro('Digite um valor para p: ')
q = erro('Digite um valor para q: ')
r = erro('Digite um valor para r: ')
print (" ")
print (" ")
if (q=="v") and (r=="v"):
qer=("v")
if (q=="v") and (r=="f"):
qer=("f")
if (q=="f") and (r=="v"):
qer=("f")
if (q=="f") and (r=="f"):
qer=("f")
print ("Conjunção (q^r) = "+qer)
print (" ")
print (" ")
if (p=="v") or (q=="v"):
pouq=("v")
if (p=="v") or (q=="f"):
pouq=("v")
if (p=="f") or (q=="v"):
pouq=("v")
if (p=="f") or (q=="f"):
pouq=("f")
print ("Disjunção (pvq)= "+pouq)
print (" ")
print (" ")
if (p=="v") or (r=="v"):
pour=("v")
if (p=="v") or(r=="f"):
pour=("v")
if (p=="f") or (r=="v"):
pour=("v")
if (p=="f") or (r=="f"):
pour=("f")
print ("Disjunção (pvr)= "+pour)
print (" ")
print (" ")
if (p=="v")or (q=="v") and (r=="v"):
pouqer=("v")
if (p=="v")or (q=="v") and (r=="f"):
pouqer=("v")
if (p=="v")or (q=="f") and (r=="v"):
pouqer=("v")
if (p=="v")or (q=="f") and (r=="f"):
pouqer=("v")
if (p=="f")or (q=="v") and (r=="v"):
pouqer=("v")
if (p=="f")or (q=="f") and (r=="f"):
pouqer=("f")
if (p=="f")or (q=="v") and (r=="f"):
pouqer=("f")
if (p=="f")or (q=="f") and (r=="v"):
pouqer=("f")
print ("ConjunçãoeDisjunção pv(q^r)= "+pouqer)
print (" ")
print (" ")
if ((p=="v") or (q=="v")) and ((p=='v') or (r=="v")):
pouqepour=("v")
if ((p=="v") or (q=="v")) and ((p=='v') or (r=="f")):
pouqepour=("v")
if ((p=="v") or (q=="f")) and ((p=='v') or (r=="v")):
pouqepour=("v")
if ((p=="v") or (q=="f")) and ((p=='v') or (r=="f")):
pouqepour=("v")
if ((p=="f") or (q=="v")) and ((p=='f') or (r=="v")):
pouqepour=("v")
if ((p=="f") or (q=="f")) and ((p=='f') or (r=="v")):
pouqepour=("f")
if ((p=="f") or (q=="v")) and ((p=='f') or (r=="f")):
pouqepour=("f")
if ((p=="f") or (q=="f")) and ((p=='f') or (r=="f")):
pouqepour=("f")
print ("DisjunçãoeConjunção (pvq)^(pvr)= "+pouqepour)
print (" ")
print (" ")
if pouqer == pouqepour:
pouqerpouqepour=("v")
print ("Bicondição pv(q^r) <--> (pvq)^(pvr)= "+pouqerpouqepour)
print ("")
x=input("Quer fazer novamente?")
|
#Faça um programa que leia 5 números e informe a soma e a média dos números.
cont = 0
s = 0
m = 0
for i in range(5):
n = float(input("Digite nota : "))
s=s+n
cont=cont+1
m=(s)/cont
print(s)
print(m)
'''
'''
# 4)
i = 0
while i < 50:
if (i % 2) == 1:
print (i)
i=i+1
|
class Person:
static = 'this is a static or class variable'
def __init__(self, name):
# This is an instance variable
self.name = name
# The first implicit parameter is always a reference to the instance and it is called self by convention
def say(self, something):
print(f'{self.name} says {something}')
# The first implicit parameter is always a reference to the class and it is called cls by convention
@classmethod
def updateAndPrintStatic(cls, str='other'):
cls.static = str
print(cls.static)
@staticmethod
def staticMethod(*args):
print(f'This function should only work on the {len(args)} input parameters')
class Developer(Person):
def __init__(self, name):
super().__init__(name)
# You can hide members with this notation
self.__secret = 'Coffee'
def say(self):
print('Code is life')
def say(self, **kwargs):
print('No function overload in python')
dave = Developer('Dave')
print(dave.name)
try:
print(dave.__secret)
except AttributeError as err:
print(dave.name, 'keep his secret')
print('But not from me :)', dave.__dict__)
input(('\n' * 2) + 'Enter to continue...')
dave.say()
dave.say(overload=True)
Developer.ask = lambda self: print('Why no function overload in python?')
dave.ask()
|
#!/usr/bin/python
'''
This program is used to implement the Naive Bayes Algorithm for classification.
To run the program, type the following command:
python NaiveBayes.py <training_file> <test_file>
'''
import sys
import csv
import math
label = "IsBadBuy"
num_attr_list=["WarrantyCost","MMRAcquisitionAuctionCleanPrice","MMRCurrentRetailAveragePrice","MMRAcquisitionRetailAveragePrice","VehOdo","VehicleAge","MMRCurrentRetailCleanPrice","MMRAcquisitionAuctionAveragePrice","MMRAcquisitonRetailCleanPrice","MMRCurrentAuctionAveragePrice","VehBCost","MMRCurrentAuctionCleanPrice","VehOdo_by_VehAge","r2_minus_r1_avg","r2_minus_r1_clean","r2_minus_a1_avg","r2_minus_a1_clean","r2_avg_minus_vehbc","r2_clean_minus_vehbc","vehbc_minus_a1_avg","vehbc_minus_a1_clean","warranty_by_vehbc"]
'''This function mentions the correct usage for running the program.
'''
def usage(program_name):
return "Wrong Usage!\nCorrect Usage is:\t<python "+ program_name + "> <train_file> <test_file> <prediction_file>"
'''This function is used to find all the distinct values that each nominal attribute can take.
This is stored in a dictionary with keys as the attribute names and the value for a
key as a list of distinct values that the attribute can take.
'''
def find_distinct_values_feature(training_data,testing_data,all_features):
values_in_features = {}
total_data = training_data + testing_data
for feature in all_features:
distinct_values = set()
for example in total_data:
distinct_values.add(example[feature])
values_in_features[feature] = distinct_values
return values_in_features
'''This function is used to calculate the prior probabilities of the class labels.
'''
def find_prior_probability(label_value,training_data):
global label
count = 0
for example in training_data:
if example[label] == label_value:
count += 1
return float(count)/float(len(training_data))
'''This function is basically the model that is learned in the Naive Bayes Classifier.
It stores the conditional probability values of each attribute_name -> value -> label
combination. These values are stored in a dictionary and looked up using a
string lookup.
'''
def store_all_feature_value_label_cond_probabilities(training_data,values_in_features):
global label
value_cond_prob = {}
labels = ['0','1']
for feature in values_in_features:
distinct_values = values_in_features[feature]
total_values_feature = len(distinct_values)
for value in distinct_values:
for label_val in labels:
string_lookup = str(feature) + ':' + str(value) + ':' + label_val
counter = 0
total_counter = 0
for example in training_data:
if example[label] == label_val:
total_counter += 1
if example[feature] == value:
counter += 1
if counter == 0:
counter = 1 #Laplacian Correction.
total_counter += total_values_feature
probability = float(counter)/float(total_counter)
value_cond_prob[string_lookup] = probability
return value_cond_prob
def store_mean_std_dev_numeric_attributes(training_data,numeric_features,value_cond_prob):
positive_examples = []
negative_examples = []
for example in training_data:
if example[label] == "1":
positive_examples.append(example)
else:
negative_examples.append(example)
value_cond_prob = get_mean_std_dev_labelled_examples(positive_examples,numeric_features,value_cond_prob,"1")
value_cond_prob = get_mean_std_dev_labelled_examples(negative_examples,numeric_features,value_cond_prob,"0")
return value_cond_prob
def get_mean_std_dev_labelled_examples(labelled_data,numeric_features,value_cond_prob,lab_val):
total = len(labelled_data)
for feature in numeric_features:
summation = 0.0
mean = 0.0
std_dev = 0.0
all_vals = []
for example in labelled_data:
summation = float(summation) + float(example[feature])
all_vals.append(float(example[feature]))
mean = float(summation)/float(total)
summation = 0.0
for value in all_vals:
dev = float(value) - float(mean)
numerator = float(dev)**2
summation = float(summation) + float(numerator)
std_dev = float(summation)/float(total)
std_dev = float(std_dev)**(0.5)
value_cond_prob[feature + "_" + lab_val] = [mean,std_dev]
return value_cond_prob
'''This function is used for training the Naive Bayes classifier and returning the corresponding
conditional probability values which is the model that is learned.
'''
def train_naive_bayes_get_classifier(training_data,values_in_features,numeric_features):
prior_positive = find_prior_probability("1",training_data)
prior_negative = find_prior_probability("0",training_data)
#print "Done finding prior probabilities for class labels."
value_cond_prob = store_all_feature_value_label_cond_probabilities(training_data,values_in_features)
value_cond_prob = store_mean_std_dev_numeric_attributes(training_data,numeric_features,value_cond_prob)
value_cond_prob['prior_positive'] = prior_positive
value_cond_prob['prior_negative'] = prior_negative
#print "Done storing conditional probabilities for attribute values."
return value_cond_prob #Return the model for the Naive Bayes classifier.
def calc_gaussian_prob(value,mean,std_dev):
diff = float(value) - float(mean)
diff_sq = float(diff)**2
variance = float(std_dev)**2
diff_sq = (-1) * float(diff_sq)/float(2.0*variance)
exp_term = float(math.exp(diff_sq))
denom = float(2.0 * math.pi * variance)
denom = float(denom**(0.5))
return float(exp_term)/float(denom)
'''This function is used to return the predictions of the classifier on testing data.
'''
def get_predictions_from_model(value_cond_prob,testing_data,nominal_features,numeric_features):
predictions = []
for example in testing_data:
predicted_label = "0"
features_prob_product_positive = 1.0
features_prob_product_negative = 1.0
for feature in nominal_features:
string_lookup = str(feature) + ':' + str(example[feature]) + ':1'
features_prob_product_positive = float(features_prob_product_positive) * float(value_cond_prob[string_lookup])
string_lookup = str(feature) + ':' + str(example[feature]) + ':0'
features_prob_product_negative = float(features_prob_product_negative) * float(value_cond_prob[string_lookup])
for num_feature in numeric_features:
string_lookup = str(num_feature) + "_" + "1"
mean,std_dev = value_cond_prob[string_lookup]
features_prob_product_positive = float(features_prob_product_positive) * float(calc_gaussian_prob(example[num_feature],mean,std_dev))
string_lookup = str(num_feature) + "_" + "0"
mean,std_dev = value_cond_prob[string_lookup]
features_prob_product_negative = float(features_prob_product_negative) * float(calc_gaussian_prob(example[num_feature],mean,std_dev))
if (float(features_prob_product_positive * value_cond_prob['prior_positive']) >= float(features_prob_product_negative * value_cond_prob['prior_negative'])):
predicted_label = "1"
predictions.append(predicted_label)
return predictions
'''This function is used to evaluate the accuracy/quality of the classifier on the test data
and for printing the metrics like the true positives, negatives, etc.
'''
def print_metrics(testing_data,predictions):
global label
true_positives = 0
false_negatives = 0
false_positives = 0
true_negatives = 0
num_examples = len(testing_data)
for example_num in range(0,num_examples):
predicted_label = predictions[example_num]
if testing_data[example_num][label] == "1":
if predicted_label == "1":
true_positives += 1
elif predicted_label == "0":
false_negatives += 1
elif testing_data[example_num][label] == "0":
if predicted_label == "1":
false_positives += 1
elif predicted_label == "0":
true_negatives += 1
print true_positives,"\t",false_negatives,"\t",false_positives,"\t",true_negatives
def read_csv(fhandle):
data = []
reader = csv.DictReader(fhandle)
data = [row for row in reader]
return data
def csv_process(train_file,test_file):
global label
global num_attr_list
training_data = read_csv(train_file)
testing_data = read_csv(test_file)
all_features = training_data[0].keys()
all_features.remove(label)
max_index = len(all_features)
numeric_features = num_attr_list
for feature in numeric_features:
all_features.remove(feature)
values_in_features = find_distinct_values_feature(training_data,testing_data,all_features)
return training_data,testing_data,values_in_features,max_index,numeric_features
if __name__ == "__main__":
if(len(sys.argv)) != 4:
print usage("NaiveBayes.py")
sys.exit(1)
else:
train_file_name = sys.argv[1]
test_file_name = sys.argv[2]
pred_file_name = sys.argv[3]
train_file = open(train_file_name,"r")
test_file = open(test_file_name,"r")
training_data,testing_data,values_in_features,max_index,numeric_features = csv_process(train_file,test_file)
train_file.close()
test_file.close()
value_cond_prob = train_naive_bayes_get_classifier(training_data,values_in_features,numeric_features)
nominal_features = values_in_features.keys()
predictions = get_predictions_from_model(value_cond_prob,training_data,nominal_features,numeric_features)
print_metrics(training_data,predictions)
predictions = get_predictions_from_model(value_cond_prob,testing_data,nominal_features,numeric_features)
pred_file = open(pred_file_name,"w")
for pred in predictions:
pred_file.write(str(pred) + "\n")
pred_file.close()
|
# RESTAURANT COLLECTION PROGRAM
# ICS 31, UCI, David G. Kay, Fall 2015
# Implement Restaurant as a namedtuple, collection as a list
##### MAIN PROGRAM (CONTROLLER)
def restaurants(): # nothing -> interaction
""" Main program
"""
print("Welcome to the restaurants program!")
our_rests = Collection_new()
our_rests = handle_commands(our_rests)
print("\nThank you. Good-bye.")
MENU = """
Restaurant Collection Program --- Choose one
n: Add a new restaurant to the collection
r: Remove a restaurant from the collection
s: Search the collection for selected restaurants
p: Print all the restaurants
e: Erase all the restaurants form the collection
c: Change prices for the dishes served
q: Quit
"""
def handle_commands(C: list) -> list:
""" Display menu, accept and process commands.
"""
while True:
response = input(MENU)
if response=="q":
return C
elif response=='n':
r = Restaurant_get_info()
## Dish_display(Menu_enter())
C = Collection_add(C, r)
elif response=='r':
n = input("Please enter the name of the restaurant to remove: ")
C = Collection_remove_by_name(C, n)
elif response=='p':
print(Collection_str(C))
elif response=='s':
n = input("Please enter the name of the restaurant to search for: ")
for r in Collection_search_by_name(C, n):
print(Restaurant_str(r))
elif response=='e':
C.clear()
elif response=='c':
n = float(input('Please enter the percent amount to change the dish price: '))
C = collection_change_price(C,n)
## elif response=='m':
## print(Dish_display(Menu_enter(C)))
else:
invalid_command(response)
def invalid_command(response): # string -> interaction
""" Print message for invalid menu command.
"""
print("Sorry; '" + response + "' isn't a valid command. Please try again.")
##### Dishes
from collections import namedtuple
Dish = namedtuple('Dish', 'name price cal')
def Dish_str(d: Dish) -> str:
'''Takes a Dish and returns a string.'''
return d.name + ' ($' + str(d.price) + '): ' + str(d.cal) + ' cal\n '
def Dish_get_info() -> Dish:
return Dish(
input('\nPlease enter the name of the Dish: '),
float(input('Please enter the price of the Dish: ')),
input('Please enter the amount of calories of the Dish: '))
##### Menus
dishes_input = '\nWould you like to add a Dish?'
def Menu_enter() -> list:
cuisine = []
while True:
response = input(dishes_input)
if response == 'yes':
cuisine.append(
Dish_get_info())
elif response == 'no':
return cuisine
def Dish_display(result: list) -> str:
s = ''
for d in result:
s = s + Dish_str(d)
return s
##### Restaurant
Restaurant = namedtuple('Restaurant', 'name cuisine phone menu')
##Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price')
# Constructor: r1 = Restaurant('Taillevent', 'French', '01-11-22-33-44', 'Escargots', 23.50)
def Restaurant_str(self: Restaurant) -> str:
return (
"Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: " + Dish_display(self.menu) + "\n")
## return (
## "Name: " + self.name + "\n" +
## "Cuisine: " + self.cuisine + "\n" +
## "Phone: " + self.phone + "\n" +
## "Dish: " + self.dish + "\n" +
## "Price: ${:2.2f}".format(self.price) + "\n\n")
def Restaurant_get_info() -> Restaurant:
""" Prompt user for fields of Restaurant; create and return.
"""
return Restaurant(
input("Please enter the restaurant's name: "),
input("Please enter the kind of food served: "),
input("Please enter the phone number: "),
Menu_enter())
## return Restaurant(
## input("Please enter the restaurant's name: "),
## input("Please enter the kind of food served: "),
## input("Please enter the phone number: "),
## input("Please enter the name of the best dish: "),
## float(input("Please enter the price of that dish: ")))
#### COLLECTION
# A collection is a list of restaurants
def Collection_new() -> list:
''' Return a new, empty collection
'''
return [ ]
def Collection_str(C: list) -> str:
''' Return a string representing the collection
'''
s = ""
for r in C:
s = s + Restaurant_str(r)
return s
def Collection_search_by_name(C: list, name: str) -> list:
""" Return list of Restaurants in input list whose name matches input string.
"""
result = [ ]
for r in C:
if r.name == name:
result.append(r)
return result
def Collection_add(C: list, R: Restaurant) -> list:
""" Return list of Restaurants with input Restaurant added at end.
"""
C.append(R)
return C
def Collection_remove_by_name(C: list, name: str) -> list:
""" Given name, remove all Restaurants with that name from collection.
"""
result = [ ]
for r in C:
if r.name != name:
result.append(r)
return result
def Dish_price_change(D: Dish, n: int) -> Dish:
return D._replace(price = D.price * (1 + 0.01 * n))
def Menu_price_change(M: list, n: int) -> list:
result = []
for dish in M:
result.append(Dish_price_change(dish, n))
return result
def Restaurant_price_change(R: Restaurant, n: int) -> float:
result = Menu_price_change(R.menu, n)
R = R._replace(menu = result)
return R
def collection_change_price(C:list, n: int)->list:
result = []
for rest in C:
result.append(Restaurant_price_change(rest, n))
return result
def Dishprice_change(R: Restaurant, n: float) -> Restaurant:
new_menu = []
new_menu = R.menu._replace(price = float(R.price) * (1 + 0.01 * n))
return new_menu
restaurants()
|
if __name__ == "__main__":
# for i in range(0,3):
# for k in range(0,i):
# print('*', end=" ")
# print("\n")
n,i = 8,0
rowCounter = 0
while(i<n):
for k in range(0,i+1):
print('*',end=" ")
if(i==n):
break
i+=1
print("\r") |
class Node:
def __init__(self,val):
self.val = val
self.next = None
def __repr__(self):
return "Node data is = {}".format(self.val)
def getval(self):
return self.val
def setval(self, new_val):
"""Replace the data with new"""
self.val = new_val
def getnext(self):
""""Return next attribute"""
return self.next
def setnext(self,new_next):
""""new next"""
self.next = new_next
class SinglyLinkedList:
def __init__(self):
self.head = None
#self.length = 0
def __repr__(self):
return "SLL object: head={}".format(self.head)
def isEmpty(self):
"""returns true if linked list is empty"""
return self.head is None
def addFront(self,val):
temp = Node(val)
temp.setnext(self.head)
self.head = temp
def size(self):
size = 0
if self.head is None:
return size
current = self.head
while(current): #while there are nodes to count
size += 1
#current = current.next
current= current.getnext()
return size
def search(self,searchterm):
if self.head is None:
return "Linked list is empty, no nodes to search"
current = self.head
while(current):
if(current.getval()==searchterm):
return True
else:
current = current.getnext()
return False
def remove(self,val):
if self.isEmpty():
return "List is empty, nothing to remove"
current = self.head
previous = None
found = False
while(not found):
if(current.getval()==val):
found = True
else:
if(current.getnext()==None):
return "Node not found"
else:
previous = current
current = current.getnext()
if(previous is None):
self.head = current.getnext()
else:
previous.setnext(current.getnext())
return found
if __name__ == "__main__":
# node = Node('apple')
# node.getval()
# node.setval(7)
# node.getval()
# node2 = Node('carrot')
# node.setnext(node2)
# print(node.getnext())
node1 = Node(4)
sll = SinglyLinkedList()
print(sll.isEmpty())
sll.head = node1
print(sll.isEmpty())
sll.addFront('Barry')
print(sll.head)
print(sll.size())
print(sll.search('barry')) |
def maxProfit(prices):
if(min(prices)) == min[:-1]:
return 0
if __name__ == "__main__":
a= [7,1,5,3,6,4]
print(min(a))
print(a[-1])
|
class solution:
# Iterate over all the elements in nums\text{nums}nums
# If some number in nums\text{nums}nums is new to array, append it
# If some number is already in the array, remove it
def singleNumber(self, nums: List[int]) -> int:
counter = []
nums.sort()
for i in range(0, len(nums)):
if(nums[i] in counter):
counter.remove(nums[i])
else:
counter.append(nums[i])
return counter.pop()
if __name__ == "__main__":
nums=[2,1,2]
s = solution
s.singleNumber(nums) |
def validPyramid(A: list) -> bool:
if(A==[] or len(A)<3):
return False
getMax=max(A)
print(getMax)
i=0
j=A.index(getMax)
validPyramidBool = False
if(j==len(A)-1 or j==0):
return False
else:
while(i<j):
if(A[i]<A[i+1]):
validPyramidBool = True
else:
validPyramidBool = False
return validPyramidBool
i+=1
while(j<len(A)-1):
if(A[j]>A[j+1]):
validPyramidBool = True
else:
validPyramidBool=False
break
j+=1
return validPyramidBool
if __name__ == "__main__":
#https://leetcode.com/problems/valid-mountain-array/
listA=[2,1]
print(validPyramid(listA)) |
import datetime as dt
def run():
name = input("What is your name? ")
age = int(input("What is your age? "))
now = dt.datetime.now()
one_hundred = (now.year - age) + 100
print(f"Hi {name} you are {age} years old and in the year {one_hundred} you will be 100 years old")
if __name__ == "__main__":
run()
|
class MyStatic:
def reset(self): # 파이썬 메소드 선언 방식
self.x = 0
self.y = 0
a = MyStatic()
MyStatic.reset(a) # 클래스 메소드
# a.reset() 인스턴스 메소드
print('x의 값', a.x)
print('y의 값', a.y)
|
# open a file named sample.txt and write to it
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# using context manager
# with open()
# allows us to allocate and release resources
# no need to use file.close()
with open("sample.txt", 'w', encoding='utf-8') as file:
file.write("Writing this line in the file.\n")
file.write("Now we'll write some values:\n")
for number in numbers:
file.write(f"number = {number}\n")
file.write("The end.")
|
from collections import deque
deq = deque(["one", "two", "three"])
print(deq)
deq.append("four")
print(deq)
deq.appendleft("zero")
print(deq)
print(".popleft() and deq after")
print(deq.popleft())
print(deq)
print(".pop() and deq after")
print(deq.pop())
print(deq)
|
print(type("hello"))
str1 = "It is string with 'double' \" quotes"
str2 = 'It is string with "single" \' quotes'
print(str1 + " " + str2)
multiline1 = """First line
Second line"""
print(multiline1)
multiline2 = '''First line
Second line'''
print(multiline2)
multiline3 = """First line\
And this is still the first line"""
print(multiline3)
phrase = "You shall not pass!"
print(phrase[-1]) # the last symbol in the string
print(phrase[:3]) # substring form the start to the 3 symbol exclusive
print(phrase[4:]) # substring form the 5 symbol to the end
print(phrase[10:14]) # substring from 10 to 14 symbols
print(len(phrase)) # length of the string
print("Hi! " * 3) # prints 'Hi! Hi! Hi! '
|
#List Comprehensions is a very powerful tool, which creates a new list based on another list, in a single, readable line.
#For example, let's say we need to create a list of integers which specify the length of each word in a certain sentence, but only if the word is not the word "the".
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
wordLengths = []
for word in words:
if word != "the":
wordLengths.append(len(word))
print(words)
print(wordLengths)
#using list comprehension
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
wordLengths = [len(word) for word in words if word != "the"]
print(words)
print(wordLengths)
#exercise
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [int(number) for number in numbers if number >= 0 ]
print(newlist)
#solution
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [int(x) for x in numbers if x > 0]
print(newlist)
|
#Multiples of 3 and 5
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
sumOfMultiples = 0
multiples = []
count = 0
while count < (1000):
if (count % 3 == 0 or count % 5 == 0):
multiples.append(count)
sumOfMultiples += count
print(sumOfMultiples)
count += 1
|
#Training used: LearnPython.org
#Hello world + variables
print("hello world")
fruits = ["1", "2", "3", "4", "5"]
for x in fruits:
print(x)
x = 1
if x == 1:
#standard indentation is 4 spaces
print("x is 1")
print("goodbye world")
#Integer
myInt = 20
print (myInt)
#Float
myFloat = 7.111
print(myFloat)
myFloat = float(7)
print(myFloat)
#String
myString = "Hello"
print(myString)
myString = 'Hello'
print(myString)
#Use "" where you can
myString = "Don't worry about apostrophes when using double quotes"
print(myString)
#Simple operators
#adding integers
one = 1
two = 2
three = one + two
print(three)
#adding strings
hello = "hello"
world = "world"
helloWorld = hello + world
print(helloWorld)
#declaring more than one variable per line
three, four = 3, 4
print(three, four)
#mixing int and strings don't work
#one = 1
#two = 2
#hello = "hello"
#print(one + two + hello)
myInt = 20
myFloat = 10.0
myString = "Hello"
#variable comparison
if myString == "Hello":
print("String: %s" % myString)
if isinstance(myFloat, float) and myFloat == 10.0:
print("Float: %f" % myFloat)
if isinstance(myInt, int) and myInt == 20:
print("Int: %d" % myInt)
|
#Generators: special iterator function that returns a iterable set, one at a time, in a special way
#generators are very easy to implement, but a bit difficult to understand.
#Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.
#When an iteration over a set of item starts using the for statement, the generator is run. Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.
#Here is a simple example of a generator function which returns 7 random integers:
#EXAMPLE
import random
def lottery():
#returns 6 number between 1 and 40
for i in range(6):
yield random.randint(1,40)
#returns a 7th number between 1 and 15
yield random.randint(1,15)
for randomNumber in lottery():
print("And the next number is... %d!" % (randomNumber))
# SOLUTION from site fill in this function
def fib():
a = 1
b = 1
while 1:
yield a
a, b=b, a + b
# testing code
import types
if type(fib()) == types.GeneratorType:
print("Good, The fib function is a generator.")
counter = 0
for n in fib():
print(n)
counter += 1
if counter == 10:
break |
no1=3
no2=9
print(float(no1+no2))
nu1=-3
#print(float(nu1+no2))
ni1=3.0
ni2=-9
#print(ni2+ni1)
#print(float(no1*no2))
#Q3
in1=10
in2=5.4
cm="cm"
m="m"
answer1=in1*1000
answer2=in1*1000000
answer3=in2*1000
answer4=in2*1000000
#print(str(answer1)+m)
#print(str(answer2)+cm)
#print(str(answer3)+m)
#print(str(answer4)+cm)
#Q4
name = input(f"What is your name? ")
height = input("How tall are you? ")
print(f"{name} is {height}cms tall.") |
groceries = {
"Baby Spinach": 2.78,
"Hot Chocolate": 3.70,
"Crackers": 2.10,
"Bacon": 9.00,
"Carrots": 0.56,
"Oranges": 3.08
}
quantity = {
"Baby Spinach": 1,
"Hot Chocolate": 3,
"Crackers": 2,
"Bacon": 1,
"Carrots": 4,
"Oranges": 2
}
for key, item in groceries.items():
print(f"{quantity[key]} {key} @ ${item} = ${round(quantity[key]*item)}.2")
colour_counts = {
"blue": 0,
"green": 0,
"yellow": 0,
"red": 0,
"purple": 0,
"orange": 0,
}
colours = [
"purple",
"red",
"yellow",
"blue",
"purple",
"orange",
"blue",
"purple",
"orange",
"green"
]
for colour in colours:
# print(colour)
# print(colour_counts[colour])
# colour_counts[colour]
#if colour exists in list
colour_counts[colour] += 1
for colour in colour_counts:
print(f"{colour}: {colour_counts[colour]}")
|
def find_unknown_number(x,y,z):
n = 0
while n % 3 != x or n % 5 != y or n % 7 !=z:
n += 1
return n
print(find_unknown_number(2,3,2)) |
class animal(object):
def __init__(self, type):
self.type = type
if type == "antelope":
self.eats = ["grass"]
elif type == "big-fish":
self.eats = ["little-fish"]
elif type == "bug":
self.eats = ["leaves"]
elif type == "bear":
self.eats = ["big-fish","bug", "chicken", "cow", "leaves", "sheep"]
elif type == "chicken":
self.eats = ["bug"]
elif type == "cow":
self.eats = ["grass"]
elif type == "fox":
self.eats = ["chicken", "sheep"]
elif type == "giraffe":
self.eats = ["leaves"]
elif type == "lion":
self.eats = ["antelope", "cow"]
elif type == "panda":
self.eats = ["leaves"]
elif type == 'sheep':
self.eats = ["grass"]
else:
self.eats = []
def __repr__(self) -> str:
return self.type
def who_eats_who(zoo):
zoolist = zoo.split(",")
classlist = []
results = [zoo]
for i in zoolist:
classlist.append(animal(i))
done = False
while done == False and len(classlist) > 1:
size = len(classlist)
for pos, val in enumerate(classlist):
if pos > 0:
if classlist[pos - 1].type in val.eats:
results.append(f"{val.type} eats {classlist[pos - 1].type}")
classlist.pop(pos - 1)
break
if pos < size-1:
if classlist[pos + 1].type in val.eats:
results.append(f"{val.type} eats {classlist[pos + 1].type}")
classlist.pop(pos + 1)
break
if len(classlist) == size:
done = True
results.append(",".join([x.type for x in classlist]))
return results
print(who_eats_who("chicken,fox,leaves,bug,grass,sheep")) |
"""
Given is a md5 hash of a five digits long PIN. It is given as string. Md5 is a function to hash your password: "password123" ===> "482c811da5d5b4bc6d497ffa98491e38"
Why is this usefull? Hash functions like md5 can create a hash from string in a short time and it is impossible to find out the password, if you only got the hash. The only way is cracking it, means try every combination, hash it and compare it with the hash you want to crack. (There are also other ways of attacking md5 but that's another story) Every Website and OS is storing their passwords as hashes, so if a hacker gets access to the database, he can do nothing, as long the password is safe enough.
What is a hash: https://en.wikipedia.org/wiki/Hash_function#:~:text=A%20hash%20function%20is%20any,table%20called%20a%20hash%20table.
What is md5: https://en.wikipedia.org/wiki/MD5
Note: Many languages have build in tools to hash md5. If not, you can write your own md5 function or google for an example.
Here is another kata on generating md5 hashes: https://www.codewars.com/kata/password-hashes
Your task is to return the cracked PIN as string.
This is a little fun kata, to show you, how weak PINs are and how important a bruteforce protection is, if you create your own login.
"""
import hashlib
import itertools
def crack(hash):
for comb in range(0,100000):
code = str(comb).zfill(5)
str2hash = hashlib.md5(code.encode())
if str2hash.hexdigest() == hash:
return code
|
def duplicate_digits(ndigit):
total = 0 # in a 1 digit number, duplicates occur 0 times
for i in range(2,ndigit+1):
total = (total + (10 ** (i-2)))*9
#return total
return total / ((10 ** (ndigit-1)) * 9)
print(duplicate_digits(7))
|
import numpy
class Vector:
def __init__(self,x=0,y=0,z=0):
if type(x) is list or type(x) is numpy.ndarray:
self.x,self.y,self.z = x
else:
self.x = x
self.y = y
self.z = z
self.magnitude = numpy.linalg.norm([self.x,self.y,self.z])
def to_tuple(self):
return (self.x,self.y,self.z)
def __str__(self):
return f"<{self.x}, {self.y}, {self.z}>"
def __eq__(self, o: "Vector") -> bool:
if type(o) is Vector:
if self.magnitude == o.magnitude and self.to_tuple() == o.to_tuple():
return True
else:
return False
else:
if self.magnitude == o:
return True
else:
return False
def __add__(self, other: "Vector"):
return Vector(self.x + other.x,self.y + other.y, self.z + other.z)
def __sub__(self, other: "Vector"):
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def cross(self,other: "Vector"):
return Vector(numpy.cross(self.to_tuple(),other.to_tuple()))
def dot(self,other: "Vector"):
return numpy.dot(self.to_tuple(),other.to_tuple())
test1 = Vector(1,2,3)
test2 = Vector(1,2,3)
print(test1.dot(test2))
print(test1.magnitude) |
def missing(s):
testlist = sequencer(s)
if testlist == -1:
return testlist
if len(testlist) != testlist[-1] - testlist[0]:
return -1
truelist = [x for x in range(testlist[0],testlist[-1] + 1)]
for test,true in zip(testlist,truelist):
if test != true:
return true
def reindexer(lst):
#TODO allow changing number of digits to next highest (IE, 99 -> 100)
pass
def sequencer(s):
for numlist in slicer(s):
truecount = 0
for pos,num in enumerate(numlist):
if pos == 0:
continue
if int(num) == int(numlist[pos - 1]) + 1:
truecount += 1
else:
truecount -= 1
if truecount >= 0:
return [int(x) for x in numlist]
return -1
def slicer(s):
for i in range(1,len(s)//2):
yield recursive_helper(s,i)
def recursive_helper(s,n):
returnlist=[]
return strsplit(s,n,returnlist)
def strsplit(s,n,returnlist):
if len(s) == 0:
return returnlist
strappend, remainder = s[0:n], s[n:]
if len(remainder) == 0:
returnlist.append(strappend)
return strsplit(remainder, n, returnlist)
elif strappend.count("9") == len(strappend) and remainder[0] == "1" or strappend.count("9") + strappend.count("8") == len(strappend) and remainder[0] == "1":
if len(returnlist) == 0:
remainder = s[n:]
returnlist.append(strappend)
return strsplit(remainder, n + 1, returnlist)
elif returnlist[-1].count("9") != len(returnlist[-1]):
remainder = s[n:]
returnlist.append(strappend)
return strsplit(remainder, n+1, returnlist)
returnlist.append(strappend)
return strsplit(remainder,n,returnlist) |
import math
class Person:
def __init__(self, name, i_d, age):
self.name = name
self.i_d = i_d
self.age = age
class Student(Person):
def __init__(self, name, i_d, age, average, institute):
Person.__init__(self, name, i_d, age)
self.average = average
self.institute = institute
def funcprint(self):
print("STUDENT:")
print("Name:",self.name)
print("ID:",self.i_d)
print("Age",self.age)
print("Average:",self.average)
print("institute:",self.institute)
class Employee(Person):
def __init__(self, salary):
self.salary = salary
def funcprint(self):
print("EMPLOYEE:")
print("Name:", self.name)
print("ID:", self.i_d)
print("Age", self.age)
print("Salary:", self.salary)
class WorkingStudent(Employee, Student):
def __init__(self, name, i_d, age, average, institute, salary, same_institute):
Employee.__init__(self, name, i_d, age, salary)
Student.__init__(self, name, i_d, age, average, institute)
self.same_institute = same_institute
def funcprint(self):
print("WORKINSTUDENT:")
print("Name:", self.name)
print("ID:", self.i_d)
print("Age", self.age)
print("Average:", self.average)
print("institute:", self.institute)
print("Salary:", self.salary)
print("Are the Student from the same institute:",self.same_institute)
def printall(arr):
for i in range(0, len(arr)):
arr[i].funcprint()
def start():
size = int(input("Enter size for arr:"))
arr = []
for i in range(0, size):
type = input("Enter type of person(Student , Employee, Workingstudent):")
while type not in ('Student', 'Employee', 'Workingstudent'):
print("This type is not exist!!\n Try again ")
type = input("Enter type of person(Student , Employee, Workingstudent):")
if type == "Student":
name = input("Enter name:")
i_d = input("Enter ID:")
age = input("Enter age:")
average = input("Enter avareage:")
institute = input("Enter institute:")
s = Student(name, i_d, age, average, institute)
arr.append(s)
if type == "Employee":
name = input("Enter name:")
i_d = input("Enter ID:")
age = input("Enter age:")
salary = input("Enter salary:")
e = Employee(name, i_d, age, salary)
arr.append(e)
if type == "Workingstudent":
name = input("Enter name:")
i_d = input("Enter ID:")
age = input("Enter age:")
average = input("Enter avareage:")
institute = input("Enter intitute:")
salary = input("Enter salary:")
same_institute = input("Are the Student from the same institute?:")
w = WorkingStudent(name, i_d, age, average, institute, salary, same_institute)
arr.append(w)
printall(arr)
start()
|
class BaseClass():
def __init__(self):
print("base ile init")
def set_name(self, name):
self.name = name
print("base set")
def display_name(self):
print("name is " + self.name)
class SubClass(BaseClass):
def __init__(self):
super().__init__()
print("sub ile init")
def set_name(self, name):
self.name = name
print("subile set")
def welcome(self):
print("welcomes you")
x = SubClass()
x.set_name("shuaib")
x.display_name()
x.welcome()
|
import datetime
now=datetime.datetime.now()
print(now.strftime("%d:%m:%Y"))
print(datetime.date.today().month)
x=datetime.datetime(2020,10,7)
y=datetime.datetime(2020,10,2)
dif=x-y
print(dif) |
import math
#V = 1/3 * pi * r **2 * h
print("Enter Radius:")
radius = input()
print("Enter Height:")
height = input()
volume = 1 / 3 * math.pi * float(radius) * float(radius) * float(height)
print("Volume = " + str(volume))
# t = 0 Me^(r(T-t)) T = 15 - Continuous
# t = 0 M(1+rT) = 15 - Discrete
Principle = 500
Time = 1.5
Rate = 3.5
Maturity = Principle * (1 + Rate * Time)
print("Maturity = " + str(Maturity))
|
import numpy as np
import data_preprocessing as dp
# THe activation function sigmoid
def sigmoid(z):
"""
Calculating and outputting n the sigmoid value from the given value z.
Args:
z: The variable z of the sigmoid funtion
Returns:
The calculation result
"""
return 1/(1+np.exp(-z))
# The initialisation function
def initialise(dim):
"""
Initialising weights and bias with 0.
Args:
dim: The dimension of vector W
Returns:
W: A vector of 0, the shape of W is (dim, 1)
b: A scalar of 0
"""
W = np.zeros(shape=(dim, 1))
b = 0
return W, b
# The flattening function
def flatten(m):
"""
Given a matrix whose shape is (x, a, b, c), outputting a new flattened matrix by converting the shape from
(x, a, b, c) to (a * b *c, x).
Args:
m: A matrix whose shape is (x, a, b, c)
Returns:
A new matrix whose shape is (a * b * c, x)
"""
return m.reshape(m.shape[0], -1).T
# The propagation function (forward propagation and backward propagation)
def propagate(W, b, X, Y):
"""
Calculating the cost value, gradients dw and db which are used for updating the parameters weights and bias.
Args:
W: The vector of weights
b:The parameter scalar of bias
X: The images used for training whose shape is (x, a, b, c)
Y: The ground truth labels of the corresponding images used for training whose shape is (x, 1)
Returns:
cost: the cost value based on the current parameters
gradients: a dictionary composed of gradients dw and db based on the current parameters
"""
m = X.shape[1]
# Forward propagation
A = sigmoid(np.dot(W.T, X) + b)
cost = (- 1 / m) * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
# Backward propagation
db = (1 / m) * np.sum(A - Y)
dW = (1 / m) * np.dot(X, (A - Y).T)
gradients = {
"dW": dW,
"db": db
}
return gradients, cost
# The optimisation function
def optimise(W, b, X, Y, lr, iterations):
"""
Given training sampeles X and Y, updating the parameters weights and bias.
Args:
W: The vector of weights whose shape is (sample_num, 1).
b: The scalar of bias, an int number.
X: Images used for training whose shape is (sample_num, width, height, colour_chanels).
Y: Labels used for training whose shape is (sample_num, 1).
lr: Learning rate, an int number.
iterations: The number of training iterations, an int number.
Returns:
cost: A array of cost values whose length is sample_num.
params: A dictionary of updated weights and bias.
gradients: a dictionary of final gradients dw and db.
"""
# the array of costs
costs = []
updated_W = W
updated_b = b
for i in range(iterations):
gradients, cost = propagate(W, b, X, Y)
dW = gradients["dW"]
db = gradients["db"]
# Updating W and b by subtracting dW and db from them
updated_W -= lr * dW
updated_b -= lr * db
# Saving and printing the cost every 100 iterations
if i % 100 == 0:
costs.append(cost)
print("The cost after iteration %i: %f" % (i, cost))
params = {
"W": updated_W,
"b": updated_b
}
gradients = {
"dW": dW,
"db": db
}
return params, gradients, costs
# The prediction function
def predict(params, X):
"""
Given test set X, prediect the corresponding label Y.
Args:
params: The dictionary comprising the updated parameters weights and bias.
X: The images for test whose shape is (sample_num, width, height, colour_chanels).
Returns:
prediction_Y: The array of predicted labels.
"""
W = params["W"]
b = params["b"]
m = X.shape[1]
prediction_Y = np.zeros(shape=(1,m))
# Calculating the prediction value A by using updated parameters W and b based on training samples X
A = sigmoid(np.dot(W.T, X) + b)
print("A shape:")
print(A.shape)
for i in range(A.shape[1]):
if A[0, i] > 0.5:
prediction_Y[0, i] = 1
else:
prediction_Y[0, i] = 0
return prediction_Y
# The model function
def model(X_train, X_test, Y_train, Y_test, lr, iterations):
"""
Integrating all the functions together, calculating prediction_Y on training sets and tests and the
accuracy rate.
Args:
X_train: The images for training whose shape is (sample_num, width, height, colour_chanels).
X_test: The images for test whose shape is (sample_num, width, height, colour_chanels).
Y_train: The ground truth label for training whose shape is (sample_num, 1).
Y_test: The ground truth label for test whose shape is (sample_num, 1).
lr: Learning rate, an int number.
iterations: The number of training iterations, an int number.
Returns:
costs: An array of costs
Y_predictions: An dictionary composed of the prediction of training set and the prediction of test test
params: An dictionary composed of the updated parameters weights and bias
"""
# m is the number of features
X_train_flatten = flatten(X_train)
X_test_flatten = flatten(X_test)
m = X_train_flatten.shape[0]
# Initialisation of weights and bias
W, b = initialise(m)
# propagation and optimisation
params, gradients, costs = optimise(W, b, X_train_flatten, Y_train, lr, iterations)
# prediction
prediction_Y_train = predict(params, X_train_flatten)
prediction_Y_test = predict(params, X_test_flatten)
predictions = {
"prediction_Y_train": prediction_Y_train,
"prediction_Y_test": prediction_Y_test
}
# Calculating accuracy rate
print("train accuracy: {} %".format(100 - np.mean(np.abs(prediction_Y_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(prediction_Y_test - Y_test)) * 100))
return params, gradients, costs, predictions
# Testing models
X_train, X_test, Y_train, Y_test = dp.get_dataset()
d = model(X_train, X_test, Y_train, Y_test, 0.005, 10000)
|
##Reorganizing the POS File -pos_file.txt-
import re
import transliteration
##Organizing in a dictionary file, the words as keys and the POS -
##tag as their values
my_text = open("pos_file.txt", 'r', encoding="utf8")
pos_text = my_text.read()
my_text.close()
regex = '"(.{,10}">.*)<'
match = re.findall(regex, pos_text)
pos_text_out = str(list(match))[1:-2]
list_ = pos_text_out.split(",")
i = 0
new_list = []
while i < len(list_):
x = list_[i].split('\">')
new_list.append(x)
i += 1
k = 0
pos_keys = []
pos_values = []
pos_dict = {} #the dictionary file of pos
while k < len(list_):
pos_keys.append(new_list[k][1][:-1])
pos_values.append(new_list[k][0][2:])
k += 1
pos_dict = dict(zip(pos_keys, pos_values))
#print(pos_dict[translitration.translit('ከደ')])
|
# This program is a simple program that implements raw_input
# and string formatting. The user gets asked a series of questions
# and then a formatted sentence is generated based on their response.
#
# There is also a try-except-else to catch whether the user types in
# a non-number for the number of pets that they have.
first_name = raw_input("Tell us your first name: ")
last_name = raw_input("Tell us your last name: ")
favorite_color = raw_input("Tell us your favorite color: ")
number_of_pets = ""
while True:
try:
number_of_pets = int(raw_input("Tell us how many pets you have: "))
if number_of_pets < 0:
print "That's a negative number!"
continue
except (ValueError):
print "That's not a number, dawg!, try again."
else: # no ValueError problems
break
# format the print statement section
message = "Great! So your name is %s %s, \nyour favorite color is %s and you have %d pets. \
\nNice to meet you!" % (first_name, last_name, favorite_color, number_of_pets)
print message
|
#%% Imports
import pandas as pd
#%% Load master class CSV
classList = pd.read_csv('Data/masterClassList.csv')
classList.head()
#%% Gather some class size statistics
avgMaxEnrl = classList['Max Enrl'].mean()
avgCurEnrl = classList['Cur Enrl'].mean()
avgPercentEnrl = avgCurEnrl / avgMaxEnrl * 100
print("The average maximum capacity for a class is {:.2f}".format(avgMaxEnrl))
print("The average actual size of a class is {:.2f}".format(avgCurEnrl))
print("The average class is {:.2f}% full".format(avgPercentEnrl))
#uvm has 18:1 student teacher ratio so this seems pretty acurate
numClasses = classList['Cur Enrl'].count()
numUnder20 = classList[classList['Cur Enrl'] < 20]['Cur Enrl'].count()
percentUnder20 = numUnder20/numClasses * 100
print("{:.2f}% of the classes had under 20 students in them".format(percentUnder20))
numClasses = classList['Max Enrl'].count()
numUnder20 = classList[classList['Max Enrl'] < 20]['Max Enrl'].count()
percentUnder20 = numUnder20/numClasses * 100
print("{:.2f}% of the classes had a max size of under 20 students".format(percentUnder20))
# Uvm claims 48.7% of classes fewer than 20 students
#%% Gather some department statistics
deparmentClasses = classList['Department'].value_counts()
#157 class categories in the registrar
pd.set_option("display.max_rows", None, "display.max_columns", None)
print(deparmentClasses)
# The registrar splits the courses up by categories with 157 categories in total
# The category with the most offered classes was EUROPEAN--STUDIES with 108
# classes, this was followed by
# music, environmental studies, business admin, and english.
# Mathematics and cs had 57 classes, stats had 32, and complex systems had 10
|
n=int(input("enter your number"))
fact=1
for i in range(1,n+1):
fact=fact*i
print("factorial of {0} is : ".format(n), fact)
|
from datetime import date
class Zodiac:
def make_date(self, month, day, year=2000):
return date(year, month, day)
def date_includes(self, month, day):
_date = self.make_date(month, day)
return self.lower_bound <= _date <= self.upper_bound
class Aries(Zodiac):
def __init__(self):
self.name = 'aries'
self.lower_bound = self.make_date(3, 21)
self.upper_bound = self.make_date(4, 19)
class Taurus(Zodiac):
def __init__(self):
self.name = 'taurus'
self.lower_bound = self.make_date(4, 20)
self.upper_bound = self.make_date(5, 20)
class Gemini(Zodiac):
def __init__(self):
self.name = 'gemini'
self.lower_bound = self.make_date(5, 21)
self.upper_bound = self.make_date(6, 20)
class Cancer(Zodiac):
def __init__(self):
self.name = 'cancer'
self.lower_bound = self.make_date(6, 21)
self.upper_bound = self.make_date(7, 22)
class Leo(Zodiac):
def __init__(self):
self.name = 'leo'
self.lower_bound = self.make_date(7, 23)
self.upper_bound = self.make_date(8, 22)
class Virgo(Zodiac):
def __init__(self):
self.name = 'virgo'
self.lower_bound = self.make_date(8, 23)
self.upper_bound = self.make_date(9, 22)
class Libra(Zodiac):
def __init__(self):
self.name = 'libra'
self.lower_bound = self.make_date(9, 23)
self.upper_bound = self.make_date(10, 22)
class Scorpio(Zodiac):
def __init__(self):
self.name = 'scorpio'
self.lower_bound = self.make_date(10, 23)
self.upper_bound = self.make_date(11, 21)
class Sagittarius(Zodiac):
def __init__(self):
self.name = 'sagittarius'
self.lower_bound = self.make_date(11, 22)
self.upper_bound = self.make_date(12, 21)
class Capricorn(Zodiac):
def __init__(self):
self.name = 'capricorn'
self.lower_bound = self.make_date(12, 22, year=2000)
self.upper_bound = self.make_date(1, 19, year=2001)
def date_includes(self, month, day):
year = 2000 if month == 12 else 2001
_date = self.make_date(month, day, year=year)
return self.lower_bound <= _date <= self.upper_bound
class Aquarius(Zodiac):
def __init__(self):
self.name = 'aquarius'
self.lower_bound = self.make_date(1, 20)
self.upper_bound = self.make_date(2, 18)
class Pisces(Zodiac):
def __init__(self):
self.name = 'pisces'
self.lower_bound = self.make_date(2, 19)
self.upper_bound = self.make_date(3, 20)
|
first_name = input("Anna etunimi: ")
last_name = input("Anna sukunimi: ")
for i in range(len(first_name)):
print(first_name[0], end = "")
print(" ", end = "")
i = len(last_name)
while i > 0:
print(last_name[i-1], end = "")
i = i-1 |
import Statistics as st
# read in input from STDIN
n = int(input())
# grab the elements
data = list(map(int, input().split()))
# grab the frequency
freq = list(map(int, input().split()))
# create an empty list
s = []
# loop through the range of n
for i in range(n):
# multiple the frequency by the data number and store it in a list
s+= [data[i]] * freq[i]
# sum the freq and sort s
N = sum(freq)
s.sort()
# write an if-else statement to find q1 and q3
if n%2 != 0:
q1 = st.median(s[:N//2])
q3 = st.median(s[N//2+1:])
else:
q1 = st.median(s[:N//2])
q3 = st.median(s[N//2:])
# find the range
ir = round(float(q3-q1), 1)
print(ir)
|
def clever_function():
return u'HELLO'
def find_string(string,list):
ret=False
for line in list:
if string in line:
ret= True
return ret |
#!/usr/bin/env python3
from itertools import product
from decimal import *
"""
Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,
where each “_” is a single digit.
"""
getcontext().prec = 19
exponents = [
10**1, 10**3, 10**5, 10**7, 10**9, 10**11, 10**13, 10**15, 10**17, 10**19
]
for l in product([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], repeat=9):
form = Decimal(1020304050607080900)
for i in range(9):
form += exponents[i] * l[i]
if form.sqrt() % 1 == 0:
print("sqrt({}) = {}".format(form, form.sqrt()))
break
|
found72=False
number=0
while not found72 and number!=3:
list=int(input())
number=number+1
if list!=72:
print("again")
if list==72:
print("win")
found72=True
elif number==3:
print("lost")
|
import turtle
#Insertion_Sort: takes one parameter, a list of Rectangle objects
#Uses insertion sort to sort the list in place from highest z value
# to lowest.
#Doesn't return anything.
def Insertion_Sort(shapels):
#Implement your insertion sort here.
for index in range(1,len(shapels)):
key = shapels[index]
#"i" is sub index
i = index-1
while (i>=0 and shapels[i].d < key.d):
shapels[i+1] = shapels[i]
i-=1
shapels[i+1] = key
pass
#Rectangle class, turtle graphics, and test case setup
#You shouldn't change any of the code below, but do read it.
#Rectangle class. Represents a single rectangle on the turtle canvas
class Rectangle:
#self.x: x coord of the Rectangle's lower left corner
#self.y: y coord of the Rectangle's lower left corner.
#self.d: depth of the Rectangle: higher values represent Rectangles
# further in the background
#self.w: extent of the Rectangle in the x direction
#self.l: extent of the Rectangle in the y direction
#self.c: String representing the color of the Rectangle
#self.id: Unique string identifier for object
def __init__(self,xpos,ypos,depth,width,length,color,name):
self.x = xpos
self.y = ypos
self.d = depth
self.w = width
self.l = length
self.c = color
self.id = name
#Draw method: takes in a Turtle object and draws the Rectangle
def draw(self,turt):
turt.penup()
turt.setpos(self.x,self.y)
turt.color(self.c)
turt.begin_fill()
turt.pendown()
for i in range(2):
turt.forward(self.w)
turt.left(90)
turt.forward(self.l)
turt.left(90)
turt.end_fill()
#String representation of Rectangle object: depth:identifier
def __repr__(self):
return str(self.d)+":"+self.id
#Set up turtle graphics
turtle.hideturtle()
t = turtle.Turtle()
t.speed(10)
s = turtle.getscreen()
s.tracer(1,1)
#Create Rectangles in scene
background = Rectangle(-400,-300,60,800,600,"lime green","background")
building = Rectangle(-150,-50,41,300,150,"ivory4","building")
door = Rectangle(50,-50,40,35,70,"burlywood4","door")
line1 = Rectangle(-200,-145,20,50,5,"yellow","line1")
line2 = Rectangle(150,-145,20,50,5,"yellow","line2")
leaves1 = Rectangle(-200,10,30,110,80,"dark green","leaves1")
leaves2 = Rectangle(90,-70,10,220,150,"dark green","leaves2")
river = Rectangle(-400,70,50,800,100,"blue","river")
road = Rectangle(-400,-200,21,800,100,"black","road")
trunk1 = Rectangle(-160,-70,31,30,110,"brown","trunk1")
trunk2 = Rectangle(170,-230,11,60,220,"brown","trunk2")
window = Rectangle(-110,-10,40,80,60,"grey20","window")
#Create test case lists
scene1 = []
scene2 = [river]
scene3 = [trunk2,road]
scene4 = [leaves2,trunk2,line2,line1,road,leaves1,trunk1,window,
door,building,river,background]
scene5 = [background,river,building,door,window,trunk1,leaves1,
road,line1,line2,trunk2,leaves2]
scene6 = [building,background,door,line1,line2,leaves1,leaves2,
river,road,trunk1,trunk2,window]
#List of test cases and their correct sorted versions
tests = [scene1,scene2,scene3,scene4,scene5,scene6]
correct = [[],
[river],
[road,trunk2],
[background,river,building,window,door,trunk1,leaves1,
road,line2,line1,trunk2,leaves2],
[background,river,building,door,window,trunk1,leaves1,
road,line1,line2,trunk2,leaves2],
[background,river,building,door,window,trunk1,leaves1,
road,line1,line2,trunk2,leaves2]]
#Run test cases, check whether sorted list correct
count = 0
for i in range(len(tests)):
try:
print("Running: Insertion_Sort(",tests[i],")\n")
Insertion_Sort(tests[i])
print("Expected:",correct[i],"\n\nGot:",tests[i])
if (correct[i] == tests[i]):
count=count+1
else:
print("FAIL: Incorrect output")
except Exception as e:
print("FAIL: Error ", e)
print()
print(count,"out of",len(tests),"tests passed.")
#Draw Rectangles in list in sequence.
for element in scene6:
element.draw(t)
t.hideturtle()
|
import traceback, turtle
#Takes as input a Square object node in a graph of Square nodes.
# This will always be the Square node representing (0,0), the start position
#Performs BFS until the goal Square is found (the Square with val == 2).
#Returns a list containing each Square node in the path from the start
# (0,0) to the goal node, inclusive, in order from start to goal.
def find_path(start_node):
start_node.set_color("gray")
start_node.depth = 0
start_node.prev = None
#TODO: Finish the BFS and return the path from start_node to the goal
pathList = []
q = Queue()
q.enqueue(start_node)
while not q.isEmpty():
node = q.dequeue()
for el in node.adj:
if el.get_color() == "white":
el.set_color("grey")
el.depth = node.depth + 1
el.prev = node
q.enqueue(el)
if el.val == 2:
newList = []
newList.append(el)
while el.prev:
el = el.prev
newList.append(el)
newList.reverse()
return newList
node.set_color("black")
pathList.append(node)
return pathList
class Queue:
def __init__(self):
self.nodes = []
def isEmpty(self):
return self.nodes == []
def enqueue(self, node):
self.nodes.insert(0,node)
def dequeue(self):
return self.nodes.pop()
def size(self):
return len(self.nodes)
# DO NOT EDIT BELOW THIS LINE
#Square class
#A single square on the grid, which is a single node in the graph.
#Has several instance variables:
# self.t: The turtle object used to draw this square
# self.x: The integer x coordinate of this square
# self.y: The integer y coordinate of this square
# self.val: An integer, which is 0 if this square is blocked, 1
# if it's a normal, passable square, and 2 if it's the goal.
# self.adj: A list representing all non-blocked squares adjacent
# to this one. (This is the node's adjacency list)
# self.__color: A private string representing the color of the square
# Must be accessed using set_color and get_color because it's private
# The color of the square is purple if it's a blocked square.
# Otherwise, it starts as white, and then progresses to grey and then
# black according to the BFS algorithm.
# self.depth: An integer representing the depth of the node within BFS
# self.prev: A Square object pointing to the node from which this node
# was discovered from within BFS: the pi variable in the textbook
class Square:
def __init__(self,x,y,val,t):
self.t = t
self.x = x
self.y = y
self.val = val
self.adj = []
if self.val:
self.__color = "white"
else:
self.__color = "purple"
self.depth = float("inf")
self.prev = None
#Getters and setters for color variable. You MUST use these rather
# than trying to change color directly: it causes the squares to
# actually update color within the graphics window.
def set_color(self,color):
if color != self.__color:
self.__color = color
self.draw()
def get_color(self):
return self.__color
#Draws the square
def draw(self):
t = self.t
t.hideturtle()
t.speed(0)
t.pencolor("blue")
if self.__color == "purple":
t.pencolor("purple")
if self.val != 2:
t.fillcolor(self.__color)
else:
t.fillcolor("blue")
t.penup()
t.setpos(self.x-.5,self.y-.5)
t.pendown()
t.begin_fill()
for i in range(4):
t.forward(1)
t.left(90)
t.end_fill()
#String representation of a Square object: (x,y)
def __repr__(self):
return "("+str(self.x)+","+str(self.y)+")"
#Check equality between two Square objects.
def __eq__(self,other):
return type(self) == type(other) and \
self.x == other.x and self.y == other.y
#Takes as input a 2D list of numbers and a turtle object
#Outputs a 2D list of Square objects, which have their adjacency
# lists initialized to all adjacent Square objects that aren't
# blocked (so their val isn't 0).
def grid_to_squares(grid,t):
square_grid = []
for j in range(len(grid)):
square_row = []
for i in range(len(grid[j])):
square_row.append(Square(i,j,grid[j][i],t))
square_grid.append(square_row)
for j in range(len(grid)):
for i in range(len(grid[j])):
adj = []
if j+1 < len(grid) and grid[j+1][i]:
adj.append(square_grid[j+1][i])
if i+1 < len(grid[j]) and grid[j][i+1]:
adj.append(square_grid[j][i+1])
if j-1 >= 0 and grid[j-1][i]:
adj.append(square_grid[j-1][i])
if i-1 >= 0 and grid[j][i-1]:
adj.append(square_grid[j][i-1])
square_grid[j][i].adj = adj
return square_grid
#Draws the entire grid of Square objects.
def draw_grid(square_grid):
for j in range(len(square_grid)):
for i in range(len(square_grid[j])):
square_grid[j][i].draw()
#Test cases
square_turtle = turtle.Turtle()
square_turtle.hideturtle()
square_turtle.speed(0)
square_turtle.pencolor("blue")
map0 = grid_to_squares(
[[1,2],
[0,0]],square_turtle)
map1 = grid_to_squares(
[[1, 0, 2],
[1, 0, 1],
[1, 1, 1]],square_turtle)
map2 = grid_to_squares(
[[1,1,1,1,1,1,1],
[1,1,1,1,1,1,1],
[1,1,1,0,0,0,0],
[1,1,1,0,2,1,1],
[1,1,1,0,1,1,1],
[1,1,1,1,1,1,1],
[1,1,1,1,1,1,1]],square_turtle)
map3 = grid_to_squares(
[[1,1,0,0,0,0,0,0,0,0],
[1,1,1,0,1,1,1,1,1,0],
[0,1,1,0,1,0,1,1,1,0],
[0,1,1,1,1,0,1,1,1,0],
[0,1,0,0,0,0,0,0,1,0],
[0,1,1,0,1,2,1,1,1,0],
[0,0,1,0,1,0,1,0,1,0],
[0,0,1,0,1,0,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0]],square_turtle)
path0 = [map0[0][0],
map0[0][1]]
path1 = [map1[0][0],
map1[1][0],
map1[2][0],
map1[2][1],
map1[2][2],
map1[1][2],
map1[0][2]]
path2 = [map2[0][0],
map2[1][0],
map2[2][0],
map2[3][0],
map2[4][0],
map2[5][0],
map2[5][1],
map2[5][2],
map2[5][3],
map2[5][4],
map2[4][4],
map2[3][4]]
path3 = [map3[0][0],
map3[1][0],
map3[1][1],
map3[2][1],
map3[3][1],
map3[4][1],
map3[5][1],
map3[5][2],
map3[6][2],
map3[7][2],
map3[8][2],
map3[8][3],
map3[8][4],
map3[7][4],
map3[6][4],
map3[5][4],
map3[5][5]]
tests = [map0,map1,map2,map3]
correct = [path0,path1,path2,path3]
#Run test cases, check whether output path correct
count = 0
import random
try:
for i in range(len(tests)):
print("\n---------------------------------------\n")
print("TEST #",i+1)
turtle.resetscreen()
turtle.setworldcoordinates(-1,-1,len(tests[i][0]),len(tests[i]))
turtle.delay(0)
square_grid = tests[i]
turtle.tracer(0)
draw_grid(square_grid)
turtle.tracer(1)
pathlst = find_path(square_grid[0][0])
if i == 0:
turtle.delay(1)
else:
turtle.speed(i)
tom = turtle.Turtle()
tom.speed(1)
tom.color("green")
tom.shape("turtle")
tom.left(90)
for square in pathlst:
tom.goto(square.x,square.y)
if i < 3:
print("Expected:",correct[i],"\nGot :",pathlst)
assert pathlst == correct[i], "Path incorrect"
print("Test Passed!\n")
count += 1
except AssertionError as e:
print("\nFAIL: ",e)
except Exception:
print("\nFAIL: ",traceback.format_exc())
print(count,"out of",len(tests),"tests passed.")
|
# dictionaries are like matlab structures
# written as mydict = {'key','value'}
# function get() used to check and see if a field exists
fav_numbers = {'pat':5,'jim':9,'tom':2,'john':5}
print(f"Pat's favorite number is {fav_numbers['pat']}")
for name, fav in fav_numbers.items():
print(f"{name.title()}'s favorite number is {fav}.")
friends = ['tom','linda']
for name in fav_numbers.keys():
print(name.title())
if name in friends:
number = fav_numbers[name]
print(f"\t{name.title()}, I see you like {number}")
else:
print(f"\t{name.title()}, please take the survey!")
print("The following numbers are favorites:")
for number in set(fav_numbers.values()):
print(number)
# Can do dictionaries inside lists or lists inside dictionaries
# Can also do dictionaries inside dictionaries
users = {'czurn': {'first':'claire','last':'zurn'},'lblatti':{'first':'luke','last':'blatti'}}
for username,user_info in users.items():
print(f"\nUsername:{username}")
full_name = f"{user_info['first']} {user_info['last']}"
print(f"\tFull name: {full_name.title()}")
|
class GraphNode:
def __init__(self, val=None, neighbors=None):
self.val = val
if neighbors is None:
self.neighbors = []
else:
self.neighbors = neighbors
visited = False
class Graph:
def __init__(self, nodes=None):
if nodes is None:
self.nodes = []
else:
self.nodes = nodes
def addNode(self, node: GraphNode):
self.nodes.append(node)
def clearVisited(self):
for node in self.nodes:
node.visited = False
|
import keys
import tweepy as t
import json
from wordcloud import WordCloud
auth = t.OAuthHandler(keys.consumer_key, keys.consumer_secret)
auth.set_access_token(keys.access_token, keys.access_token_secret)
api = t.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
tweets = api.search(q="vote", count=3)
#print(tweets)
# Excercise - based om the object created above, print out the screen name
# user and the text of the tweet
'''
for tweet in tweets:
print(tweet.user.screen_name, ":", tweet.text)
tweets = api.search(q = "#collegefootball", count =2)
for tweet in tweets:
print(tweet.user.screen_name, ":", tweet.text)
'''
# Places with Trending Topics
trends_available = api.trends_available()
#print(len(trends_available))
#print(trends_available[:3]) # trends_available is a list of dicts
world_trends = api.trends_place(id = 1)
#print(world_trends)
outfile = open('world_trends.json', 'w')
json.dump(world_trends, outfile, indent = 5)
trends_list = world_trends[0]['trends']
#print(trends_list)
# Excercise
# using list comprehension grab those trends that
# have more than 10,000 tweets
'''
trends_list = [t for t in trends_list if t["tweet_volume"]]
from operator import itemgetter
trends_list.sort(key = itemgetter("tweet_volume"), reverse = True)
print(trends_list[:5])
print out the name of the topic for the 5 top topics.
for trend in trends_list[:5]:
#print(trend["name"])
'''
# Excercise
# Find the trending topics for New York City and
# create a wordcloud from it New York City Trending Topics
nyc_trends = api.trends_place(id=2459115)
nyc_trends_list = nyc_trends[0]['trends']
nyc_trends_list = [t for t in nyc_trends_list if t["tweet_volume"]]
from operator import itemgetter
nyc_trends_list.sort(key = itemgetter("tweet_volume"), reverse = True)
topics = {} #create empty dictionary
for trend in nyc_trends_list:
#print(trend)
topics[trend["name"]] = trend["tweet_volume"]
wordcloud = WordCloud(
width=1600,
height=900,
prefer_horizontal=0.5,
min_font_size=10,
colormap="prism",
background_color="white",
)
wordcloud = wordcloud.fit_words(topics)
wordcloud = wordcloud.to_file("TrendingTwitter_fall2020.png")
|
import numpy as np
mat_a = np.array([[2, 3, 4], [1, 2, 4]])
mat_b = np.array([[3, 4], [4, 3], [2, 4]])
mat_c = np.dot(mat_a, mat_b)
mat_d = np.zeros([2,2])
# Please employ the for loops to finih the matrix multiplication.
# Your answer "mat_d" should be equivalent to "mat_c"
for idx1 in range(2):
for idx2 in range(2):
for idx3 in range(3):
pass
print (mat_d)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""RFC822 like parsing.
There is just enough to read a succession of fields separated by empty lines.
Multilines are supported and line separators are kept. Only space on first
column is removed.
"""
import string
KEY_CHARS = string.ascii_letters + '-_+' + string.digits
class RFC822Exception(Exception):
"""Error while parsing RFC822 like messages."""
pass
class RFC822:
"""Very simple RFC822 implementation.
Just enough to parse packages definitions.
"""
def __init__(self, io):
"""Create parser on file like object `io`.
`io` shall support reading lines using iteration, `close()` method
and `closed` attribute.
"""
self.io = io
self.n = 0
def __error(self, msg):
"""Raise `RFC822Exception` from current line."""
raise RFC822Exception('line {}: {}'.format(self.n, msg))
def __fields(self):
"""Generator on each field in message.
Stop on empty line or when there is no longer input to read.
"""
def _concat(field):
if len(field) == 1:
field = field[0].rstrip()
else:
field = ''.join(field)
return field
header = []
for line in self.io:
self.n += 1
if line == '\n':
if header:
break
elif line[0] in ' \t':
if header:
if len(line) == 3 and line[1] == '.' and line[2] == '\n':
header.append('\n')
else:
header.append(line[1:])
else:
self.__error('unexpected whitespace at start of line')
else:
if header:
yield _concat(header)
header = [line]
else:
self.io.close()
if header:
yield _concat(header)
def messages(self):
"""Generator that yield each message."""
while not self.io.closed:
message = list()
for field in self.__fields():
try:
key, value = field.split(':', 1)
except ValueError:
self.__error('no header found')
key, value = key.rstrip(), value.lstrip()
if not key:
self.__error('empty header')
if not all([c in KEY_CHARS for c in key]):
self.__error('key shall only contain ASCII,digits letters or "-_+"')
message.append((key, value))
yield message
|
import threading
import time
import random
class CustThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self): #this is called when the thread is executed
getTime(self.name)
print("Thread", self.name, "Execution Ends")
def getTime(name):
print("Thread {} sleeps at {}".format(name,
time.strftime("%H:%M:%S", time.gmtime())))
randSleepTime = random.randint(1, 5)
time.sleep(randSleepTime)
thread1 = CustThread("1")
thread2 = CustThread("2")
thread1.start()
thread2.start()
print("Thread 1 Alive:", thread1.is_alive()) #check if thread1 is alive
print("Thread 2 Alive:", thread2.is_alive()) #check if thread2 is alive
print("Thread 1 Name:", thread1.getName()) #get name of thread
print("Thread 2 Name:", thread2.getName()) #get name of thread
thread1.join() #wait for threads to exit
thread2.join()
print("Execution Ends")
|
import random
sj = random.randint(0,100)
count = 1
while count <= 5:
guess = int(input('请输入一个数字: '))
if guess == sj:
print('你真棒!')
break
elif guess < sj:
print('数字猜小了!')
else:
print('数字猜大了!')
count += 1
if count == 6:
print('太笨了,请重新投币!')
|
lie = []
while True:
t = input('请输入任务或者do: ')
if t != 'do':
lie.append(t)
else:
if len(lie) > 0:
print(lie.pop(0))
else:
print('下课了!')
break
|
#一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
'''
程序分析:
假设该数为 x。
1、则:x + 100 = n^2, x + 100 + 168 = m^2
2、计算等式:m^2 - n^2 = (m + n)(m - n) = 168
3、设置: m + n = i,m - n = j,i * j = 168,i 和 j 至少一个是偶数
4、可得: m = (i + j) / 2, n = (i - j) / 2,i 和 j 要么都是偶数,要么都是奇数。
5、从 3 和 4 推导可知道,i 与 j 均是大于等于 2 的偶数。
6、由于 i * j = 168, j>=2,则 2 <= i <= 168 / 2 。
7、接下来将 i 的所有数字循环计算即可。
'''
for i in range(2,85):
if 168 % i == 0 :
j = 168 / i
if i > j and (i + j) % 2 == 0 and (i - j) % 2 == 0 :
m = (i + j) / 2
n = (i - j) / 2
x = n * n - 100
print(x)
|
name = input('请输入name:')
age = input('请输入age:')
height = input('请输入height:')
weight = input('请输入weight:')
gender = input('请输入gender:')
print("你输入的名字是:", name, "你输入的年龄是:", age, "你输入的身高是:" ,height, "输入的体重是:" ,weight, "你输入的性别是:", gender)
|
num = []
while True:
promit = input('请输入一个任务或者do:')
if promit != 'do':
num.append(promit)
else:
if len(num) > 0:
print(num.pop(0))
else:
print('毕业啦!')
break
|
num = []
while True:
test = input('请输入任务或do:')
if test != 'do':
num.append(test)
else:
if len(num) > 0:
print(num.pop(0))
else:
print('OK,这些钱都是你了!')
break |
#Exercise 4.1 of Cracking the Coding Interview
#Given a directed graph, design an algorithm to find out whether there is a path route between two nodes
#################################################################################
#Recursive Solution
def find_path(graph, start, end, path=None):
"""
>>> find_path(graph, 'A', 'D')
['A', 'B', 'C', 'D']
"""
if path is None:
path = []
path += [start]
#this is the base case:
if start == end:
return path
if start not in graph:
return None
for adj_node in graph[start]:
if adj_node not in path:
return find_path(graph, adj_node, end, path)
return None
#Simple graph traversal, check to see if node is found using Queue (list of lists)
#Graph is in an adjacent list representation
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
def bfs(graph, start, end):
queue = []
queue.append([start]) # push 1st path into queue
while queue:
path = queue.pop(0)
node = path[-1] # get last node from path
if node == end:
return path
for adjacent in graph.get(node,[]):
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
return None
#CTCI solution: Simple graph traversal, check to see if node is found & keep track of visited nodes"
#Iterative Implementation of Breadth-First Search using deque
class DirectedGraph:
def __init__(self, content):
self.content = content
self.neighbors = []
def find_path2(start, end):
if start is end:
return True
elif start is None or end is None:
return False
visited = set([start, end])
from Queue import deque # double-ended queue supports adding & removing elements from either end
queue = deque([start])
while len(queue) > 0:
node = queue.popleft()
for child in node.neighbors:
if child is end:
return True
elif child not in visited:
visited.add(child)
queue.append(child)
return False
#For a non-directed graph, iterative implemention of Breadth-First Search - Non-recursive
def find_path3(start, end):
possible_nodes = Queue()
seen = set()
possible_nodes.enqueue(start)
seen.add(start)
while not possible_nodes.is_empty():
start = possible_nodes.dequeue()
if start == end:
return True
else:
for adj_node in start.adjacent:
if adj_node not in seen:
possible_nodes.enqueue(adj_node)
seen.add(adj_node)
return None
#################################################################################
if __name__ == "__main__":
import doctest
doctest.testmod()
|
#Exercise 2.5 of Cracking the Coding Interview
#You have 2 numbers represented by a linked list where each node contains a single digit. The digits are stored in reverse order such that the 1's digit is at the head of the list. Write a function that adds the 2 numbers and returns the sum as a linked list
#################################################################################
#Time = O(n)
#Space = O(1)
from linked_list import *
def sum_lists(node1, node2):
"""
>>> from linked_list import *
>>> ll = LinkedList()
>>> ll.data_to_list([7,1,6])
>>> ll2 = LinkedList()
>>> ll2.data_to_list([5,9,2])
>>> sum_lists(ll, ll2)
LinkedList([2, 1, 9])
"""
current1 = node1.head
current2 = node2.head
result_ll = LinkedList() # result node
tens_place = 0
while current1 is not None and current2 is not None:
sum1 = tens_place
if current1 is not None:
sum1 += current1.data
current1 = current1.next
if current2 is not None:
sum1 += current2.data
current2 = current2.next
digit = sum1 % 10
result_ll.addNode(digits)
tens_place = sum1/10
# sum1 % 10
return result_ll
#################################################################################
#Recursive Solution
#Time: O(n)
#Space: O(n)
# def sum_lists2(node1, node2, carry=0):
# """
# >>> from linked_list import *
# >>> ll = LinkedList()
# >>> ll.data_to_list([7,1,6])
# >>> ll2 = LinkedList()
# >>> ll2.data_to_list([5,9,2])
# >>> sum_lists2(ll, ll2)
# LinkedList([2, 1, 9])
# """
# if node1 is None and node2 is None and carry == 0:
# return None
# result = LinkedList() # new node
# value = carry
# if node1 is not None:
# value += node1.data
# if node2 is not None:
# value += node2.data
# result.data = value % 10 # gets the ones' place digit
# if node1 is not None or node2 is not None and value >= 10:
# more = sum_lists2(node1.next, node2.next, carry == 1)
# elif node1 is not None or node2 is not None and value < 10:
# more = sum_lists2(node1.next, node2.next, carry == 0)
# result.next = more
# return result
#################################################################################
if __name__ == "__main__":
import doctest
doctest.testmod()
|
#Exercise 1.8 of Cracking the Coding Interview
#Write an alogrithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
#################################################################################
from random import randint
#Time = O(M*N)
#Space = O(M*N)
def get_zeros(matrix):
"""
>>> get_zeros([[1, 0, 3, 6],[4, 8, 6, 2],[7, 8, 9, 0]])
([0, 2], [1, 3])
"""
# matrix = [[0]*n for i in range(m)]
# matrix = []
# for i in range(m):
# new = []
# for j in range(n):
# element = randint(0,9)
# new.append(element)
# matrix.append(new)
row_list = []
column_list = []
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
row_list.append(i)
column_list.append(j)
return row_list, column_list
def set_zeros(matrix, row_list, column_list):
"""
>>> set_zeros([[1, 0, 3, 6],[4, 8, 6, 2],[7, 8, 9, 0]], [0, 2], [1, 3])
[[0, 0, 0, 0], [4, 0, 6, 0], [0, 0, 0, 0]]
"""
for row in row_list:
matrix[row] = [0]*len(matrix[row])
for row in matrix:
for col in column_list:
row[col] = 0
return matrix
##################################################################################
if __name__ == "__main__":
import doctest
doctest.testmod()
|
#Exercise 3.2 of Cracking the Coding Interview
#How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop, and min should all operate in O(1) time.
#################################################################################
class StackWithMin(object):
def __init__(self):
self.items = []
self.min = []
def push(self, value):
self.items.append(value)
if len(self.min) == 0 or value <= self.min[-1]:
self.min.append(value)
def pop(self):
if len(self.items) == 0:
return None
data = self.stack.pop()
if data == self.min[-1]:
self.min.pop()
return data
def get_minimum(self):
if len(self.min) == 0:
return None
return self.min[-1]
|
#Implementation of Building a Parse Tree
def buildParseTree(fpexp):
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i not in ['+', '-', '*', '/', ')']:
currentTree.setRootVal(int(i))
parent = pStack.pop()
currentTree = parent
elif i in ['+', '-', '*', '/', ')']:
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
else:
raise ValueError
return eTree
pt = buildParseTree("( ( 10 + 5 ) * 3 )")
#Evaluating a Parse Tree via postorder traversal
def postordereval(parseTree):
opers = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
res1 = None
res2 = None
if parseTree:
res1 = postordereval(parseTree.getLeftChild())
res2 = postordereval(parseTree.getRightChild())
if res1 and res2:
return opers[parseTree.getRootVal()](res1, res2)
else:
return parseTree.getRootVal()
def printexpression(parseTree):
sVal = ""
if parseTree:
sVal = '(' + printexpression(parseTree.getLeftChild())
sVal = sVal + str(parseTree.getRootVal())
sVal = sVal + printexpression(parseTree.getRightChild()) + ')'
return sVal
|
#Exercise 3.6 of Cracking the Coding Interview
#An animal shelther which holds only cats & dogs operatoes on a strictly FIFO basis.
#People must adopt either the oldest of all animals at the shelter or they can select whether they would prefer a dog or a cat.
#They cannot select which specific animal they would like. Create the data structures to maina these system.
#Implement operations such as enqueue, dequeueAny, dequeueDog, dequeueCat.
#################################################################################
class AnimalQueue(object):
def __init__(self):
from collections import deque
self.dog_q = deque()
self.cat_q = deque()
self.time_stamp = 0
def enqueue(self, animal_type, animal_name):
if animal_type == "dog":
self.dog_q.appendleft((animal_name, self.time_stamp))
self.time_stamp += 1
elif animal_type == "cat":
self.cat_q.appendleft((animal_name, self.time_stamp))
self.time_stamp += 1
else:
print "invalid animal type"
def dequeue_any(self):
dog = self.dog_q.pop() if not len(self.dog_q) == 0 else (None, -1)
cat = self.cat_q.pop() if not len(self.cat_q) == 0 else (None, -1)
if dog[1] == -1 and cat[1] == -1:
return None
elif dog[1] < cat[1]:
self.cat_q.append(cat)
return dog[0]
else:
self.dog_q.append(dog)
return cat[0]
def dequeue_cat(self):
if not len(self.cat_q) == 0:
return self.cat_q.pop()[0]
def dequeue_dog(self):
if not len(self.dog_q) == 0:
return self.dog_q.pop()[0]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.