text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
"""Program that performs the backward algorithm
for a hidden markov model"""
import numpy as np
def backward(Observation, Emission, Transition, Initial):
"""Function that performs the backward algorithm
for a hidden markov model"""
if type(Observation) is not np.ndarray or len(Observation.shape) != 1:
return (None, None)
if type(Emission) is not np.ndarray or len(Emission.shape) != 2:
return None, None
if type(Transition) is not np.ndarray or len(Transition.shape) != 2:
return None, None
if Transition.shape[0] != Transition.shape[1]:
return None, None
if type(Initial) is not np.ndarray or len(Initial.shape) != 2:
return None, None
if Emission.shape[0] != Transition.shape[0] != Transition.shape[0] !=\
Initial.shape[0]:
return None, None
if Initial.shape[1] != 1:
return None, None
T = Observation.shape[0]
N, M = Emission.shape
B = np.empty([N, T], dtype='float')
B[:, T - 1] = 1
for t in reversed(range(T - 1)):
B[:, t] = np.dot(Transition,
np.multiply(Emission[:,
Observation[t + 1]], B[:, t + 1]))
P = np.dot(Initial.T, np.multiply(Emission[:, Observation[0]], B[:, 0]))
return (P, B)
|
#!/usr/bin/env python3
""" defines a deep neural network performing binary classification"""
import numpy as np
class DeepNeuralNetwork():
""" defines a deep neural network performing binary classification
using He initialization sqrt(2./layers_dims[l-1]).)"""
def __init__(self, nx, layers):
"""Constructor for class DeepNeuralNetwork"""
if type(nx) is not int:
raise TypeError("nx must be an integer")
if nx < 1:
raise ValueError("nx must be a positive integer")
if type(layers) is not list or not layers:
raise TypeError("layers must be a list of positive integers")
self.__L = len(layers)
self.__cache = {}
self.__weights = {}
for x in range(self.__L):
if type(layers[x]) is not int or layers[x] <= 0:
raise TypeError('layers must be a list of positive integers')
wi = 'W'+str(x + 1)
bi = 'b'+str(x + 1)
if x == 0:
self.__weights[wi] = np.random.randn(layers[x], nx)\
* np.sqrt(2./nx)
else:
self.__weights[wi] = np.random.randn(layers[x], layers[x-1])\
* np.sqrt(2/layers[x-1])
self.__weights[bi] = np.zeros((layers[x], 1))
@property
def L(self):
""" getter function for layers in neural network"""
return self.__L
@property
def cache(self):
"""getter function for intermediate values of network"""
return self.__cache
@property
def weights(self):
""" getter function for Weights and biased of network"""
return self.__weights
|
#!/usr/bin/env python3
"""Program that calculates the derivative of a polynomial"""
def poly_derivative(poly):
"""Function that calculates the derivative of a polynomial"""
if type(poly) is not list or len(poly) == 0:
return None
elif len(poly) == 1:
return [0]
else:
dvPoly = [poly[x] * x for x in range(1, len(poly))]
if dvPoly == 0:
return [0]
return dvPoly
|
import random
class Deck(object):
def __init__(self):
self.deck = []
self.createDeck()
def createDeck(self):
suits = ["Club", "Spade", "Heart", "Diamond"]
faceCards = ["Jack", "Queen", "King", "Ace"]
for outer_count in range(0, 4):
for inner_count in range(1, 14):
if inner_count == 1:
card = Card(suits[outer_count], faceCards[3])
if inner_count == 11:
card = Card(suits[outer_count], faceCards[0])
if inner_count == 12:
card = Card(suits[outer_count], faceCards[1])
if inner_count == 13:
card = Card(suits[outer_count], faceCards[2])
card = Card(suits[outer_count], inner_count)
self.deck.append(card)
def shuffleDeck(self):
random.shuffle(self.deck)
return self.deck
def flipCard(self):
return self.deck.pop()
def resetDeck(self):
self.deck = []
self.creatDeck()
def deal2Cards(self):
dealtCards =[]
for count in range(0, 2)
dealtCards.append(self.deck.pop())
return dealtCards
class Card(object):
def __init__(self, suit, value):
self.suit = suit
self.value = value
if self.suit == "Club" or self.suit == "Spade":
self.color = "Black"
else:
self.color = "Red"
def __repr__(self):
return:"Suit: %r Color: %r Value: %r" % (self.suit, self.color, self.value)
deck1 = Deck()
# print deck1.deck[0].suit
# print deck1.deck[0].color
# print deck1.deck[0].value
print deck1
|
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def printName(a):
for x in a:
print x['first_name'], x['last_name']
printName(students)
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
def printUsers(dict):
for x in dict:
print x
# print data
i = 1
for value in dict[x]:
# print value
# index = data.index("value")
# print index
length = len(value["first_name"]) + len(value["last_name"])
print i, "-", value["first_name"], value["last_name"], "-", length
i += 1
printUsers(users)
for categories, data in users.iteritems():
print categories
i = 1
for element in data:
str = element['first_name']+" "+element['last_name']
print 1, "-", str, "-", len(str)-1
i += 1
|
class Car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price < 10000:
self.tax = 0.12
else:
self.tax = 0.15
def display_all(self):
print "This car is priced at $"+str(self.price)+" and running at "+self.speed+" and the tank is "+self.fuel+" and the mpg is "+self.mileage+" with the tax rate of "+str(self.tax)+"."
car1 = Car(2000, "35mph", "Full", "15mpg")
car2 = Car(2000, "5mph", "No Full", "105mpg")
car3 = Car(2000, "15mpg", "Kind of Full", "95mpg")
car4 = Car(2000, "25mpg", "Full", "25mpg")
car5 = Car(2000, "45mpg", "Empty", "25mpg")
car6 = Car(20000000, "35mpg", "Empty", "15mpg")
print car1.display_all()
print car2.display_all()
print car3.display_all()
print car4.display_all()
print car5.display_all()
print car6.display_all()
|
x=10
y=20;
larger=x if x>y else y
print(f"{larger} is larger")
print(f"{x} is greater than {y}" ) if x>y else print(f"{y} is greter than {x}") |
from random import randint
from typing import Tuple
class ListNode:
def __init__(self, value: int):
self.value = value
self.next = None
def create_num_list(num) -> ListNode:
res = None
last_node = None
for digit in reversed(str(num)):
new_node = ListNode(int(digit))
if last_node is not None:
last_node.next = new_node
else:
res = new_node
last_node = new_node
return res
def list2num(node: ListNode) -> int:
res = 0
mult = 1
while node is not None:
res += mult * node.value
mult *= 10
node = node.next
return res
def add_two_numbers(num1: ListNode, num2: ListNode) -> ListNode:
"""
Add two non-negative numbers represented as a linked lists.
:param num1: first number linked list
:param num2: second number linked list
:return: linked list representing the sum of two numbers
"""
assert (num1 is not None) and (num2 is not None)
res = None
trans_value = 0
last_node = res
def add_digits(val1: int, val2: int = 0, val3: int = 0) -> Tuple[ListNode, int]:
sum_digit = val1 + val2 + val3
new_digit, val3 = sum_digit % 10, sum_digit // 10
new_node = ListNode(value=new_digit)
return new_node, val3
while num1 is not None and num2 is not None:
new_node, trans_value = add_digits(num1.value, num2.value, trans_value)
if last_node is not None:
last_node.next = new_node
else:
res = new_node
last_node = new_node
num1 = num1.next
num2 = num2.next
while num1 is not None:
new_node, trans_value = add_digits(num1.value, trans_value)
last_node.next = new_node
last_node = new_node
num1 = num1.next
while num2 is not None:
new_node, trans_value = add_digits(num2.value, trans_value)
last_node.next = new_node
last_node = new_node
num2 = num2.next
if trans_value != 0:
new_node = ListNode(value=trans_value)
last_node.next = new_node
return res
if __name__ == '__main__':
num1 = 342
num2 = 465
num1_l = create_num_list(num1)
num2_l = create_num_list(num2)
assert list2num(add_two_numbers(num1_l, num2_l)) == num1 + num2
for _ in range(100000):
num_1, num_2 = randint(0, 99999), randint(0, 999999)
num_1_l, num_2_l = create_num_list(num_1), create_num_list(num_2)
true_add = num_1 + num_2
res_node = add_two_numbers(num_1_l, num_2_l)
assert list2num(res_node) == true_add
|
"""
1.每个词条有一个 id = "bodyContent",包含了正文内容,可以缩小范围。
2.词条页面url很统一: /wiki/Multi-paradigm_programming_language
3.为什么有些p标签的内容无法保存?
4.应该重构一下代码:分为两部分:第一部分专注于获取相关url,第二部分专注于保持内容
"""
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
import re
TOPICS = {
"python": "https://en.wikipedia.org/wiki/Python_(programming_language)",
}
pattern = "\/wiki\/[a-zA-Z0-9_\(\)]+"
baseUrl = "https://en.wikipedia.org/wiki"
def getBodyContent(url):
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
}
req = urllib.request.Request(url,headers = headers)
try:
response = urllib.request.urlopen(req)
content = response.read().decode("utf-8")
soup = BeautifulSoup(content, "html.parser")
bodyContent = soup.find(id="bodyContent")
title = soup.find(id = "firstHeading").string
print("正在爬取词条: " + title + " " + url)
return bodyContent
except:
pass
def getWikis(bodyContent, baseUrl):
bodyContent = str(bodyContent)
URLS = []
wikis = re.findall(pattern, bodyContent)
for wiki in wikis:
fullWikiUrl = urllib.parse.urljoin(baseUrl, wiki)
if fullWikiUrl not in URLS:
URLS.append(fullWikiUrl)
return URLS
def storeWikiContent(bodyContent, topic): # 接口:bodyContent是一个soup对象
paras = bodyContent.find_all("p")
with open("wikipedia" + "-" + topic + ".txt", "a+", encoding="utf-8") as f:
for para in paras:
if para:
f.write(para.get_text())
f.write("\n")
print("成功保持词条的内容!")
url = "https://en.wikipedia.org/wiki/Python_(programming_language)"
topic = "python"
bodyContent = getBodyContent(url)
wikiUrls = set(getWikis(bodyContent, baseUrl))
for wikiUrl in wikiUrls:
bodyContent = getBodyContent(wikiUrl)
if bodyContent:
storeWikiContent(bodyContent, topic)
wikiUrls = getWikis(bodyContent, baseUrl)
for wikiUrl in wikiUrls:
bodyContent = getBodyContent(wikiUrl)
if bodyContent:
storeWikiContent(bodyContent, topic)
wikiUrls = getWikis(bodyContent, baseUrl)
for wikiUrl in wikiUrls:
bodyContent = getBodyContent(wikiUrl)
if bodyContent:
storeWikiContent(bodyContent, topic)
wikiUrls = getWikis(bodyContent, baseUrl)
|
class Dog:
species = "Bulldog"
def __init__(self, name, age):
self.name = name
self.umur = age
def toString(self):
print(self.name, self.umur)
def withParameter(self, parameter):
print(self.name, self.umur, parameter)
dog = Dog("Doggy", "2")
print(dog.species)
dog.toString()
dog.withParameter("Parameter")
print(dog.name)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def printStudent(self):
return f"Name: {self.name}\nAge: {self.age}\nGrade: {self.grade}"
yosafat = Student("Yosafat", 22, 100)
print(yosafat.printStudent())
print(yosafat.name)
|
'''
常用运算
'''
import numpy as np
from pandas import Series,DataFrame
df1 = DataFrame(np.arange(9).reshape(3,3), columns=list('ABC'), index=list('abc'))
print(df1)
'''
A B C
a 0 1 2
b 3 4 5
c 6 7 8
'''
f = lambda x: x.max() - x.min()
c = df1.apply(f)
print(c)
'''
A 6
B 6
C 6
'''
print(df1.max()) # 每一列的最大值
'''
A 6
B 7
C 8
'''
print(df1.min()) # 每一列的最小值
'''
A 0
B 1
C 2
'''
print(df1.apply(f,axis=1)) # 每一行的最大值和最小值之差
'''
a 2
b 2
c 2
'''
print(df1.apply(f,axis=0)) # 每一列的最大值和最小值之差,默认每一列
'''
A 6
B 6
C 6
以上代码中,我们定义了 f 匿名函数,该匿名函数简单的返回列表的极差,
然后首先通过 df.apply(f) 应用 f, 统计出了每列的极差,接着通过传入
axis=1 参数,统计出了每行的极差,
如果想将某函数应用到每一个元素上,对于 DataFrame 数据可使用 df.applymap
方法,而对于 Series 数据可以使用 s.map 方法:
'''
print(df1.applymap(lambda x:x+1)) # 应用到每一个元素
'''
A B C
a 1 2 3
b 4 5 6
c 7 8 9
'''
# git config remote.origin.url 'git://github.com/LIZEJU/flask-demo.git'
print('==========')
print(df1.apply(lambda x:x+1))
'''
A B C
a 1 2 3
b 4 5 6
c 7 8 9
''' |
# -*- coding:utf-8 -*-
# Author: 李泽军
# Date: 2020/1/25 6:48 PM
# Project: flask-demo
import re
pattern = re.compile('\w+\d+')
s = 'pwdALLLF123'
s1 = pattern.search(s)
if s1:
print(s1)
print(s1.group(0))
s2 = '111@#$%'
s3 = pattern.search(s2)
print(s3.group(0)) |
def gcd(p,q):
while q != 0:
p,q = q, p % q
return p
p = 35
q = 42
result = gcd(p,q)
print 'GCD of (%s, %s) is %s: ' % (p, q, result)
|
'''
Author: Manzoor Mohammed
URL: https://github.com/manzoormohammed/Python.git
Find min operations needed to enter a pattern on dialpad
DialPad:
1 2 3
4 5 6
7 8 9
* 0 #
Operations:
U
L S R
D
Starts at 1
'''
from __future__ import print_function
import sys
# print error and stop execution with failure
def printerror(message):
print("ERROR: " + message, file=sys.stderr)
sys.exit(1)
# hashmap of the dialpad
def getDialPad():
dialPad = {}
dialPad["1"] = {"row": 0, "col": 0}
dialPad["2"] = {"row": 0, "col": 1}
dialPad["3"] = {"row": 0, "col": 2}
dialPad["4"] = {"row": 1, "col": 0}
dialPad["5"] = {"row": 1, "col": 1}
dialPad["6"] = {"row": 1, "col": 2}
dialPad["7"] = {"row": 2, "col": 0}
dialPad["8"] = {"row": 2, "col": 1}
dialPad["9"] = {"row": 2, "col": 2}
dialPad["*"] = {"row": 3, "col": 0}
dialPad["0"] = {"row": 3, "col": 1}
dialPad["#"] = {"row": 3, "col": 2}
return dialPad
def operationsCount(char, startAt, dialPad):
rowDiff = abs(dialPad[char]["row"] - dialPad[startAt]["row"])
colDiff = abs(dialPad[char]["col"] - dialPad[startAt]["col"])
return rowDiff + colDiff
def minOperations(inputString):
if not inputString:
printerror("Please provide an input string")
dialPad = getDialPad()
startAt = "1"
totalOperations = 0
for char in inputString:
if char not in dialPad:
printerror("Input character '" + char + "' not found in dialPad")
if char != startAt:
totalOperations += operationsCount(char, startAt, dialPad)
# add 1 for operation S (to select)
totalOperations += 1
startAt = char
return totalOperations
# test
print(minOperations("1153*"))
|
# taken from https://wiki.theory.org/Decoding_bencoded_data_with_python
# fixed to work with python3 bytearrays
# could precompute ords but this is more readable
def bdecode(data):
# try to be nice and work on strings too
# done this way to prevent encoding/decoding issues
if type(data) == str:
b = bytearray()
b.extend(map(ord, data))
chunks = b
else:
chunks = bytearray(data)
chunks.reverse()
root = _dechunk(chunks)
return root
def _dechunk(chunks):
item = chunks.pop()
if item == ord('d'):
item = chunks.pop()
h = {}
while item != ord('e'):
chunks.append(item)
key = _dechunk(chunks)
h[key] = _dechunk(chunks)
item = chunks.pop()
return h
elif item == ord('l'):
item = chunks.pop()
l = []
while item != ord('e'):
chunks.append(item)
l.append(_dechunk(chunks))
item = chunks.pop()
return list
elif item == ord('i'):
item = chunks.pop()
num = ''
while item != ord('e'):
num += chr(item)
item = chunks.pop()
return int(num)
elif item < 0x3A and item >= 0x30: # is this a decimal?
num = ''
while item < 0x3A and item >= 0x30 :
num += chr(item)
item = chunks.pop()
line = ''
for i in range(int(num)):
line += chr(chunks.pop())
return line
else:
print(item)
raise Exception("Invalid input!") |
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 1
while i < len(nums):
if nums[i] == nums[i-1]:
nums.remove(nums[i])
i = i+1
return nums
if __name__ == "__main__":
nums = [1,1,2,2,3]
print(Solution().removeDuplicates(nums)) |
class RLEIterator:
def __init__(self, A):
"""
:type A: List[int]
"""
# decode, memory error
self.ret_list = []
for i in range(0, len(A), 2):
self.ret_list.append(A[i]*[A[i+1]])
# trick
self.ret_list = sum(self.ret_list, [])
print(self.ret_list)
# iterator, for next2() function
self.ret_iter = iter(self.ret_list)
# pointer, for next() function
self.ptr = 0
def next(self, n):
if self.ptr+n-1 < len(self.ret_list):
ret = self.ret_list[self.ptr+n-1]
self.ptr += n
return ret
else:
return -1
def next2(self, n):
"""
:type n: int
:rtype: int
"""
try:
for i in range(n-1):
next(self.ret_iter)
return next(self.ret_iter)
except StopIteration:
return -1
# Your RLEIterator object will be instantiated and called as such:
# obj = RLEIterator(A)
# param_1 = obj.next(n)
if __name__ == "__main__":
rle = RLEIterator([3,8,0,9,2,5])
print(rle.next(2))
print(rle.next(1))
print(rle.next(1))
print(rle.next(2))
|
"""
Missing Number Lab written by Kevin Oyowe
October 12, 2016
"""
def find_missing(firstList, secondList):
"""
This function compares two lists and returns the extra number in the longer list
"""
extraList = []
lesserList = []
if len(firstList) > len(secondList):
extraList = firstList
lesserList = secondList
else:
extraList = secondList
lesserList = firstList
extraNumber = [x for x in extraList if x not in lesserList]
if len(extraNumber) == 0:
return 0
return extraNumber.pop() |
#!/usr/bin/python
def n_gramas(cadena, n):
"""
Esta función recibe una cadena y un entero.
:param cadena: Cadena a procesar.
:param n: Número entero que es la ene de los n-gramas.
:return: Lista de n-gramas.
"""
if len(cadena) <= n:
return [cadena]
else:
return [cadena[i:i+n] for i in range(len(cadena) - n + 1)]
|
### Coffee Machine Code ###
"""
====================
OUTLINE
====================
What I need to happen:
Anytime you enter report it will print out a report of
the amount of coffee, water , milk, coins in the Machine
It processes coins, you put in a number of 50p coins or whatever.
Checks it has enough coffee.
Checks if it can do the transaction.
===========================
THE PLAN
===========================
what would you like?
options:
report
cappuccino
latte
black
after report need to print resources and coins
"""
Menu = {
"cappuccino": {
"ingredients": {
"water":250,
"milk":150,
"coffee":24
},
"price":3.0
},
"latte": {
"ingredients": {
"water":200,
"milk":150,
"coffee":24
},
"price":2.5
},
"espresso": {
"ingredients": {
"water":50,
"milk":0,
"coffee":18
},
"price":1.5
}
}
Resources = {
"water":300,
"milk":300,
"coffee":300,
"money":0
}
def Report():
print("Water :", Resources["water"])
print("Milk :", Resources["milk"])
print("Coffee :", Resources["coffee"])
print("Money :", Resources["money"])
def Off():
global On
On = 0
def Order():
order = "test"
while order != "espresso" or "cappuccino" or "latte" or "report" or "off":
print("What would you like? (Espresso/Latte/Cappuccino)")
order = input()
order = order.lower()
print("test order", order)
return order
def CheckResources(order):
order = order.lower()
for i in Resources:
if Resources[i] - Menu[order]["ingredients"][i] < 0:
return False
else:
return True
def MakeCoffee(order):
order = order.lower()
for i in Resources:
try:
Resources[i] = Resources[i] - Menu[order]["ingredients"][i]
except:
pass
print("Please take your", order)
def CoffeeMachine():
while On == 1:
order = Order()
if order == "off":
Off()
elif order == "report":
Report()
else:
if CheckResources(order) == True:
MakeCoffee(order)
else:
print("Not enough resources")
On = 1
CoffeeMachine()
|
import qsimulator as qs
import numpy as np
import time
"""
Deutsch's algorithm is a special case of the general Deutsch-Jozsa algorithm.
It checks the condition f(0) = f(1).
Once all the operations are finished, a measurement is made. If the measured state is |0> the function is
constant (f(0) = f(1)). If the measure state is |1> the function is balanced (f(0) != f(1)).
We use a "quantum implementation" (represented by a matrix in our code) of the function that maps
|x>|y> to |x>|f(x) XOR y>. Unfortunately this matrix has to be brute force computed because of the way our code works.
I don't think this is a problem as any actual implementation (real world implementation) of an oracle is most
definitely going to look nothing like the usual quantum circuit model.
"""
# Constructing random function
def construct_problem():
answers = np.random.randint(0, 2, size=2)
def f(x):
return answers[x]
return f
def deutsch_algorithm(func):
qubit1 = qs.State(np.array([1, 1]) / np.sqrt(2))
qubit2 = qs.State(np.array([1, -1]) / np.sqrt(2))
# Equivalent to initial state |0>|1> passed through Hadamard gate
initState = qubit1 * qubit2
H = qs.hGate()
I = qs.iGate(1)
# Time to create an oracle that we need
operatorMatrix = np.zeros((4, 4))
for i in range(4):
for j in range(4):
leftBit = j // 2
rightBit = j % 2
if 2 * leftBit + (func(leftBit) + rightBit) % 2 == i:
operatorMatrix[i][j] = 1
oracle = qs.QuantumGate(operatorMatrix)
# Applying Hadamard gate to first qubit
finalState = (H * I)(oracle(initState))
measurement = finalState.measure() // 2 # to get the state of the leftmost bit
return measurement
if __name__ == "__main__":
f = construct_problem()
parity = f(0) == f(1)
measurement = deutsch_algorithm(f)
print('f(0): {}, f(1): {}'.format(f(0), f(1)))
print('f(0) == f(1): {}'.format(parity))
print('Measurement: {}'.format(measurement))
|
# codes copied from contacts.py
from tkinter import *
import datetime
import sqlite3
from tkinter import messagebox
date = datetime.datetime.now().date()
date = str(date)
conn = sqlite3.connect('database.db')
cur = conn.cursor()# we use cursor to run queries
class Display(Toplevel):
def __init__(self, person_id):# recieving person_id from contacts.py
Toplevel.__init__(self)
self.geometry('650x650+350+25')
self.title('Display Contact')
self.resizable(False, False)
# print ('person id = ', person_id) #testing if the person_id is recieved
# or not
query = "select * from addressbook where person_id = '{}'".format(person_id)
#Here, .format(person_id) will fill the '{}'
result = cur.execute(query).fetchone()# using fetchone() for one data
# and not fetchall()
# print(result) #testing if the query is working and prints the contact
# details with a tuple in a list using fetchall() method
# but fetchone() method will give result to a tuple only.
#creating variables
self.person_id = person_id # person_id is passed in the constructor.
# Here, it is assigned to a global varialbe so that we can use anywhere.
# Using this variable in update_contact method
person_name = result[1]
person_last_name = result[2]
person_email = result[3]
person_phno = result[4]
person_address = result [5]
#testing if a variable works
# print('Address: ', person_address)# prints address
#copying from add_contacts.py
#creating frames
# self is the tob level window not master
self.top_frame = Frame(self, height = 150, bg = 'white')
self.top_frame.pack(fill = X)
self.bottom_frame = Frame(self, height = 500, bg = '#44465d')
self.bottom_frame.pack(fill = X)
#designing top frame
self.top_image = PhotoImage(file = 'icons/contacts.png')
self.top_image_label = Label(self.top_frame, image = self.top_image, bg = 'white')
self.top_image_label.place(x = 130, y = 25)
self.heading_label = Label(self.top_frame, text = 'Contact Details', font = 'arial 15 bold', bg = 'white', fg = '#7240D0')
self.heading_label.place(x = 230, y = 50)
#date/time
self.date_label = Label(self.top_frame, text = "Today's Date: "+date, font = 'Arial 15 bold', bg = 'white', fg = '#7240D0')
self.date_label.place(x = 400, y = 110)
#Requirement for contact details
#name
self.label_name = Label(self.bottom_frame, text = 'Name: ', font = 'arial 15 bold',fg = 'white', bg = '#97449c')
self.label_name.place(x = 49, y = 40)
self.entry_name = Entry(self.bottom_frame, font = 'arial 15 bold', width = 30, bd = 4, fg = '#ffc0cb')
self.entry_name.insert(0, person_name) # using the defined variable to get the data
self.entry_name.config(state = 'disable')# if we disable the state in the main entry
# box, the entry box will be blank. So, we have to configure it after the insert statement.
self.entry_name.place(x = 180, y = 40)
#last name
self.label_lastname = Label(self.bottom_frame, text = 'Lastname: ', font = 'arial 15 bold',fg = 'white', bg = '#97449c')
self.label_lastname.place(x = 49, y = 80)
self.entry_lastname = Entry(self.bottom_frame, font = 'arial 15 bold', width = 30, bd = 4, fg = '#ffc0cb')
self.entry_lastname.insert(0, person_last_name)# using the defined variable to get the data
self.entry_lastname.config(state = 'disable')
self.entry_lastname.place(x = 180, y = 80)
#email
self.label_email = Label(self.bottom_frame, text = 'Email: ', font = 'arial 15 bold',fg = 'white', bg = '#97449c')
self.label_email.place(x = 49, y = 120)
self.entry_email = Entry(self.bottom_frame, font = 'arial 15 bold', width = 30, bd = 4, fg = '#ffc0cb')
self.entry_email.insert(0, person_email)# using the defined variable to get the data
self.entry_email.config(state = 'disable')# if we disable the state in the main entry
# box, the entry box will be blank. So, we have to configure it after the insert statement.
self.entry_email.place(x = 180, y = 120)
#ph.no.
self.label_phno = Label(self.bottom_frame, text = 'Mob no: ', font = 'arial 15 bold',fg = 'white', bg = '#97449c')
self.label_phno.place(x = 49, y = 160)
self.entry_phno = Entry(self.bottom_frame, font = 'arial 15 bold', width = 30, bd = 4, fg = '#ffc0cb')
self.entry_phno.insert(0, person_phno)# using the defined variable to get the data
self.entry_phno.config(state = 'disable')# if we disable the state in the main entry
# box, the entry box will be blank. So, we have to configure it after the insert statement.
self.entry_phno.place(x = 180, y = 160)
#address
self.label_address = Label(self.bottom_frame, text = 'Address: ', font = 'arial 15 bold',fg = 'white', bg = '#97449c')
self.label_address.place(x = 49, y = 200)
self.text_address = Text(self.bottom_frame, font = 'arial 15 bold', width = 30, height = 10,bd = 4)
self.text_address.insert(1.0, person_address)# using the defined variable to get the data
self.text_address.config(state = 'disable')# if we disable the state in the main text
# box, the text box will be blank. So, we have to configure it after the insert statement.
self.text_address.place(x = 180, y = 200) |
'''
Self Timer Camera
By : Ashutosh Maheshwari
'''
import pygame.camera
import pygame.image
import time
pygame.camera.init()
cam = pygame.camera.Camera(pygame.camera.list_cameras()[0])
print("SELF TIMER\nEnter the time duration in seconds: ");
num = int(input())
cam.start()
while num > 0:
if num <= 3:
print(str(num)+" seconds left\n")
if num==1:
print("Say CHEESE\n")
time.sleep(1)
num -= 1
time.sleep(3)
img = cam.get_image()
pygame.image.save(img, "self_timer.jpg")
pygame.camera.quit()
|
# _*_ coding: utf8 _*_
import random
# Creamos una funcion llamada contenido(nombre)
# que recibe el nombre del archivo que vamos a abrir
def contenido(nombre):
# Abrimos el archivo en modo lectura
f = open(nombre, "r")
# Leemos el contenido del archivo
# y lo guardamos en la variable `texto`
texto = f.read()
# Cerramos el archivo
f.close()
# Regresamos el contenido del
# archivo guardado en la variable `texto`
return texto
# Creamos la funcion llamada colocar(nombre, texto)
# que inserte el contenido de la variable `texto`
# en el archivo con el nombre dado
def colocar(nombre, texto):
# Abrir el archivo en modo escritura
f = open(nombre, "w")
# Colocar el contenido de la variable `texto`
# en archivo
f.write(texto)
# Cerrar el archivo
f.close()
# Creamos la funcion llamada contenido_falso(nombre, n)
# y genera n numeros aleatorios y los coloca
# dentro del archivo
def contenido_falso(nombre, n):
# Abrir el archivo
f = open(nombre, "w")
# Repetir `n` veces:
for i in range(n):
# Genera un numero aleatorio
x = random.randint(0, 9)
# Guardalo en archivo
f.write("%d\n" % x)
# Cerrar el archivo
f.close()
# github.com/badillosoft/python-scib |
import sqlite3
import sys
#sqlite3.connect(dbName) will create the db if not exists
# http://www.pythondoc.com/flask-sqlalchemy/index.html
dbName = "app_service.db"
class BaseTable:
def __init__(self,table_name):
self.table_name = table_name
pass
def create_table(self,**field_kw):
sql = "create %s if not exists " % self.table_name
class Table_user:
table_name = 'user_table'
def __init__(self):
self.create_table()
def insert_user(self,user_name,password):
sql = 'insert into %s(username,password) values (?,?)' % self.table_name
conn = sqlite3.connect(dbName)
cursor = conn.cursor()
cursor.execute(sql,(user_name,password))
print(sql+" %s %s "% (user_name,password))
result = cursor.rowcount
cursor.close()
conn.commit()
conn.close()
if result > 0:
return True
else:
return False
def create_table(self):
sql = "create table if not exists %s(id integer primary key autoincrement,username string not null, password string not null)"% self.table_name
conn = sqlite3.connect(dbName)
cursor = conn.cursor()
cursor.execute(sql)
print(sql)
cursor.close()
conn.commit()
conn.close()
def select_user(self,username,password):
sql = "select * from %s where username = ? and password = ?" %self.table_name
conn = sqlite3.connect(dbName)
cursor = conn.cursor()
cursor.execute(sql, (username,password))
print(sql+(" %s %s "% (username,password)))
result = cursor.fetchall()
print(result)
cursor.close()
conn.commit()
conn.close()
return result
def selectAll(self):
sql = "select * from %s " %self.table_name
conn = sqlite3.connect(dbName)
cursor = conn.cursor()
cursor.execute(sql)
print(sql)
result = cursor.fetchall()
print(result)
cursor.close()
conn.commit()
conn.close()
return self.resultToUserList(result)
def resultToUserList(self,result):
user_list = []
for usertuple in result:
user = Table_user()
user.id = usertuple[0]
user.username = usertuple[1]
user.password = usertuple[2]
user_list.append(user)
return user_list
def __repr__(self):
return "id: %s name: %s password: %s" % (self.id,self.username,self.password)
@staticmethod
def selectAllNews():
pass
#命令行
if __name__ == '__main__':
user = Table_user()
user.select_user('ofx','password') |
class Car:
car="tayota"
def __init__(self,made,register,color,module):
self.made=made
self.register=register
self.color=color
self.module=module
def doings(self):
return f"This car is made in {self.made} year of {self.register} is {self.color} have nice {self.module}" |
#Shifa Mehreen
#121910313005
#Addition of sparse matrix
#input
def input_matrix():
#size of matrix
r= int(input("Enter the number of rows: "))
c = int(input("Enter the number of columns: "))
matrix = []
#taking in elements
print("Enter elements: ")
for i in range(r):
a =[]
for j in range(c):
k = int(input())
a.append(k)
matrix.append(a)
return matrix
#printing elements
def display_matrix(matrix):
for i in matrix:
for j in i:
print(j, end=" ")
print()
#SparseMatrix
def sparseMatrix(matrix):
sparsematrix = [] #declare empty list
#looping
#and checking for non-zero elements
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0:
temp=[] #temporary list
temp.append(i) #adding row index
temp.append(j) # adding column index
temp.append(matrix[i][j]) #value of tht non-zero element
#appending temp to sparsematrix
sparsematrix.append(temp)
return sparsematrix
#input matrix1
x= input_matrix()
print("Given Matrix 1: ")
display_matrix(x)
#conversion1
print("SparseMatrix 1: ")
x1 = sparseMatrix(x)
display_matrix(x1)
#input matrix2
y= input_matrix()
print("Given Matrix 2: ")
display_matrix(y)
#conversion2
print("SparseMatrix 2: ")
y1 = sparseMatrix(y)
display_matrix(y1)
#addition of given matrix
def add_matrices(a,b):
#add
if len(a) != len(b):
print("Addition not possible! Enter matrices with same lengths!!")
else:
sum = []
for i in range(len(a)):
tempo = []
for j in range(len(a)):
tempo.append(a[i][j] + b[i][j])
sum.append(tempo)
#print
print("Addition of matrix 1 and 2: ")
display_matrix(sum)
add_matrices(x,y)
#addition of sparse matrices
def sparse_add(a1,b1):
r = []
l1 = len(a1)
l2 = len(b1)
if l1==0 : r = b1
if l2==0 : r = a1
i = 0
j = 0
while l1>0 and l2>0:
if a1[i][0]==b1[j][0] and a1[i][1]==b1[j][1]:
r.append([a1[i][0],a1[i][1],a1[i][2]+b1[j][2]])
i += 1
j += 1
else:
m = min(a1[i],b1[j])
r.append(m)
if m==a1[i]:
i += 1
else:
j += 1
if i>=l1:
for x in range(j,l2):
r.append(b1[x])
break
if j>=l2:
for x in range(i,l1):
r.append(a1[x])
break
#print
print("Sparse Matrix Addition of matrix 1 and 2: ")
display_matrix(r)
sparse_add(x1,y1)
|
#uma maheshwar
#121910313061
#Binary search with user defined function and dynamic inputs
#with recurssion
#dynamic inputs
def array_input():
n = int(input("Enter no'of elements: "))
print("Enter elements: ")
a = []
for i in range(0,n):
k = int(input())
a.append(k)
return a
# recursive function
def binarysearch_array(a,low,high,search):
if high >= low:
mid = (high+low)//2
a.sort()
if a[mid]==search:
return mid
elif a[mid]>search:
return binarysearch_array(a,low,mid-1,search)
else:
return binarysearch_array(a,mid+1,high,search)
else:
return -1
#function calling
arr = array_input()
print("Array is: ", arr)
arr.sort()
print("Sorted Array: ",arr)
#search element
x = int(input("Enter search element: "))
result=binarysearch_array(arr,0,len(arr)-1,x)
if result==-1:
print("element not found")
else:
print("Element",x,"found at",result,"index") |
#uma maheshwar
#121910313061
#Binary search with test cases
#function
def binarysearch_array(a,x):
print("Array is: ",a)
a.sort()
print("Sorted array is: ",a)
#taking ranges
f = 0
loc =0
low = 0
high = len(a) - 1
mid = (low+high)//2
#checking with mid value
if a[mid] == x:
loc = mid
f = 1
#checking with elements lesser than the mid value
elif x < a[mid]:
for i in range(low,mid):
if a[i] == x:
loc = i
f = 1
break
#checking with elements greater than the mid value
elif x > a[mid]:
for i in range(mid,high+1):
if a[i] == x:
loc = i
f = 1
break
#output
#if found
if f == 1:
print("Element",x,"is found at index",loc)
#if not found
else:
print("Element not found!!")
#test cases
#1
print("TestCase1: ")
a1 = [1,2,4,6,8,10,12,14,16,20] #sorted list
x1 = 2
#function calling
binarysearch_array(a1,x1)
#2
print("TestCase2: ")
a2 = [2,5,25,11,6,8,19,55,15] #unsorted list
x2 = 8
#function calling
binarysearch_array(a2,x2)
#3
print("TestCase3: ")
a3 = [3,6,7,5,7,9,10,4,2,13,16,3,2,9,5] #repeated elements list
x3 = 5
#function calling
binarysearch_array(a3,x3)
#4
print("TestCase4: ")
a3 = [2,5,7,9,10,11,6,9,3,1,2,88] #list
x3 = 4 #element that's not present in the list
#function calling
binarysearch_array(a3,x3) |
#uma maheshwar
#121910313061
#Concatenating arrays
def array_input():
#length of array
n = int(input("Enter length of an array: "))
a=[] #declaring empty array
#taking input from user for elements
print("Enter elements: ")
for i in range(0,n):
k = int(input())
a.append(k) #adding elements
return a
#array1
a1 = array_input()
#array2
a2 = array_input()
#printing array
print("Array1: ",a1)
print("Array2: ",a2)
#adding elements into array3
a3 = a1+a2
#Sorting the new array: a3
for l in range(0,len(a3)):
for m in range(l+1,len(a3)):
#checking
if a3[l] > a3[m]:
#swapping
temp = a3[l]
a3[l] = a3[m]
a3[m] = temp
#output
print("New Array is: ",a3)
|
#виведіть на екран транспоновану матрицю 3*3 (початкова матриця задана користувачем).
import numpy
#аналогічно створюємо масив з нулів, типу цілих чисел
c=numpy.zeros((3,3),dtype=numpy.int_)
for d in range(3):
for e in range(3):
# міняємо містями e i d , і тоді матриця залишается такою ж, а ітерація йде вертикально
c[e,d]=int(input('A['+str(d)+','+str(e)+']='))
print(c) |
def maxsubArray(arr,size):
max_so_far=0
max_ending_here=0
for i in range(0,size):
max_ending_here+=arr[i]
if(max_ending_here<0):
max_ending_here=0
elif(max_so_far<max_ending_here):
max_so_far=max_ending_here
return max_so_far
arr=[2,3,-1,-9,0]
size=len(arr)
res=maxsubArray(arr,size)
print(res) |
phone=(input("Enter number: "))
mapping={"1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine"}
output=""
for ch in phone:
output+=mapping.get(ch)+" "
print(output)
|
import random
guessesTaken=0
print("Hello, What is your name?")
name=input()
number=random.randint(1,20)
print("Well,"+name+",I'm thinking of a number between 1 to 20")
while guessesTaken<6:
print('Take a guess')
guess=input()
guess=int(guess)
guessesTaken+=1
if(guess<number):
print('Number guess is too low')
if(guess>number):
print("Number guess is too high")
if(guess==number):
break
if(guess==number):
guessesTaken = str(guessesTaken)
print('Good job, ' + name + '! You guessed my number in ' + guessesTaken + ' guesses!')
if(guess!=number):
number = str(number)
print('Nope. The number I was thinking of was ' + number)
|
from itertools import permutations
def AnagramSearch(a,s,d):
e=len(d)
for i in range(len(s)):
l=[]
st=s[i:i+e]
c=permutations(st)
for j in c:
l.append(''.join(j))
print(l)
for k in l:
if k==d:
return "Yes"
return -1
a=input().split(" ")
s=a[0]
d=a[1]
print(AnagramSearch(a,s,d)) |
numbers=[]
x=int(input("Enter number of elements in list"))
for i in range(x):
numbers.append(int(input()))
findNum=int(input("The number to be deleted is "))
i=0
for element in numbers:
if(element == findNum):
numbers.pop(i)
x=x-1
i=i-1
i=i+1
print(numbers) |
n=int(input())
temp=n
t=0
while n>0:
c=n%10
# print(c)
t=t*10+c
print(t)
n=n//10
# print(n)
if temp==t:
print("True")
else:
print("False") |
def uncommon(s1,s2):
sr1=s1.split(" ")
sr2=s2.split(" ")
uncommon=""
for i in sr1:
if i not in sr2:
uncommon=uncommon+" "+i
return uncommon
s1=input("Enter string1:")
s2=input("Enter string2:")
result=uncommon(s1,s2)
print(result) |
def flip_case(str, letter):
"""given a string and a letter, if the string contains any letter in them, swap the letter case"""
result = ""
for s in str:
if s == letter or s == letter.swapcase():
s = s.swapcase()
result += s
return result |
def multiple_letter_count(str):
count = {}
for letter in str:
count[letter] = count.get(letter, 0) + 1
return count |
#! /usr/bin/env python
import sys
str = "Hello World"
print str
print str[0]
print str[2:7]
print str[2:]
print sys.argv
list = ['first',1,'second',2]
tinylist = [3,'ff']
print list+tinylist
dict = {}
dict['one'] = "this is one"
dict[2] = "this is two"
tinylist = {'name':'jhon','phone':'15690018743','dept':'3.3'}
print dict['one']
print dict[2]
print tinylist
print tinylist.keys()
print tinylist.values()
exit(0)
|
word = raw_input().split(',')
#print " ".join(set(word))
print word
l = []
[l.append(i) for i in word if i not in l]
print " ".join(l)
|
#words = raw_input("Enter the words : ").split(',')
'''
for i in words:
words.sort()
print words
'''
words = [x for x in raw_input("Enter the words : ").split(',')]
words.sort()
print words
~
|
from tkinter import *
from PIL import ImageTk, Image
from tkinter import messagebox
root = Tk()
root.title('Message')
# showinfo, showwarning, showerror, askquestion, askokcancel, askyesno
def popup():
response = messagebox.askyesno("This is my Popup!", "Hello World!")
# Label(root, text=response).pack()
if response == 1:
Label(root, text="You Clicked Yes!").pack()
else:
Label(root, text="You Clicked No!").pack()
Button(root, text='Popup', command=popup).pack()
mainloop() |
# 共用变量问题————资源竞争
import threading
def h1():
global xx
for _ in range(0, 1000000):
xx += 1
def do1():
li = []
for _ in range(10):
t = threading.Thread(target=h1)
li.append(t)
for x in li:
x.start()
for x in li:
x.join()
# 理论值 10,000,000 实际 3,500,000左右
# 同一个瞬间 x 被多个线程同时调用造成了误差
def h2():
global yy
global mylock
for _ in range(0, 1000000):
mylock.acquire()
yy += 1
mylock.release()
# 同步:同时间只能做一件事,效率低但安全
# 异步:同时间分别做不同的事,效率高但不安全
# 添加一个锁,使得 调用y成为同步过程,即y在同一时间只能被一个线程访问,防止原来问题发生
# 别忘了解锁
def do2():
li = []
for _ in range(10):
t = threading.Thread(target=h2)
li.append(t)
for x in li:
x.start()
for x in li:
x.join()
if __name__ == '__main__':
xx = 0
do1()
print(xx)
print('-' * 40)
mylock = threading.Lock()
yy = 0
do2()
print(yy)
|
# 进程池
import multiprocessing
import time
def do(x):
a=0
for x in range(0,x+1):
a+=x
print(a)
if __name__ == '__main__':
pool=multiprocessing.Pool(32)
# 异步
good1=time.time()
for x in range(1000):
pool.apply_async(func=do,args=(x,))
good2=time.time()
# 同步
bad1=time.time()
for x in range(1000):
pool.apply(func=do,args=(x,))
bad2=time.time()
print('good: ',good2-good1)
print('bad: ',bad2-bad1) |
'''
统计一下你写过多少行代码。包括空行和注释,但是要分别列出来
python 代码中的注释块怎么获取没有想到更好的办法,有待优化
'''
import os
import re
code_lines = 0
empty_lines = 0
notes_lines = 0
file_path = "E:\\file\\workbook\\example.py"
is_notes = 0
with open(file_path, encoding='UTF-8') as f:
for line in f.readlines():
if not len(line) or re.match(r'\s+$', line):
empty_lines += 1
elif line.startswith('#'):
notes_lines += 1
elif line.startswith("'''") and is_notes == 0:
notes_lines += 1
is_notes = 1
elif line.startswith("'''") and is_notes != 0:
notes_lines += 1
is_notes = 0
elif is_notes != 0:
notes_lines += 1
else:
code_lines += 1
print("文件是:{0}".format(os.path.basename(file_path)))
print("代码行数是:{0}".format(code_lines))
print("注释行数是:{0}".format(notes_lines))
print("空白行数是:{0}".format(empty_lines))
|
import tkinter as tk
state = [[0 for i in range(3)] for j in range(3)]
window = tk.Tk()
canvas = tk.Canvas(window,width = 400,height = 400,bg = "white")
canvas.create_line(0,133.33,400,133.33)
canvas.create_line(0,266.66,400,266.66)
canvas.create_line(133.33,0,133.33,400)
canvas.create_line(266.66,0,266.66,400)
button = [[0 for i in range(3)] for j in range(3)]
c = 0
def check_state(state):
if (state[0][0]==state[0][1] and state[0][1] == state[0][2] and state[0][2]=="x" or
state[1][0]==state[1][1] and state[1][1] == state[1][2] and state[1][2]=="x" or
state[2][0] == state[2][1] and state[2][1] == state[2][2] and state[2][2]=="x" or
state[0][0] == state[1][0] and state[1][0] == state[2][0] and state[2][0]=="x" or
state[0][1] == state[1][1] and state[1][1] == state[2][1] and state[2][1]=="x" or
state[0][2] == state[1][2] and state[1][2] == state[2][2] and state[2][2] =="x" or
state[0][0] == state[1][1] and state[1][1] == state[2][2] and state[2][2] == "x" or
state[0][2] == state[1][1] and state[1][1] == state[2][0] and state[2][0] == "x" ):
canvas.create_text(200,200,text = "Player1 has won")
window.after(5000,window.destroy)
elif (state[0][0]==state[0][1] and state[0][1] == state[0][2] and state[0][2]=="o" or
state[1][0]==state[1][1] and state[1][1] == state[1][2] and state[1][2]=="o" or
state[2][0] == state[2][1] and state[2][1] == state[2][2] and state[2][2]=="o" or
state[0][0] == state[1][0] and state[1][0] == state[2][0] and state[2][0]=="o" or
state[0][1] == state[1][1] and state[1][1] == state[2][1] and state[2][1]=="o" or
state[0][2] == state[1][2] and state[1][2] == state[2][2] and state[2][2] =="o" or
state[0][0] == state[1][1] and state[1][1] == state[2][2] and state[2][2] == "o" or
state[0][2] == state[1][1] and state[1][1] == state[2][0] and state[2][0] == "o" ):
canvas.create_text(200,200,text = "Player2 has won")
window.after(5000,window.destroy)
for turn in range(1):
def X_turn(x,y):
canvas.create_rectangle(133.3*x,133.33*y,133.33*(x+1),133.33*(y+1),fill = "white")
canvas.create_line(133.3*x+15,133.33*y+15,133.33*(x+1)-15,133.33*(y+1)-15)
canvas.create_line(133.33*(x+1)-15,133.33*y+15,133.33*x+15,133.33*(y+1)-15)
x = int(x)
y = int(y)
print (x,y)
state[x][y] = "x"
check_state(state)
def O_turn(x,y):
canvas.create_rectangle(133.3 * x, 133.33 * y, 133.33 * (x + 1), 133.33 * (y + 1), fill="white")
canvas.create_oval(133.33*x+15,133.33*y+15,133.33*(x+1)-15,133.33*(y+1)-15)
x = int(x)
y = int(y)
state[x][y] = "o"
check_state(state)
for i in range(3):
for j in range(3):
button[i][j] = canvas.create_oval(133.33*i+30,133.33*j+30,133.33*(i+1)-30, 133.33*(j+1)-30,fill = "orange")
for i in range(3):
for j in range(3):
def clicked(event):
global c
x = event.x
y = event.y
x = x//133.33
y = y//133.33
c +=1
if c%2 == 1:
X_turn(x,y)
else:
O_turn(x,y)
canvas.tag_bind(button[i][j], "<Button-1>", clicked)
canvas.pack()
window.mainloop()
|
'''
Created on Nov 2, 2017
Description: Creates a mandlebrot set based on complex numbers
@author: Adam Undus
'''
from cs5png import PNGImage
def update(c,n):
""" updates the sum of the complex values c"""
z = 0
ct = 0
while ct < n:
z = z ** 2 + c
ct += 1
return z
def inMSet(c,n):
""" checks if the complex number c is in the set"""
ct = 0
z = 0
while ct < n:
if abs(z) > 2:
return False
z = z ** 2 + c
ct += 1
return True
def scale(pix, pixMax, floatMin, floatMax):
''' scale takes in pix, the CURRENT pixel column (or row) pixMax, the total # of pixel columns
floatMin, the min floating-point value floatMax, the max floating-point value scale returns the floating-point value thatcorresponds to pi'''
mult = pix/pixMax
diff = (floatMax - floatMin)/floatMax
return diff * mult + floatMin
def mset():
""" creates a 300x200 image of the Mandelbrot set"""
width = 300
height = 200
image = PNGImage(width, height)
for col in range(width):
for row in range(height):
#create the complex number, c!
x = scale(col, width, -2.0, 1.0)
y = scale(row, height, -1.0, 1.0)
c = x + y*1j
if inMSet( c, 25 ) == True:
image.plotPoint(col, row)
image.saveFile()
mset()
|
##############################################################################
#
# Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
from Sync import Synchronized
import thread
from random import random
from time import sleep
class P(Synchronized):
def __init__(self,*args,**kw):
self.count=0
def inc(self):
c = self.count
if random() > 0.7:
sleep(1)
self.count = self.count + 1
return c, self.count
def incn(self,n):
c = self.count
for i in range(n):
self.inc()
return c, self.count
p = P(1, 2, spam=3)
def test():
for i in range(8):
n = 3
old, new = p.incn(n)
if old + n != new:
print 'oops'
sleep(2)
thread_finished()
def thread_finished(lock=thread.allocate_lock()):
global num_threads
lock.acquire()
num_threads = num_threads - 1
lock.release()
num_threads = 8
for i in range(num_threads):
thread.start_new_thread(test, ())
while num_threads > 0:
sleep(1)
|
""" flat """
def flat(string):
""" flat """
txt = ""
for i in string:
if i.isnumeric() or i == "-":
txt += i
else:
txt += " "
#print(txt)
ans = ""
num = []
for j in txt:
if not j.isspace():
ans += j
else:
num.append(ans)
ans = ""
check = [int(i) for i in num if not i == ""]
print(sorted(check, key=float, reverse=1))
flat(input())
|
""" shortten """
def shortten(num):
""" shortten """
first = num
r_first = num
count = 0
ans = ""
while num != -1:
if count == 0:
first = num
count += 1
elif r_first+1 == num:
count += 1
r_first = num
elif r_first+1 != num:
if count > 1:
ans += str(first)+"-"+str(r_first)+", "
elif count == 1:
ans += str(r_first)+", "
count = 1
r_first = num
first = r_first
num = int(input())
if count > 1:
ans += str(first)+"-"+str(r_first)
elif count == 1:
ans += str(r_first)
print(ans)
shortten(int(input()))
|
""" missing card """
def missing_card():
""" missing card """
card = "3S QH 6C JH 2H JD 5D 9D AS 9H 6D 2S 10H JC AH 8S KS 3C\
AD KH AC 9C 7C 5H QS 5C JS 10D 10C 8D 5S QC 3D KC\
2D QD 10S 3H 7H 4H 8H 7S 7D 4D 6H 9S 8C 6S 4C 4S 2C KD".split()
lst = []
for _ in range(51):
lst.append(input())
ans = set(card).difference(set(lst))
print(*ans)
missing_card()
|
""" diamond """
def diamond(num):
""" diamond """
for i in range(num):
if i == 0 or i == num-1:
space = " "*((num-1)//2)
print(space+"*"+space)
elif ((num-1)//2) > i > 0:
space = " "*((num-1)//2-i)
n_space = " "*(2*i-1)
print(space+"*"+n_space+"*"+space)
elif i == ((num-1)//2):
print("*"*num)
elif i > ((num-1)//2):
space = " "*(i-((num-1)//2))
check = i-(i-((num-1)//2))*2
n_space = " "*(check*2-1)
print(space+"*"+n_space+"*"+space)
diamond(int(input()))
|
""" main """
def main(num):
""" main """
if num > 1:
main(num//2)
print(num%2, end="")
main(int(input()))
|
""" multiply """
def multiply_matrix():
""" multiply matrix """
row, col, row2 = int(input()), int(input()), int(input())
lst = []
lst2 = []
last = [[0 for i in range(row2)] for i in range(row)]
for _ in range(row):
ans = []
for _ in range(col):
ans.append(int(input()))
lst.append(ans)
for _ in range(col):
ans = []
for _ in range(row2):
ans.append(int(input()))
lst2.append(ans)
for i in range(len(lst)):
for j in range(len(lst2[0])):
for k in range(len(lst2)):
last[i][j] += lst[i][k]*lst2[k][j]
_ = [print(*i, sep=" ") for i in last]
multiply_matrix()
|
""" euclid dis """
def euclid_recur(lst, lst2):
""" calculate """
ans = ((lst[0]-lst2[0])**2+(lst[1]-lst2[1])**2)**0.5
return ans
def main():
""" main """
plus = 0
num = int(input())
lst = []
for _ in range(num):
lst.append([int(i) for i in input().split()])
for i in range(len(lst)-1):
plus += euclid_recur(lst[i], lst[i+1])
print("%.2f" %plus)
main()
|
""" ink """
def ink():
""" ink """
import math
txt = input().split()
for _ in range(int(txt[1])):
point = input().split()
rdis = ((int(point[0])-0)**2+(int(point[1])-0)**2)**(1/2)
area = 3.1416*(rdis**2)
print(math.ceil(area/int(txt[0])))
ink()
|
""" kayak """
def kayak(num):
""" kayak """
people = input().split(" ")
people_n = []
num = 0
for i in people:
people_n.append(int(i))
people_n.sort()
#print(people_n)
while len(people_n) != 2:
lst = []
people_n.sort()
for i in range(1, len(people_n)):
lst.append(people_n[i]-people_n[(i-1)])
inds = lst.index(min(lst))
num += min(lst)
#print(lst)
for j in range(len(people_n)):
if people_n[j] == people_n[inds] or people_n[j] == people_n[inds+1]:
people_n[j] = ""
people_n.remove("")
people_n.remove("")
if len(people_n) == 2:
break
#print(people_n)
print(num)
kayak(int(input()))
|
""" gcd N """
def gcdv_1(a_num, b_num):
""" gcd """
if b_num == 0:
return a_num
else:
return gcdv_1(b_num, a_num%b_num)
def main():
""" main """
reg = int(input())
lst = [int(input()) for i in range(reg)]
if len(lst) == 1:
print(lst[0])
else:
gcd = gcdv_1(lst[0], lst[1])
for i in range(2, len(lst)):
gcd = gcdv_1(gcd, lst[i])
print(gcd)
main()
|
def my_sort(a):
for i in range(1, len(a)):
while i > 0 and a[i] < a[i - 1]:
temp = a[i - 1]
a[i - 1] = a[i]
a[i] = temp
i = i - 1
return a
a = [5, 6, 3, 10, 78, 1, 49]
# a.sort()
print my_sort(a)
|
def search(arr, n, key):
# Travers the given array starting
# from leftmost element
i = 0
while (i < n):
# If key is found at index i
if (arr[i] == key):
return i
# Jump the difference between
# current array element and key
i = i + abs(arr[i] - key)
print("key not found!")
return -1
# test
arr = [8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 ]
n = len(arr)
key = 3
print("Found at index ", search(arr,n,key)) |
def subArraySum(arr, n, Sum):
d = {}
curr_sum = 0
for i in range(0,n):
curr_sum = curr_sum + arr[i]
if curr_sum == Sum:
print("Sum found between indexes 0 to", i)
return
if (curr_sum - Sum) in d:
print("Sum found between indexes",
d[curr_sum - Sum] + 1, "to", i)
return
d[curr_sum] = i
print("No subarray with given sum exists")
arr = [10, 2, -2, -20, 10]
n = len(arr)
sum = -10
subArraySum(arr, n, sum)
1, 4, 20, 3, 10, 5
arr = [1, 4, 20, 3, 10, 5]
n = len(arr)
sum = 33
subArraySum(arr, n, sum) |
def strStr(s, x):
if not x:
return 0
for i in range(len(s) - len(x) + 1):
if s[i] == x[0]:
j = 1
while j < len(x) and s[i+j] == x[j]:
j += 1
if j == len(x):
return i
return -1
s = 'wednesday'
x = 'day'
print(strStr(s,x))
|
var1=int(input("Enter the first vlaue:"))
var2=int(input("enter the second value"))
var3=int(input("enter the third value"))
if var1>var2 and var1>var3 :
print("Var1 is greater ")
elif var2>var3 :
print("var2 is greater")
else:
print("var3 is greater")
|
def yazitura():
import random
secim=input("Yazı mı 'y', Tura mı 't'?: ")
zeka=random.randint(0,1)
if zeka==0:
print("Yazı...")
else:
print("Tura...")
if secim=="y" and zeka==0:
print("Kazandınız...")
elif secim=="t" and zeka==1:
print("Kazandınız...")
else:
print("Kaybettiniz...")
tekrar="1"
while tekrar=="1":
yazitura()
tekrar=input("Tekrar Denemek İçin 1, Çıkış İçin Enter Tuşlayın: ") |
def indirimhesap(urun,indirim):
ind=indirim/100
hesap=urun*ind
sonuc=urun-hesap
return sonuc
urun=eval(input("Lütfen Ürün Fiyatını Giriniz: "))
indirim=eval(input("Lütfen İndirim Oranını Giriniz: "))
s=indirimhesap(urun,indirim)
print("İndirimli Fiyat:",s) |
p = 0
def search(lst, n):
l = 0
u = len(lst) - 1
while l <= u:
mid = (l + u)//2
if lst[mid] == n:
globals()['p'] = mid
return True
else:
if lst[mid] < n:
l = mid + 1
else:
u = mid - 1
return False
lst = [4, 5, 6, 7, 8, 9]
n = 5
if search(lst, n):
print(f"Found at {p + 1}")
else:
print("not found") |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : replace_words.py
@Author : Siwen
@Time : 3/5/2020 5:58 PM
"""
"""
648. Replace Words
In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
Example 1:
Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Note:
The input will only have lower-case letters.
1 <= dict words number <= 1000
1 <= sentence words number <= 1000
1 <= root length <= 100
1 <= sentence words length <= 1000
"""
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.is_word = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur = self.root
for c in word:
cur = cur.children[c]
cur.is_word = True
def searchPrefix(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
prefix = ''
cur = self.root
for c in word:
if cur.is_word:
return prefix
if c not in cur.children:
return word
prefix += c
cur = cur.children[c]
return word
class Solution:
def replaceWords(self, dict: List[str], sentence: str) -> str:
tire = Trie()
for word in dict:
tire.insert(word)
words_list = sentence.split(" ")
for i in range(len(words_list)):
words_list[i] = tire.searchPrefix(words_list[i])
return " ".join(words_list) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
answer = []
if not root:
return answer
stacknode = []
node = root
while node != None:
stacknode.append(node)
node = node.left
while stacknode:
a = stacknode.pop()
answer.append(a.val)
a = a.right
while a != None:
stacknode.append(a)
a = a.left
return answer |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : add_and_search_word_data_structure_design.py
@Author : Siwen
@Time : 3/5/2020 6:32 PM
"""
"""
211. Add and Search Word - Data structure design
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
"""
"""
method 1: Tire
"""
from collections import defaultdict
class TireNode:
def __init__(self):
self.children = defaultdict(TireNode)
self.is_word = False
class WordDictionary:
def __init__(self):
self.root = TireNode()
def addWord(self, word: str) -> None:
cur = self.root
for c in word:
cur = cur.children[c]
cur.is_word = True
def search(self, word: str) -> bool:
trienode_l = [self.root]
for c in word:
temp_l = []
for node in trienode_l:
if c == ".":
for char, newnode in node.children.items():
temp_l.append(newnode)
if c in node.children:
temp_l.append(node.children[c])
if not temp_l:
return False
trienode_l = temp_l
for node in trienode_l:
if node.is_word:
return True
return False
"""
method 2: save length to word dictionary
because only search exact word, prefix not useful
"""
from collections import defaultdict
class WordDictionary:
def __init__(self):
self.vocab = defaultdict(set)
def addWord(self, word: str) -> None:
self.vocab[len(word)].add(word)
def search(self, word: str) -> bool:
if '.' not in word:
return word in self.vocab[len(word)]
pool = self.vocab[len(word)]
for i, ch in enumerate(word):
if ch != '.':
pool = {wrd for wrd in pool if wrd[i] == ch}
if not pool:
return False
return True
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
|
"""
<file_name>.py
--------------
Graph distance based on <link to paper, or website, or repository>.
author: <your name here>
email: <name at server dot com> (optional)
Submitted as part of the 2019 NetSI Collabathon.
"""
from .base import BaseDistance
class <AlgorithmName>(BaseDistance):
def dist(self, G1, G2):
"""A brief one-line description of the algorithm goes here.
A short paragraph may follow. The paragraph may include $latex$ by
enclosing it in dollar signs $\textbf{like this}$.
Params
------
G1, G2 (nx.Graph): two networkx graphs to be compared.
Returns
-------
dist (float): the distance between G1 and G2.
"""
# A note on input validation: You should _only_ validate input params
# that are (1) specific to the method you are computing and (2) can
# cause errors in the execution of the method. For example, you do not
# need to validate that G1 is a networkx graph. However, if your method
# requires that G1 and G2 are the same size, you should add the
# following validation (and if you aren't sure, ask!):
# if G1.number_of_nodes() != G2.number_of_nodes():
# raise ValueError('G1 and G2 must have same number of nodes')
# Your code goes here!
# Your code goes here!
# Your code goes here!
# Make sure to always save the final distance value inside the
# self.results dict as follows:
self.results['dist'] = dist
# If there are other important quantities that may be of value to
# the user, you can (and should) also store them in the
# self.results dict. For example, if the adjacency matrix of
# the graphs G1 and G2 was computed, we may do something like the
# following:
# self.results['adj1'] = first_adjacency_matrix
# self.results['adj2'] = second_adjacency_matrix
# The last line MUST be the following. Please make sure that you
# are only returning one numerical value, the distance between G1
# and G2. All other values that may be of importance should be
# stored in self.results instead.
return dist
### Auxiliary functions go here!
### Auxiliary functions go here!
### Auxiliary functions go here!
# def auxiliary_function1(param1, param2):
# """Brief description.
#
# Params
# ------
#
# param1 (type): description.
#
# param2 (type): description.
#
# Returns
# -------
#
# some_value (type) with description.
#
# """
# pass
|
def cubeVolume(l):
# return sideLength^3
if type(l) is int or type(l) is float:
return l * l * l
return TypeError
def avgList(li):
# num of items
j = 0
# total of items
t = 0
for i in li:
if(type(i) is not int):
return TypeError
j += 1
t += i
if j == 0:
return None
else:
return t/j
def nameGen(f, l):
if(type(f) is not str or type(l) is not str):
return TypeError
return f + " " + l
|
#!/usr/bin/env python3
# convert-jpg-to-png.py
#
# Quick and dirty script to convert the book's jpeg scans
# into png files, removing the color, and adding transparency.
# This way any background color can be used and still look
# relatively nice on the illustrations.
#
# Image Magick Command Example
#
# magick convert 9037m.jpg -fx intensity -fuzz 15% -transparent white 9037m.png
#
# Helpful links
# https://www.imagemagick.org/discourse-server/viewtopic.php?t=12619
# https://imagemagick.org/script/convert.php
from pathlib import Path
import subprocess
command_str = 'magick convert {0}.jpg -fx intensity -fuzz 15% -transparent white {0}.png'
#command_str = 'ls {0}.jpg'
p = Path('.')
for pf_jpg in list(p.glob('**/*.jpg')):
filename = str(pf_jpg).rstrip('.jpg')
print(command_str.format(filename))
out_bytes = subprocess.check_output(command_str.format(filename), shell=True, stderr=subprocess.STDOUT)
# print(out_bytes.decode('utf-8'))
|
# BinaryNode class
# Modified code from Listings 5.5, 5.6, 5.7, 5.8 & 5.12
class BinaryNode:
# default constructor
# makes an empty node
def __init__(self):
self.key = None
self.left = None
self.right = None
# constructor for nodes
# assigns initial value to key
def __init__(self,rootObj):
self.key = rootObj
self.left = None
self.right = None
# return value of current node
def getRootVal(self):
return self.key
# set value of current node
def setRootVal(self,obj):
self.key = obj
# return root of left subtree of current node
def getLeftChild(self):
return self.left
# insert newNode as left child of current node
def setLeftChild(self,newNode):
self.left = newNode
# return root of right subtree of current node
def getRightChild(self):
return self.right
# insert newNode as right child of current node
def setRightChild(self,newNode):
self.right = newNode
# returns a string from a preorder traversal
def strPreorder(self):
print self.key
if self.left:
self.left.strPreorder()
if self.right:
self.right.strPreorder()
# returns a string from an inorder traversal
def strInorder(self):
if self.left:
self.left.strInorder()
print self.key
if self.right:
self.right.strInorder()
# returns a string from a postorder traversal
def strPostorder(self):
if self.left:
self.left.strPostorder()
if self.right:
self.right.strPostorder()
print self.key
|
# June 17, 2008, San Diego, CA
# This program simulates a factory conveyor system in which all boxes
# are the same, but they arrive with random inter-arrival times. We
# will investigate the number of boxes N(t) that have arived up to and
# including time t.
# The simulation input is the set of critical event times.
# The simulation output is the function N(t) which is the number of
# events up to and including time t.
from visual import *
from random import random, randrange
# Draw the x,y,z axes and labels
x_axis=curve(pos=[(-200,0,0),(200,0,0)],radius=0.03, color=color.yellow)
y_axis=curve(pos=[(0,-50,0),(0,200,0)],radius=0.05, color=color.white)
z_axis=curve(pos=[(0,0,-200),(0,0,200)],radius=0.03, color=color.yellow)
x_label=label(pos=(202,0,0), text='x', box=0, opacity=0)
y_label=label(pos=(0,202,0), text='y', box=0, opacity=0)
#z_label=label(pos=(0,0,202), text='z', box=0, opacity=0)
# The ground floor is 100*100 square units
ground=box(position=(0,0,0),length=400,height=0,width=400, color=(0,10,0))
# The conveyor is 30 units long and 20 units off the ground floor, 10 units wide
conveyor=box(pos=(15,19.9,0),length=30,height=0.2,width=10,color=(0,100,200))
pole_1=box(pos=(5,9.95,0),length=2,height=19.9,width=10,color=(10,0,0))
pole_2=box(pos=(25,9.95,0),length=2,height=19.9,width=10,color=(10,0,0))
# The wharehouse where packages will come out from
# The root position of the supporting poles
F1=(-30,0,30) # southwest foot
F2=(0,0,30) # southeast foot
F3=(0,0,-30) # northeast foot
F4=(-30,0,-30) # northwest foot
# The top position of the supporting poles
T1=(-30,40,30) # southwest top position
T2=(0,40,30) # southeast top position
T3=(0,40,-30) # northeast top position
T4=(-30,40,-30) # northwest top position
# South side wall
Swall=faces(pos=[T2,F1,F2, T1,F1,T2], color=(10,5,0)) # outside of south wall
Swallb=faces(pos=[T2,F2,F1, T2,F1,T1], color=(10,5,5)) # inside of south wall
# North side wall
Nwall=faces(pos=[T3,F3,F4, T3,F4,T4], color=(10,5,0)) # outside of north wall
Nwallb=faces(pos=[T3,F4,F3, T4,F4,T3], color=(10,5,5)) # inside of north wall
# West side wall
Wwall=faces(pos=[T1,F4,F1, T4,F4,T1], color=(10,5,0)) # outside of west wall
Wwallb=faces(pos=[T1,F1,F4, T1,F4,T4], color=(10,5,5)) # inside of west wall
# East side wall where the conveyor is located
# Need 4 more points
F2R=(0,20,10) # this point is located to the right of F2
F2RR=(0,0,5) # this point is located to the right of right of F2
F2RRT=(0,20,5) # this point is located above the right of right of F2
F3L=(0,20,-10) # this point is located to the left of F3
F3LL=(0,0,-5) # this point is located to the left of left of F3
F3LLT=(0,20,-5) # this point is located ABOVE the left of left of F3
T2R=(0,30,10) # this point is located above F2r
T3L=(0,30,-10) # this point is located above F3L
Ewall=faces(pos=[F2RR,F3LL,F3LLT, F3LLT,F2RRT,F2RR, F2R,F2RR,F2RRT, F2RR,F2R,F2, F2,F2R,T2R, T2R,T2,F2, T2,T2R,T3, T2R,T3L,T3,
T3,T3L,F3, F3,T3L,F3L, F3L,F3LL,F3, F3L,F3LLT,F3LL], color=(10,5,0)) # outside of east wall
Ewallb=faces(pos=[F3LL,F2RR,F3LLT, F2RRT,F3LLT,F2RR, F2RR,F2R,F2RRT, F2R,F2RR,F2, F2R,F2,T2R, T2,T2R,F2, T2R,T2,T3, T3L,T2R,T3,
T3L,T3,F3, T3L,F3,F3L, F3LL,F3L,F3, F3LLT,F3L,F3LL], color=(10,5,5)) # inside of east wall
wndwln=curve(pos=[T2R,F2R,F3L,T3L,T2R], radius=0.3, color=(10,0,0)) # window line
p11=curve(pos=[T1,F1], radius=1.5, color=(10,0,10))# poles in the 4 corners
p22=curve(pos=[T2,F2], radius=1.5, color=(10,0,10))
p33=curve(pos=[T3,F3], radius=1.5, color=(10,0,10))
p44=curve(pos=[T4,F4], radius=1.5, color=(10,0,10))
# The roof
# the South side of the roof
M1=(-35,50,0) # middle point on west side
M2=(5,50,0) # middle point on east side
T1x=(-35,40,30) # T1 extra, 5 units to the west of T1
T1xx=(-35,38,40) # T1 extra extra, further south to T1 and lower
T2x=(5,40,30) # T2 extra, 5 units to the east of T2
T2xx=(5,38,40) # T2 extra extra, further south to T2 and lower
Srf=faces(pos=[M1,T1x,T2x, M1,T2x,M2],color=(10,0,10)) #South roof
Srfb=faces(pos=[T1x,M1,T2x, T2x,M1,M2],color=(10,1,10)) #South roof back side
Srfx=faces(pos=[T1xx,T2xx,T1x, T1x,T2xx,T2x],color=(10,0,10)) #South roof edge
Srfxb=faces(pos=[T2xx,T1xx,T1x, T2xx,T1x,T2x],color=(10,1,10)) #S rf edge bk side
# the North side of the roof
T4x=(-35,40,-30) # T4 extra, 5 units to the north of T4
T4xx=(-35,38,-40) # T4 extra extra, further north to T4 and lower
T3x=(5,40,-30) # T3 extra, 5 units to the north of T3
T3xx=(5,38,-40) # T3 extra extra, further north to T3 and lower
Nrf=faces(pos=[M1,M2,T4x, M2,T3x,T4x],color=(10,0,10)) #North roof
Nrfb=faces(pos=[M2,M1,T4x, T3x,M2,T4x],color=(10,1,10)) #North roof back side
Nrfx=faces(pos=[T3xx,T4xx,T3x, T3x,T4xx,T4x],color=(10,0,10)) #North roof edge
Nrfxb=faces(pos=[T4xx,T3xx,T3x, T4xx,T3x,T4x],color=(10,0,10)) #N rf edge bk s
# To build the container at end of the package trip, we need 8 points
ct1=(28,8,10) # container top point position 1
cb1=(28,0.11,10) # container bottom point position 1
ct2=(40,8,10) # container top point position 2
cb2=(40,0.11,10) # container bottom point position 2
ct3=(40,8,-10) # container top point position 3
cb3=(40,0.11,-10) # container bottom point position 3
ct4=(28,8,-10) # container top point position 4
cb4=(28,0.11,-10) # container bottom point position 4
# To build the S.E.N.W walls and base of the container
wallsNbase = faces(pos=[ct1,cb1,cb2, cb2,ct2,ct1, cb2,cb3,ct2, cb3,ct3,ct2, cb3,cb4,ct3,
cb4,ct4,ct3, cb4,cb1,ct1, cb4,ct1,ct4, cb1,cb4,cb2,
cb2,cb4,cb3], color=(1,1,30))
wallsNbasebk = faces(pos=[cb1,ct1,cb2, ct2,cb2,ct1, cb3,cb2,ct2, ct3,cb3,ct2, cb4,cb3,ct3,
ct4,cb4,ct3, cb1,cb4,ct1, ct1,cb4,ct4, cb4,cb1,cb2,
cb4,cb2,cb3], color=(30,30,0))
cln_1 = curve(pos=[ct1,cb1],radius=0.3,color=(10,0,0)) # corner line no. 1
cln_2 = curve(pos=[ct2,cb2],radius=0.3,color=(10,0,0)) # corner line no. 2
cln_3 = curve(pos=[ct3,cb3],radius=0.3,color=(10,0,0)) # corner line no. 3
cln_4 = curve(pos=[ct4,cb4],radius=0.3,color=(10,0,0)) # corner line no. 4
tln = curve(pos=[ct1,ct2,ct3,ct4,ct1],radius=0.2,color=(10,0,0)) # top line
bln = curve(pos=[cb1,cb2,cb3,cb4,cb1],radius=0.2,color=(10,0,0)) # base line
# ....... End Building the Factory Conveyor System with End-Container .......
# Prompt user for total number of events to take place
TotEvntNbr=input("Enter total number of boxex to arrive:\n") # TotEvntNbr=Total Event Nbr
intrArTmList=[] #inter-arrival time(also named inter-event time) list
for i in range(TotEvntNbr):
intrArTmList.append(randrange(1,100))
print "intrArTmList = ",intrArTmList
arvTmLst=[intrArTmList[0]] # arrival time list, also named event time list, initialized
# with the arrival time of the very first event.
# From the second one on, each event arrival time is equal to
# the sum of its precessor's arrival time plus the inter-arrival
# time as shown in the next two statements.
for x in intrArTmList[1:]:
arvTmLst += [arvTmLst[-1]+x]
print "Arrival Time List or Event Time List = arvTmLst = ",arvTmLst # should be an ascending list
#print "Now, Enter a list of critical event times, in ascending order:\n"
crtEvnTmLst=input("Now, Enter a list of critical event times, in ascending order:\n")
nbrEvnUpInclLst = [] # list of numbers N(t)'s of events up to and including t. t is called critical
# event time. length of crtEvnTmLst = length of nbrEvnUpTnclLst.
# that is if crtEvnTmLst = [t1, t2, t3, t4, t5], then
# nbrEvnUpInclLst = [N(t1), N(t2), N(t3), N(t4), N(t5)]
pair=zip(arvTmLst[:-1],arvTmLst[1:])
#print "Debug $$$$$$$ pair = ",pair
for m in crtEvnTmLst:
if m<arvTmLst[0]:
nbrEvnUpInclLst.append(0)
elif arvTmLst[-1] <= m:
nbrEvnUpInclLst.append(len(arvTmLst))
else:
for k in range(len(pair)):
if pair[k][0] <= m <pair[k][1]:
nbrEvnUpInclLst.append(k+1)
print "List of nbr of events up to and including critical time = nbrEvnUpInclLst = ",nbrEvnUpInclLst
#Next we will show the arrival of one box for each entry a in inList
# The longer the inter-event time implies the slower the execution.
# So we use rate(10.0/a) as the inter-event time.
for k in intrArTmList:
rate(10.0/k) # waiting for k seconds. Greater k value implies smaller rate
# which then implies longer waiting time for next box to arrive
# All packages are the same, so we use a box object to display a package
pkg=box(position=(0,22.5,0),length=5,height=5,width=2, color=(100,0,0))
# pkg is being transported On the conveyor
t=0.0
dt=0.1
while t<=32.5:
x= t
y=22.5
z=0
pkg.pos=(x,y,z)
t +=dt
rate(150)
# pkg is descending
t=22.5
dt=0.2
while t>=2.5:
rate(50)
x=32.5
y=t
z=0
pkg.pos=(x,y,z)
t=t-dt
#pkg.visible = 0 # pkg disappearing
|
from random import *
def lol():
loop = 1
cash = 2000
while loop == 1:
x = randrange(0,101)
y = randrange(0,101)
z = randrange(0,101)
bets = raw_input("Bet on either x,y or z: ")
print "Cash:",cash
bet_cash = input("Play your bet: ")
cash = cash - bet_cash
print "Cash:",cash
ready = raw_input("Ready? y/n: ")
if ready == 'y':
if bets == 'x':
if x > y and x > z:
print "You have won!"
cash = cash+(bet_cash*2)
print "You now have",cash,"cash."
else:
print "You have lost"
if bets == 'y':
if y > x and y > z:
print "You have won!"
cash = cash+(bet_cash*2)
print "You now have",cash,"cash."
else:
print "You have lost"
if bets == 'z':
if z > x and z > y:
print "You have won!"
cash = cash+(bet_cash*2)
print "You now have",cash,"cash."
else:
print "You have lost"
if cash <= 0:
print "You have lost all your money!"
break
elif cash >= 10000:
print "You have emptied out all the competitors! Congratulations!"
break
again = raw_input("Continue? y/n: ")
if again == 'n':
print "You have won",cash,"cash."
print "Thanks for playing."
break
|
# This program shows that the return statement can be used to return
# multiple number of values not just one, by using a list.
from visual import *
def compute(x,y): # given two integer values x, y
myList = [ ]
s=x+y
d=x-y
p=x*y
q=x/y #quotient
r=x%y # remainder of division
myList = [s]+[d]+[p]+[q]+[r] # add the 5 singleton lists together
print "Within the compute function, myList = %s\n" % myList
return myList
m=13
n=5
L = compute(m,n)
print "m=%s, n=%s\n" % (m,n)
print "m+n=%3d, m-n=%3d, m*n=%3d\n" % (L[0],L[1],L[2])
print "m/n=%3d, m%sn=%3d\n" % (L[3],'%',L[4])
|
#Shawn Thompson
#CSC 360
#ex 1.1
#List of input voltage
#Corrosponding output voltage
#Vr(t) = Ir2
#Vs(t) = I(r+r2)
#Vr(t)/Vs(t)= Ir2/(I(r+r2)) = r2/(r+r2)
#Vr(t) becomes equation used in line 12
def inOut_1(r,r2):
control = 1
while control == 1:
x = input("Please enter the voltage: ")
z = ((r2)/(r+r2))*x
print "x(t) z(t)"
print x," ", z
qP = raw_input("Enter another value?: ")
if qP == 'N' or qP == 'No' or qP == 'n' or qP == 'no':
break
print "All values processed. Program Ended."
def inOut_2(r,r2):
#xList = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
#zList = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
xList = [0]
zList = [0]
control = input("How many voltage values would you like to calculate?(20 Max): ")
xL_con = -1
zL_con = -1
xadd_line = 0
zadd_line = 0
for i in range(control):
xL_con = xL_con + 1
zL_con = zL_con + 1
x = input("Please enter the voltage: ")
z = ((r2)/(r+r2))*x
xList[xL_con] = x
zList[zL_con] = z
xList += [xadd_line]
zList += [zadd_line]
#print "x(t) z(t)"
#print x," ", z
xList.remove(0)
zList.remove(0)
xnums = -1
znums = -1
for i in range(control):
xnums = xnums + 1
znums = znums + 1
print xList[xnums]," ", zList[znums]
print "All values processed. Program Ended."
#Suppose the input values are given in a data file. "vData.dat"
#ex:
#20 30
#220
#350
#1000
#3350
#1250
#600
#v = infile.readline()
#while v:
#v = string.split(v)
#v = map(float,v)
#v = v[0]
#vr = v*((r2)/(r1+r2)
#outfile.write("%-6.2f %-6.2f "%(v,vr))
#v = infile.readline()
#infile.close
#outfile.close
def inOut_3(control):
import string, os
#The "r" stands for read, the "w" stands for write.
#Be sure to place the .dat and .out file in the same folder as the program.
Outfile = open("vData.out","w") # output file
Outfile.write("Simulation of System of Electrical Resistive Network")
print
Outfile.write("======================================")
print
Infile = open("vData.dat","r") # input file
r_val = Infile.readline() #Reads the entire first line of the file
print "Resistance values:",r_val
sPr = string.split(r_val) #Seperates the two values on line 0, sPr is a list
fPoint_r = map(float,sPr)
r = fPoint_r[0]
r2 = fPoint_r[1]
Outfile.write(" R1 =%6.2f, R2 =%6.2f"%(r,r2))
v_val = Infile.read() #Read all lines in file. May be used to replace readline();single line
sPv = string.split(v_val)
fPoint_v = map(float,sPv)
x = fPoint_v[0]
print "Voltages", sPv
xList = [0]
zList = [0]
fPoint_v = [0]
#control = input("How many voltage values would you like to calculate?(20 Max): ")
xL_con = -1
zL_con = -1
xadd_line = 0
zadd_line = 0
y = -1
for i in range(control):
y = y + 1
#xL_con = xL_con + 1 #Set slot in list to store data
#zL_con = zL_con + 1
#x = input("Please enter the voltage: ")
z = ((r2)/(r + r2))* x
#xList[xL_con] = fPoint_v[y] #Set the value of the slot in list
#zList[zL_con] = z
#xList += [xadd_line] #Add new line to list
#zList += [zadd_line]
#print "x(t) z(t)"
#print x," ", z
#xList.remove(0) #Drop the initial zero placeholder value
#zList.remove(0)
#xnums = -1
#znums = -1
#for i in range(control):
#xnums = xnums + 1
#znums = znums + 1
#print xList[xnums]," ", zList[znums]
print "All values processed. Program Ended."
|
# BTTester program
from BinaryTree import *
# main tester function
def main():
# create an empty binary tree
btree = BinaryTree()
addEmployee(btree)
if btree.root:
print "Preorder\n"
Preorder = btree.root.strPreorder()
print "Inorder\n"
Inorder = btree.root.strInorder()
print "Postorder\n"
Postorder = btree.root.strPostorder()
def addEmployee(btree):
add = raw_input("Add an employee to the tree? >>")
if add == 'yes' or add == 'y':
firstName = raw_input("Please enter first name: ")
lastName = raw_input("Please enter last name: ")
hoursPerWeek = input("Please enter hours per week: ")
payRate = input("Please enter pay rate: ")
employee = Employee(firstName, lastName, hoursPerWeek, payRate)
if btree.isEmpty == True:
btree.setRoot(employee)
print firstName, "set as root."
else:
lrChoice = raw_input("Left or Right child?(l/r): ")
if lrChoice == 'l':
btree.insertLeft(employee)
elif lrChoice == 'r':
btree.insertRight(employee)
|
#defining the function
def cnv(n):
if n > 1:
cnv(n // 2) # floor division: nous permet de prendre juste la resultat sans vergule
print(n % 2, end=' ')
nbr = int(input("Veuillez entrez un nombre decimal: ")) #calling the function
cnv(nbr ) |
# Conrad Ibanez
# Webscraping data from online source
import pandas as pd
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
import requests
# this method is from the textbook
def decode_content(r, encoding):
return (r.content.decode(encoding))
# this method is from the textbook
def encoding_check(r):
return (r.encoding)
# this method is to read in the html file and save the file to disk using the company's symbol in the filename
def readSaveHtml(companyList):
# referenced this webpage for the code to get html and save- https://stackoverflow.com/questions/40529848/how-to-write-the-output-to-html-file-with-python-beautifulsoup
# also read suggestions in course slack channel
#soup = BeautifulSoup(open('1.html'),"html.parser")
#html =soup.contents
for c in companyList:
#url = "https://finance.yahoo.com/quote/" + c
url = "https://finance.yahoo.com/quote/" + c + "/key-statistics"
response = requests.get(url)
contents = decode_content(response,encoding_check(response))
with open("../companyStats/" + c + "-stats.html", "w", encoding="utf-8") as file:
file.write(contents)
# this method is to create the dataframe from processing the html files that were saved to disk; the dataframe is saved as csv file to disk
def createDataFrame(companyList):
#companyList = companyList[0:400]
#companyList = ['AAPL']
# the below company symbols needed to be removed from the list as processing the data would not complete due to errors
# many of these companies may be obsolete or have no data
companyList.remove("AET") #Issue with Data
companyList.remove("APC") #Not Valid
companyList.remove("BHI") #Issue with Data
companyList.remove("BCR") #Issue with Data
companyList.remove("BBT") #Not Valid
companyList.remove("BF.B") #Not Valid
companyList.remove("CA") #Issue with Data
companyList.remove("CBG") #Not Valid
companyList.remove("CELG")
companyList.remove("COH")
companyList.remove("CSRA")
companyList.remove("DPS")
companyList.remove("DNB")
companyList.remove("EVHC")
companyList.remove("ESRX")
companyList.remove("GGP")
companyList.remove("HAR")
companyList.remove("HRS")
companyList.remove("HCP")
companyList.remove("LLL")
companyList.remove("LUK")
companyList.remove("LVLT")
companyList.remove("LLTC")
companyList.remove("MJN")
companyList.remove("KORS")
companyList.remove("MON")
companyList.remove("NFX")
companyList.remove("PX")
companyList.remove("PCLN")
companyList.remove("RHT")
companyList.remove("RAI")
companyList.remove("COL")
companyList.remove("SCG")
companyList.remove("SNI")
companyList.remove("SPLS")
companyList.remove("SYMC")
companyList.remove("TDC")
companyList.remove("TSO")
companyList.remove("TWX")
companyList.remove("TMK")
companyList.remove("TSS")
companyList.remove("VIAB")
companyList.remove("HCN")
companyList.remove("WFM") #Whole foods bought by Amazon
companyList.remove("WYN")
companyList.remove("XL")
companyList.remove("YHOO") #Bought by Verizon
columnNames = ["Symbol","Fiscal_Year_End","Recent_Qtr","Profit_Margin","Operation_Margin","Return_On_Assets","Return_On_Equity","Revenue","Revenue_Per_Share","Gross_Profit","EBITDA","Total_Cash","High_52","Low_52"]
webDf= pd.DataFrame(columns = columnNames)
'''
print(companyList)
for c in companyList:
with open("../companyStats/" + c + "-stats.html", "rb") as fd:
soup = BeautifulSoup(fd)
tables = soup.findAll('table')
print("\nThe total number of tables is: ", len(tables))
fiscalYrEnd = soup.select("td[class*='Fw(500) Ta(end) Pstart(10px) Miw(60px)']")[0].text
#recentQtr = soup.select("td[data-reactid*='310']")[0].text
print(fiscalYrEnd)
#print(recentQtr)
'''
for c in companyList:
with open("../companyStats/" + c + "-stats.html", "rb") as fd:
soup = BeautifulSoup(fd)
tables = soup.findAll('table')
#print("\nThe total number of tables is: ", len(tables))
#print(recentQtr)
# the following code was used to display the table contents
# using the output and also the view-source and inspect element of the web browser to understand the table structures
'''
for i, table in enumerate(tables, start=1):
print("\nTables ", i, "\n", '-'*40, sep='')
print(table)
'''
#print(c,"++++++++++++++++++++++++++++++")
# get the sources from tables[3]
rItems = tables[3].findAll('tr')
tItems0 = rItems[0].findAll('td')
tItems1 = rItems[1].findAll('td')
fiscalYrEnd = tItems0[1].getText().strip()
recentQtr = tItems1[1].getText().strip()
rItems = tables[4].findAll('tr')
tItems0 = rItems[0].findAll('td')
tItems1 = rItems[1].findAll('td')
profitMargin = tItems0[1].getText().strip()
opMargin = tItems1[1].getText().strip()
rItems = tables[5].findAll('tr')
tItems0 = rItems[0].findAll('td')
tItems1 = rItems[1].findAll('td')
returnAssets = tItems0[1].getText().strip()
returnEquity = tItems1[1].getText().strip()
rItems = tables[6].findAll('tr')
tItems0 = rItems[0].findAll('td')
tItems1 = rItems[1].findAll('td')
tItems3 = rItems[3].findAll('td')
tItems4 = rItems[4].findAll('td')
revenue = tItems0[1].getText().strip()
revenuePerShare= tItems1[1].getText().strip()
grossProfit = tItems3[1].getText().strip()
ebitda = tItems4[1].getText().strip()
rItems = tables[7].findAll('tr')
tItems0 = rItems[0].findAll('td')
totalCash = tItems0[1].getText().strip()
rItems = tables[0].findAll('tr')
tItems3 = rItems[3].findAll('td')
tItems4 = rItems[4].findAll('td')
high52 = tItems3[1].getText().strip()
low52 = tItems4[1].getText().strip()
'''
print(fiscalYrEnd)
print(recentQtr)
print(profitMargin)
print(opMargin)
print(returnAssets)
print(returnEquity)
print(revenue)
print(revenuePerShare)
print(grossProfit)
print(ebitda)
print(totalCash)
print(high52)
print(low52)
print("++++++++++++++++++++++++++++++")
'''
dictRow = {"Symbol":c,"Fiscal_Year_End":fiscalYrEnd,"Recent_Qtr":recentQtr,"Profit_Margin":profitMargin,"Operation_Margin":opMargin,"Return_On_Assets":returnAssets,"Return_On_Equity":returnEquity,"Revenue":revenue,"Revenue_Per_Share":revenuePerShare,"Gross_Profit":grossProfit,"EBITDA":ebitda,"Total_Cash":totalCash,"High_52":high52,"Low_52":low52}
webDf = webDf.append(dictRow,ignore_index=True)
#sourceNames =[t.findAll('a')[0].getText().strip() for t in tItems]
#print("length of sourceNames: ", len(sourceNames))
#for n in tItems0:
# (print(n))
print(webDf.head())
print(webDf.shape)
# Saving dataframe to csv file as the processing of the data is taking some time
webDf.to_csv('webData_05022020.csv', index=False)
def main():
'''
Milestone 3 (Weeks 7 & 8)
Cleaning/Formatting Website Data
Perform at least 5 data transformation and/or cleansing steps to your website data. For example:
Replace Headers
Format data into a more readable format
Identify outliers and bad data
Find duplicates
Fix casing or inconsistent values
Conduct Fuzzy Matching
'''
securitiesDf = pd.read_csv("StockMarket/nyse/securities.csv")
# need to rename "Ticker symbol" column heading to "Ticker Symbol" as used for data in other files
securitiesDf.rename(columns={'Ticker symbol': 'Ticker Symbol', 'Security': 'Company Name'}, inplace=True)
print(securitiesDf.head())
print("\nShape of securities.csv\n", '-'*40, sep='')
print(securitiesDf.shape)
#get all the ticker symbols for companies
companyList = securitiesDf["Ticker Symbol"].tolist()
print("\ncompanyList contains this many companies: ", len(companyList))
print("\nreadSaveHtml() was called in previous program run to save html files to ../companyStats/ directory\n", '-'*40, sep='')
# the following method was used to get the html and save the file to disk
#readSaveHtml(companyList)
print("\ncreateDataFrame() was called in previous program run to process html files and create and save webData_05022020.csv to disk \n", '-'*40, sep='')
# the following method was used to create the dataframe using the html files that was saved to disk
# the dataframe is saved to disk in csv format to save time of processing the data every time program is run
#createDataFrame(companyList)
# create the dataframe from the csv file
websiteDf = pd.read_csv("webData_05022020.csv")
print(websiteDf.head())
print("\nShape of websiteDf created from webData_05022020.csv\n", '-'*40, sep='')
print(websiteDf.shape)
print(websiteDf.dtypes)
#outputs (1781, 79)
# noticed when viewing file in Excel and filtering that there were some rows that were completely null
# need to remove
websiteDf = websiteDf.dropna(subset=["Fiscal_Year_End","Recent_Qtr","Profit_Margin","Operation_Margin","Return_On_Assets","Return_On_Equity","Revenue","Revenue_Per_Share","Gross_Profit","EBITDA","Total_Cash","High_52","Low_52"], how='all')
print("\nShape of websiteDf after removing row with all N/A values except the symbol\n", '-'*40, sep='')
print(websiteDf.shape)
# assigning to another data frame as it might not be good to remove entries with just a few missing data
websiteRemoveAllMissingDf = websiteDf.dropna()
print("\nShape of websiteDf if removing rows with any missing data\n", '-'*40, sep='')
print(websiteRemoveAllMissingDf.shape)
print("\nRenamed the column for the symbol to be consistent with the columns for the flat files\n", '-'*40, sep='')
websiteDf.rename(columns={'Symbol': 'Ticker Symbol'}, inplace=True)
print(websiteDf.head())
print("\nConverting Fiscal_Year_End and Recent_Qtr to datetime format for better processing\n", '-'*40, sep='')
websiteDf['Fiscal_Year_End'] = websiteDf['Fiscal_Year_End'].str.replace('[, ]', '', regex=True)
websiteDf['Recent_Qtr'] = websiteDf['Recent_Qtr'].str.replace('[, ]', '', regex=True)
print(websiteDf.head())
websiteDf['Fiscal_Year_End'] = pd.to_datetime(websiteDf['Fiscal_Year_End'], format='%b%d%Y')
websiteDf['Recent_Qtr'] = pd.to_datetime(websiteDf['Recent_Qtr'], format='%b%d%Y')
print(websiteDf.head())
print("\nAnalyzing 52 Week High and Low Price Difference for outliers, bad data,\n", '-'*40, sep='')
# Need to remove some quotes on the High and Low 52 week price
# new dataframe for this part
website52Df = websiteDf.dropna(subset=["High_52","Low_52"], how='all')
website52Df['High_52'] = website52Df['High_52'].str.replace('["\']', '', regex=True)
website52Df['Low_52'] = website52Df['Low_52'].str.replace('["\']', '', regex=True)
website52Df['High_52'] = pd.to_numeric(website52Df['High_52'],errors='coerce')
website52Df['Low_52'] = pd.to_numeric(website52Df['Low_52'],errors='coerce')
# create new column to hold the difference between High 52 Price and Low 52 Price
website52Df["Diff_High_Low_Price_52"] = website52Df["High_52"] - website52Df["Low_52"]
website52Df = website52Df.dropna(subset=["Diff_High_Low_Price_52"])
(website52Df["Diff_High_Low_Price_52"])
# print the box plot to show any outliers between High and Low 52 Week Price calculations that may be of interest
print("\nBox Plot of Differences between High and Low 52 Week Price\n", '-'*40, sep='')
plt.boxplot(website52Df["Diff_High_Low_Price_52"])
plt.show()
print("\nBox Plot shows outliers that are close to 500 or more difference between the High and Low 52 Week Price\n", '-'*40, sep='')
#print("\nColumns in securities.csv\n", '-'*40, sep='')
#for c in securitiesDf.columns:
# print(c)
# Web Service
# https://financialmodelingprep.com/api/v3/company/profile/AAPL,FB
# https://finnhub.io/docs/api#company-executive
# Website - Yahoo finance
# https://finance.yahoo.com/quote/AAPL/profile?p=AAPL
if __name__ == '__main__':
main() |
# Create a class Time with private attributes hour, minute and second. Overload ‘+’ operator to
#find sum of 2 time.
class times:
def __init__(self,h,m,s):
self.h=h
self.m=m
self.s=s
def __add__(self, other):
return self.h + other.h, self.m + other.m, self.s + other.s
v1 = times(2,10,3)
v2 = times(5,2,1)
v3 = v1+v2
print(v3)
|
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
def tri_plot(x,y,topo):
"""
This is a super simple function to plot a triangular mesh.
It is also an interesting exercize to see how to loop over the
mesh elementzs. ``x`` and ``y`` are one dimensional arrays containg the nodes
coordinates. On each row of the ``topo`` matrix is stored the
dof (degree of freedom) with support on the row-th element. Notice that
we are looping over the first dimension of ``topo``, so we only need to
write a standard ``python`` for loop:
.. code:: python
for row in topo:
The ``numpy`` command ``hstack`` is used to attach the last node to the
first one. This is done to "close" our triangles.
.. code:: python
row = np.hstack([row,row[0]])
We use the ``[`` ``]`` brackets to acces the nodes and define the local coords.
.. code:: python
x_l = x[row]
y_l = y[row]
Now we only need to plot the local coords for every triangle:
.. code:: python
plt.plot(x_l, y_l,'-b',linewidth=2)
"""
for row in topo:
row = np.hstack([row,row[0]])
x_l = x[row]
y_l = y[row]
plt.plot(x_l, y_l,'-b',linewidth=2)
plt.show()
return
def plot_sol_p1(x,y,z,topo):
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, cmap=cm.jet,vmin=min(z), vmax=max(z), linewidth=0.2)
#for row in topo:
# x_l = x[row]
# y_l = y[row]
# z_l = z[row]
# ax.plot_trisurf(x_l, y_l, z_l, cmap=cm.jet,
# vmin=min(z), vmax=max(z), linewidth=0.2)
#ax.view_init(90, 0)
#ax.set_zlim([-20,20])
plt.show()
return
def plot_sol_p1p0(x,y,z,topo):
fig = plt.figure()
ax = fig.gca(projection='3d', aspect='equal')
#ax.plot_trisurf(x, y, z, cmap=cm.jet,vmin=min(z), vmax=max(z), linewidth=0.2)
for row in topo:
x_l = x[row[0:3]]
y_l = y[row[0:3]]
z_l = z[row[0:3]]+z[row[3]]
max_z = max(z_l)
ax.plot_trisurf(x_l, y_l, z_l, cmap=cm.jet,
vmin=-110, vmax=110, linewidth=0.)
ax.view_init(70,40)
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
#ax.axis('equal')
plt.show()
return
def plot_sol_p1p0_tex(x,y,z,topo,filename):
fig = plt.figure()
ax = fig.gca(projection='3d', aspect='equal')
#ax.plot_trisurf(x, y, z, cmap=cm.jet,vmin=min(z), vmax=max(z), linewidth=0.2)
for row in topo:
x_l = x[row[0:3]]
y_l = y[row[0:3]]
z_l = z[row[0:3]]+z[row[3]]
max_z = max(z_l)
ax.plot_trisurf(x_l, y_l, z_l, cmap=cm.jet,
vmin=-20, vmax=20., linewidth=0.)
font_size = 18
#ax.view_init(50,30)
ax.set_xlabel(r'$x$',fontsize=font_size)
ax.set_ylabel(r'$y$',fontsize=font_size)
ax.set_zlabel(r'$p$',fontsize=font_size)
ax.set_xticks([0,0.357,.5,1])
ax.set_xticklabels([r'$0$', r'$0.357$', r'$0.5$',r'$1$'],
fontsize=font_size)
ax.set_yticks([0,.5,.7,1])
ax.set_yticklabels([r'$0$', r'$0.5$', r'$0.7$',r'$1$'],
fontsize=font_size)
ax.set_zticks([-20,0,20])
ax.set_zticklabels(
[r'$-20$',r'$0$',r'$20$'],
fontsize=font_size)
ax.set_ylim([0,1])
ax.set_xlim([0,1])
ax.set_zlim([-20,20])
ax.view_init(80,60)
ax.axis('equal')
fig.savefig(filename+'_prex.png')
return
def tri_plot_nodes_num(x,y,topo,line):
i_el = 0
fig = plt.figure()
ax = fig.gca(aspect='equal')
for row in topo:
nds = np.hstack([row,row[0]])
x_l = x[nds]
y_l = y[nds]
x_g = sum(x[row])/3
y_g = sum(y[row])/3
#plt.text(x_g,y_g,str(i_el))
plt.plot(x_l, y_l,line,linewidth=2)
i_el +=1
node_id = 0
for xn,yn in zip(x,y):
ax.text(xn,yn,str(node_id))
node_id +=1
#plt.axis([min(x)-.1*max(x), 1.1*max(x),
# min(y)-.1*max(y), 1.1*max(y)])
#plt.savefig(filename)
return
def tri_plot_tex(x,y,topo,line,filename):
fig = plt.figure()
ax = fig.gca(aspect='equal')
for row in topo:
nds = np.hstack([row,row[0]])
x_l = x[nds]
y_l = y[nds]
plt.plot(x_l, y_l,line,linewidth=1)
ax.set_ylim([0,1])
ax.set_xlim([0,1])
font_size = 18
ax.set_xlabel(r'$x$',fontsize=font_size)
ax.set_ylabel(r'$y$',fontsize=font_size)
ax.set_xticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
ax.set_xticklabels([r'$0$',r'$0.1$',r'$0.2$',r'$0.3$',r'$0.4$' ,r'$0.5$',r'$0.6$',r'$0.7$',r'$0.8$',r'$0.9$',r'$1$'],
fontsize=font_size)
ax.set_yticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
ax.set_yticklabels([r'$0$',r'$0.1$',r'$0.2$',r'$0.3$',r'$0.4$' ,r'$0.5$',r'$0.6$',r'$0.7$',r'$0.8$',r'$0.9$',r'$1$'],
fontsize=font_size)
ax.grid(True)
fig.savefig(filename+'.png')
#plt.savefig(filename)
return
def plot_thin_str(x,y,filename):
fig = plt.figure()
ax = fig.gca(aspect='equal')
plt.plot(x,y)
ax.set_ylim([0,1])
ax.set_xlim([0,1])
fig.savefig(filename+'.png')
return
def plot_ibm(XY_str):
x = XY_str[:,0]
y = XY_str[:,1]
plt.plot(x,y)
plt.axis('equal')
return
def quiver_vel(x,y,u,nx,ny,filename):
ndofs = u.shape[0]
ux = u[0:ndofs/2]
uy = u[ndofs/2:ndofs]
#print u.shape
#print ux.shape
#print uy.shape
x = np.reshape(x , (nx+1,ny+1))
y = np.reshape(y , (nx+1,ny+1))
ux = np.reshape(ux , (nx+1,ny+1))
uy = np.reshape(uy , (nx+1,ny+1))
fig = plt.figure()
plt.quiver(x,y,ux,uy)
plt.axis([-.1, 1.1, -.1, 1.1])
fig.savefig(filename+'.png')
return
def streamlines_str_plot(x,y,u,nx,ny,xs,ys,topo_s,filename):
ndofs = u.shape[0]
ux = u[0:ndofs/2]
uy = u[ndofs/2:]
x = np.reshape(x , (nx+1,ny+1))
y = np.reshape(y , (nx+1,ny+1))
ux = np.reshape(ux , (nx+1,ny+1))
uy = np.reshape(uy , (nx+1,ny+1))
fig = plt.figure()
ax = fig.gca(aspect='equal')
speed = np.sqrt(ux*ux+uy*uy)
lw = 5*speed/speed.max()
plt.streamplot(x,y,ux,uy,color=speed,linewidth=lw)
for row in topo_s:
nds = np.hstack([row,row[0]])
x_l = xs[nds]
y_l = ys[nds]
plt.plot(x_l, y_l,color='0.',linewidth=1)
ax.set_ylim([0,1])
ax.set_xlim([0,1])
font_size = 18
ax.set_xlabel(r'$x$',fontsize=font_size)
ax.set_ylabel(r'$y$',fontsize=font_size)
ax.set_xticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
ax.set_xticklabels([r'$0$',r'$0.1$',r'$0.2$',r'$0.3$',r'$0.4$' ,r'$0.5$',r'$0.6$',r'$0.7$',r'$0.8$',r'$0.9$',r'$1$'],
fontsize=font_size)
ax.set_yticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
ax.set_yticklabels([r'$0$',r'$0.1$',r'$0.2$',r'$0.3$',r'$0.4$' ,r'$0.5$',r'$0.6$',r'$0.7$',r'$0.8$',r'$0.9$',r'$1$'],
fontsize=font_size)
ax.grid(True)
plt.show()
fig.savefig(filename+'.png')
return
def vel_str_plot(x,y,u,nx,ny,xs,ys,topo_s,filename):
ndofs = u.shape[0]
ux = u[0:ndofs/2]
uy = u[ndofs/2:ndofs]
#print u.shape
#print ux.shape
#print uy.shape
x = np.reshape(x , (nx+1,ny+1))
y = np.reshape(y , (nx+1,ny+1))
ux = np.reshape(ux , (nx+1,ny+1))
uy = np.reshape(uy , (nx+1,ny+1))
fig = plt.figure()
ax = fig.gca(aspect='equal')
plt.quiver(x,y,ux,uy,color='0.5')
#plt.axis([-.1, 1.1, -.1, 1.1])
#fig.savefig(filename+'.png')
# fig = plt.figure()
for row in topo_s:
nds = np.hstack([row,row[0]])
x_l = xs[nds]
y_l = ys[nds]
plt.plot(x_l, y_l,'-b',linewidth=1)
ax.set_ylim([-.1,1.1])
ax.set_xlim([-.1,1.1])
font_size = 18
ax.set_xlabel(r'$x$',fontsize=font_size)
ax.set_ylabel(r'$y$',fontsize=font_size)
ax.set_xticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
ax.set_xticklabels([r'$0$',r'$0.1$',r'$0.2$',r'$0.3$',r'$0.4$' ,r'$0.5$',r'$0.6$',r'$0.7$',r'$0.8$',r'$0.9$',r'$1$'],
fontsize=font_size)
ax.set_yticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
ax.set_yticklabels([r'$0$',r'$0.1$',r'$0.2$',r'$0.3$',r'$0.4$' ,r'$0.5$',r'$0.6$',r'$0.7$',r'$0.8$',r'$0.9$',r'$1$'],
fontsize=font_size)
ax.grid(True)
plt.show()
fig.savefig(filename+'.png')
return
|
N=int(input())
fact=1
if(N==0):
print("1")
else:
for i in range(1,N + 1):
fact=fact*i
print(fact)
|
# Q. Take input from the user to get fibonacci series till the number entered
# Ex - input:3
# Ouput: 0, 1, 1
nterms = int(input("How many terms do you want? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print(f"Fibonacci sequence upto {nterms} digits :")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
|
import ast
def tuple_to_string(tupl):
separator = ","
tuple_list = []
for element in tupl:
tuple_list.append(str(element))
string = "(" + separator.join(tuple_list) + ")"
return string
def string_to_tuple(string):
# literal_eval takes a string and duck types it
if type(string) is tuple:
return string
else :
#return tuple([x for x in string.strip().split(",")])
return ast.literal_eval(string)
#return tupl
#takes two tuples of the same length and subtracts each element. zip returns an iterator
def tuple_dif(t1, t2):
return tuple([x-y for x, y in zip(t1,t2)])
def tuple_add(t1, t2):
return tuple([x+y for x, y in zip(t1,t2)])
#converts q,r into q,r,s
def tuple2throuple(t):
if len(t) >2:
return t
### print("{} is {}".format(t, type(t)))
return (*t,-(t[0]+t[1]))
def throuple2tuple(t):
return t[:2]
# converts 2-tuple of integer to string 3-tuple
def convert(t):
return string_to_tuple(tuple2throuple(t)) |
def maximum(num1, num2, num3):
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
return largest
num1 = int (input("Enter first number: " ))
num2 = int (input("Enter second number: " ))
num3 = int (input("Enter third number: " ))
print("The largest number is",maximum(num1, num2, num3)) |
# Jonathan Gieg 77804954 and Hieu Dao-Tran 24353293 ICS 31 Lab Assignment 2
print('How many hours?')
hours = float(input())
print('This many hours:', hours)
print('How many dollars per hour?')
rate = float(input())
print('This many dollars per hour: ', rate)
print('Weekly salary: ', hours * rate)
hours = int(input('How many hours?'))
print('This many hours:', hours)
rate = float(input('How many dollars per hour?'))
print('This many dollars per hour: $ ', rate)
print('Weekly salary: $ ', hours * rate)
print('Hello. What is your name?')
name = input()
print("Hello,", name)
print("It's nice to meet you.")
print('How old are you?')
age = int(input())
print('Next year you will be', age + 1, 'years old.')
print('Good-bye!')
krone_per_euro = 7.46
krone_per_pound = 10.33
krone_per_dollar = 6.66
print('What is your business name?')
business_name = input()
print('How many Euros do you have?')
number_of_euros = float(input())
print('How many pounds do you have?')
number_of_pounds = float(input())
print('How many dollars do you have?')
number_of_dollars = float(input())
print('Business name:', business_name)
print('Number of euros:', number_of_euros)
print('Number of pounds:', number_of_pounds)
print('Number of dollars:', number_of_dollars)
print('Copenhagen Chamber of Commerce')
print('Business name: Tycho Brahe Enterprises')
print(number_of_euros, 'euros is',number_of_euros * krone_per_euro,'krone')
print(number_of_pounds, 'pounds is', number_of_pounds * krone_per_pound,'krone')
print(number_of_dollars, 'dollars is', number_of_dollars * krone_per_dollar,'krone')
e = number_of_euros * krone_per_euro
p = number_of_pounds * krone_per_pound
d = number_of_dollars * krone_per_dollar
print('Total krone:', float(e + p + d))
from collections import namedtuple
Book = namedtuple('Book', 'title author year price')
favorite = Book('Adventures of Sherlock Holmes',
'Arthur Conan Doyle', 1892, 21.50)
another = Book('Memoirs of Sherlock Holmes',
'Arthur Conan Doyle', 1894, 23.50)
still_another = Book('Return of Sherlock Holmes',
'Arthur Conan Doyle', 1905, 25.00)
print(still_another[0])
print(another[3])
print(float((favorite[3] + another[3] + still_another[3])/3))
print(favorite[2] < 1900)
still_another = Book('Return of Sherlock Holmes',
'Arthur Conan Doyle', 1905, 26.00)
print(still_another[3] * 1.20)
from collections import namedtuple
Animal = namedtuple('Animal', 'name species age_in_years weight_in_kg food')
animal1 = Animal('Jumbo', 'Elephant', 50 , 1000, 'peanuts')
animal2 = Animal('Perry', 'Platypus', 7 , 1.7 , 'shrimp')
print(animal1[3] < animal2[3])
booklist = [favorite, another, still_another]
print(booklist[0][3] < booklist[1][3])
print(booklist[0][2] > booklist[-1][2])
|
from Tkinter import *
import time
import random
from collections import deque
#####################
##### CLASSES #######
#####################
#square tile
#size is the w or h
class Tile:
def __init__(self, size, centerX, centerY, row, col):
self.size = size
self.centerX = centerX
self.centerY = centerY
self.row = row
self.col = col
self.visited = False
self.frontier = False
self.cost = 0
self.partOfPath = False
#randomly make some tiles impassable
chance = 2
if random.randint(0, chance) == chance:
self.passable = False
else:
self.passable = True
def draw(self):
if self.passable == False:
color = "black"
elif self.partOfPath == True:
color = "#904040"
elif self.frontier == True:
color = "#404090" #blue
elif self.visited == True:
color = "#409040" #green
else:
color = "#808080" #gray
canvas.create_rectangle(self.centerX - tileSize / 2,
self.centerY - tileSize / 2,
self.centerX + tileSize / 2,
self.centerY + tileSize / 2,
fill=color)
canvas.create_text(self.centerX, self.centerY, text=self.cost)
def togglePassable(self):
self.passable = not self.passable
self.draw()
#a gridSize x gridSize array of Tiles
class Grid:
def __init__(self):
#self.playGrid = [[0 for i in range(gridSize)] for j in range(gridSize)]
self.playGrid = []
#create tiles
for row in range(numRows):
self.playGrid.append([])
for col in range(numCols):
#i * tileSize gets you to the left side, adding half of tilesize gets you to the center, modulus keeps it in rows
#centerX = (i * tileSize + (tileSize / 2)) % (lastPixel)
centerX = col * tileSize + (tileSize / 2)
#i / grisize gets you the row #, * tilsize gets you the bottom of the rectangle, - tilesize/2 gets you the center
#centerY = ((i / gridSize) + 1) * tileSize - (tileSize / 2)
centerY = row * tileSize + (tileSize / 2)
#RRGGBB more green as it goes to the right, more blue as it goes down
#color = "#00" + "%02x" % ((i % gridSize) * (256 / gridSize)) + "%02x" % ((i / gridSize) * (256 / gridSize))
#color = random.choice(colors)
#self.playGrid[row][col] = Tile(tileSize, centerX, centerY, row, col)
self.playGrid[row].append(Tile(tileSize, centerX, centerY, row, col))
#draws rectangles on a canvas based on the tile information
def drawTiles(self): #add newseed if going back to random colors
#random.seed(newSeed)
canvas.delete(ALL)
for row in self.playGrid:
for tile in row:
#tile.color = random.choice(colors)
tile.draw()
#canvas.create_text(tile.centerX, tile.centerY, text=tile.cost)
canvas.pack()
#returns number of clicked tile, based off x & y coords
def findTile(self, xpos, ypos):
row = ypos / tileSize
col = xpos / tileSize
return self.playGrid[row][col]
class POI:
def __init__(self, xpos, ypos, tag, color, symbol):
#self.gridX = xpos
#self.gridY = ypos
self.tag = tag
self.color = color
self.symbol = symbol
def placeAt(self, row, col):
self.row = row
self.col = col
grid.playGrid[row][col].passable = True
grid.playGrid[row][col].draw()
self.draw()
def draw(self):
if self.row == None or self.col == None:
return
canvas.delete(self.tag)
canvas.create_oval(grid.playGrid[self.row][self.col].centerX - tileSize / 2,
grid.playGrid[self.row][self.col].centerY - tileSize / 2,
grid.playGrid[self.row][self.col].centerX + tileSize / 2,
grid.playGrid[self.row][self.col].centerY + tileSize / 2,
fill=self.color,
tag=self.tag)
canvas.create_text(grid.playGrid[self.row][self.col].centerX, grid.playGrid[self.row][self.col].centerY, text=self.symbol, tag=self.tag)
class Pathfinder:
def __init__(self):
self.frontier = deque()
self.stepCount = 0
#start from the end
self.current = 0
self.pathLength = 0
def fullFrontier(self):
self.clear()
self.reset()
while len(self.frontier) > 0:
self.stepFrontier()
def stepFrontier(self):
if len(self.frontier) == 0:
return
self.stepCount += 1
stpct.set("Step Count: " + str(self.stepCount))
workingTile = self.frontier.popleft()
workingTile.visited = True
workingTile.frontier = False
workingTile.draw()
possibleFrontier = adjacentTiles(workingTile)
for loc in possibleFrontier:
if inRange(loc[0], loc[1]):
tile = grid.playGrid[loc[0]][loc[1]]
if tile.visited == True:
tile.cost = min(tile.cost, workingTile.cost + 1)
elif tile not in self.frontier and tile.passable == True:
self.frontier.append(tile)
tile.frontier = True
tile.cost = workingTile.cost + 1
tile.draw()
drawEntities()
def fullPath(self):
#wh
i = 0
while self.current != grid.playGrid[player.row][player.col] and i < 100:
if self.stepPath() == 1:
return
i += 1
def playPath(self):
i = 0
while self.current != grid.playGrid[player.row][player.col] and i < 100:
if self.stepPath() == 1:
return
i += 1
#move one tile closer to the player, based on the cost of tiles
def stepPath(self):
#initialize
if self.current == 0:
self.current = grid.playGrid[exit.row][exit.col]
self.current.partOfPath = True
self.current.draw()
if self.current.visited == False:
print "Error: no path found, try expanding frontier"
return 1
#find row, col of all adjacent tiles
adjacents = adjacentTiles(self.current)
#add all in range tiles to list of possibles
adjTiles = []
for adj in adjacents:
if inRange(adj[0], adj[1]):
adjTiles.append(grid.playGrid[adj[0]][adj[1]])
#see which possible has the lowest cost and is passable
for adj in adjTiles:
if adj.cost < self.current.cost and adj.passable:
self.current = adj
self.pathLength += 1
pathLength.set("Path Length: " + str(self.pathLength))
self.current.partOfPath = True
self.current.draw()
drawEntities()
def clear(self):
self.frontier.clear()
self.stepCount = 0
self.pathLength = 0
self.current = 0
stpct.set("Step Count: 0")
pathLength.set("Path Length: 0")
for row in grid.playGrid:
for tile in row:
tile.visited = False
tile.frontier = False
tile.cost = 0
tile.partOfPath = False
drawAll()
def reset(self):
self.frontier.append(grid.playGrid[player.row][player.col])
#####################
##### FUNCTIONS #####
#####################
def drawEntities():
for entity in entities:
entity.draw()
def drawAll():
grid.drawTiles()
drawEntities()
def adjacentTiles(tile):
return ((tile.row+1, tile.col),
(tile.row-1, tile.col),
(tile.row, tile.col+1),
(tile.row, tile.col-1))
def inRange(row, col):
if row >= 0 and row < numRows and col >= 0 and col < numCols:
return True
else:
return False
#for when you click on a tile
def clickTile(event):
global prevClickedEntity #no statics :(
frame.focus_set()
clickedTile = grid.findTile(event.x, event.y)
clickedEntity = None
#find if there's an entity on the clicked tile
for entity in entities:
if entity.row == clickedTile.row and entity.col == clickedTile.col:
clickedEntity = entity
#if you're selecting an entity for the first time, remove it from board
if clickedEntity is not None and prevClickedEntity is None:
clickedEntity.row = None
clickedEntity.col = None
prevClickedEntity = clickedEntity
canvas.delete(clickedEntity.tag)
pathfinder.clear()
#if you've previously selected an entity and are clicking an empty tile, add the prev entity to the board
elif clickedEntity is None and prevClickedEntity is not None:
prevClickedEntity.row = clickedTile.row
prevClickedEntity.col = clickedTile.col
drawEntities()
pathfinder.reset()
prevClickedEntity = None
#otherwise toggle passable
else:
clickedTile.togglePassable()
#####################
##### CONSTANTS #####
#####################
colors = ["white", "red", "green", "blue", "cyan", "yellow", "magenta"]
#gridSize = 16
numRows = 32
numCols = 32
lastTile = numRows * numCols
tileSize = 16
lastHPixel = numRows * tileSize
lastVPixel = numCols * tileSize
#####################
####### MAIN ########
#####################
root = Tk()
root.wm_title("Pathfinder")
pathfinder = Pathfinder()
frame = Frame(root)
frame.pack(side=LEFT)
prevClickedEntity = None
canvas = Canvas(frame, width=numCols * tileSize, height=numRows * tileSize)
canvas.bind("<Button-1>", clickTile)
canvas.pack()
optionsPanel = Frame(root)
optionsPanel.pack(side=RIGHT)
stpct = StringVar()
steps = Label(optionsPanel, width=14, textvariable=stpct)
steps.grid(row=0, column=0)
stpct.set("Step Count: 0")
fullFrontierButton = Button(optionsPanel, text="frontier", command=pathfinder.fullFrontier)
fullFrontierButton.grid(row=0, column=1)
stepFrontierButton = Button(optionsPanel, text="f>", command=pathfinder.stepFrontier)
stepFrontierButton.grid(row=0, column=2)
pathLength = StringVar()
pathLen = Label(optionsPanel, width=14, textvariable = pathLength)
pathLen.grid(row=1, column=0)
pathLength.set("Path Length: 0")
fullPathButton = Button(optionsPanel, text="path", command=pathfinder.fullPath)
fullPathButton.grid(row=1, column=1)
stepPathButton = Button(optionsPanel, text="p>", command=pathfinder.stepPath)
stepPathButton.grid(row=1, column=2)
grid = Grid()
grid.drawTiles() #seedEntry.get() if going back to random colors
entities = []
player = POI(xpos=3, ypos=2, tag="player", color="yellow", symbol="@")
player.placeAt(0, 0)
entities.append(player)
exit = POI(xpos=1, ypos=2, tag="exit", color="red", symbol="E")
exit.placeAt(numRows-1, numCols-1)
entities.append(exit)
pathfinder.reset()
drawEntities()
#main loop
root.mainloop() |
with open('pi_digits.txt') as file_object:
content = file_object.read()
print(content)
print()
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print()
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip()) |
# В трёх классах проходят занятия в одно и то же время, нужно узнать количество парт для каждого класса.
# За каждой партой может сидеть не больше двух учеников.
# Известно количество учащихся в каждом из трёх классов.
# Сколько всего нужно закупить парт чтобы их хватило на всех учеников?
# Программа получает на вход три натуральных числа: количество учащихся в каждом из трех классов.
a = int(input('\nУчеников в первом классе:\t'))
b = int(input('Учеников во втором классе:\t'))
c = int(input('Учеников в третьем классе:\t'))
i = '\n\tВсего нужно {} парт(ы)\n'
n = (((a // 2) + (a % 2)) + ((b // 2) + (b % 2)) + ((c // 2) + (c % 2)))
print('~' * 30, (i.format(n)), '~' * 28)
|
#sequence.py
#lists the squares of all integers from some starting number squared down to one
#
#Colin McCahill
#09/10/15
x=eval(input("Give me a number to start with:"))
print("Squares from",x**2,"down to 1:")
for i in range(x,0,-1):
print(i**2,", ",sep='',end='')
|
#hello.py
#classic Hello, World program, but this time we will say hello from multiple
#processes
#
#Colin McCahill
#12/2/15
from multiprocessing import *
def HelloWorld(name):
print("Hello to %s from process %d" %(name,current_process().pid))
def main():
name=input("What is your name? ")
n=eval(input("number n of processes to create: "))
for i in range(n):
p=Process(target=HelloWorld,args=(name,))
p.start()
main()
|
def euclidian(testElement,training): #euclidian distance algorithm
import math
distances = []
for trainingElement in training: #loops through all the training elements
dist = 0
for m in range(1,len(testElement)): #loops through each attribute
difference = testElement[m] - trainingElement[m] #finds the difference in distance
dist += (difference * difference) #squares the distance
dist = math.sqrt(dist) #square roots the sum of distances
distances.append(dist)
return distances
def hamming(testElement,training): #hamming distance algorithm
distances = []
for trainingElement in training: #loops through training
dist = 0
for m in range(1,len(testElement)): #loops through each attribute
if testElement[m] != trainingElement[m]: #if the attribute is different, it adds 1 to distance
dist +=1
distances.append(dist)
return distances
def most_frequent(List): #this function is here to find the most common element in the list of neighbors for n neighbors
counter = 0
num = List[0]
for i in List:
curr_frequency = List.count(i)
if(curr_frequency> counter):
counter = curr_frequency
num = i
return num
def calculateAccuracy(training,test,distFunc,k): #does most of the work of the program
predicted = []
actual = []
labels= []
for testElement in test: #loops through all test elements
if(distFunc == "E"): #euclidian
distances = euclidian(testElement,training)
else: #hamming
distances = hamming(testElement,training)
minDistance = []
#loops through the distances and finds the smalllest distances
for i in range(0,len(distances)):
if i < k:
minDistance.append(distances[i])
else:
if distances[i] < max(minDistance):
minDistance[minDistance.index(max(minDistance))] = distances[i]
predictionIndices = []
#finds the indices of the minDistances in the distances list
for i in range(0, len(minDistance)):
predictionIndices.append(distances.index(minDistance[i]))
predictions = []
#goes through each predictionIndex and finds the correlating classification in the training list
for m in predictionIndices:
predictions.append(training[m][0])
predicted.append(most_frequent(predictions))
for i in test: #this loop gives the list of possible labels
actual.append(i[0])
if len(labels) == 0:
labels.append(i[0])
elif i[0] in labels:
continue
else:
labels.append(i[0])
matrix = []
for m in range(0,len(labels)): #these two loops create the matrix necessary for printing
matrixEntry = [0] * (len(labels) + 1)
matrixEntry[0] = labels[m]
matrix.append(matrixEntry)
for p in range(0,len(predicted)):
predictedIndex = labels.index(predicted[p])
actualIndex = labels.index(actual[p]) + 1
matrix[predictedIndex][actualIndex] += 1
return labels,matrix
def createTrainingSet(seed,percentage,entireList): #creates the training set and test set
import random
trainingLimit = round(percentage * len(entireList)) #finds the necessary number of instances for each set
sizeOfEntireList = len(entireList) - 1
trainingSet = []
random.seed(seed) #uses the seed necessary for randomization
for i in range(0,trainingLimit):
index = random.randint(0,sizeOfEntireList) #finds a random index to put in the training set
trainingSet.append(entireList[index])
del entireList[index]
sizeOfEntireList -= 1
return trainingSet,entireList
#parseFile
def parseFile(file,nominal): #parses the file into a list
counter = 0
data = []
for line in file:
if counter==0 or nominal:
startline = line.strip().split(",")
startlineStrings = []
for i in startline:
startlineStrings.append(str(i).replace('"',''))
data.append(startlineStrings)
else:
dataLine = line.strip().split(",")
dataValues = []
dataValues.append(str(dataLine[0].replace('"','')))
for x in range(1,len(dataLine)):
dataValues.append(float(dataLine[x]))
data.append(dataValues)
counter +=1
return data
#main
import sys
filePath = open(sys.argv[1])
distFunc = str(sys.argv[2])
k = int(sys.argv[3])
trainingPercent = float(sys.argv[4])
seed = int(sys.argv[5])
nominal = False
if(str(sys.argv[1]) == "monks1.csv"): #case statement here for monks (for parsing purposes)
nominal = True
wholeSet = parseFile(filePath,nominal)
training,test = createTrainingSet(seed, trainingPercent,wholeSet[1:])
labels,matrix = calculateAccuracy(training,test,distFunc,k)
for L in labels:
print(L + ",",end ='')
print()
for i in range(1,len(matrix)+1):
for m in matrix:
print(str(m[i])+",",end='')
print(labels[i-1])
|
#recstr.py
#1.prompt the user for a string s
#2.prompt the user for string t,
#3.print s backwards
#4.print whether or not s is a palindrome,
#5.print whether t appears as a (possibly non-consecutive)subsequence of s.
def rev(s):
if len(s)==0:
return s
else:
return s[-1]+rev(s[0:len(s)-1])
def pal(s):
if len(s)==0 or len(s)==1:
return "is"
if s[len(s)-1]==s[0]:
return pal(s[1:len(s)-1])
else:
return "is not"
def subseq(s,t):
if len(t)==0:
return "is"
if len(t)>len(s):
return "is not"
if s[0]==t[0]:
return subseq(s[1:len(s)],t[1:len(s)])
if s[0]!=t[0]:
return subseq(s[1:len(s)],t)
def main():
print("Welcome to my Incredible Recursive string thing!")
print()
s=input("Please enter a string s:")
t=input("Please enter a string t:")
print("The string \"",s,"\" backwards is \"",rev(s),"\".",sep='')
print("The string \"",s,"\" ", pal(s), " a palindrome.",sep='')
print("The string \"",t,"\" ",subseq(s,t)," a subsequence of \"",s,"\".",
sep='')
main()
|
import math
# classe usada para armazenar grandezas vetoriais e realizar operacoes envolvendo essas grandezas
class Vetor(object):
def __init__(self, x, y):
self.x = x
self.y = y
# cria um vetor unitario a partir de um angulo
@classmethod
def unitario(self, theta):
return Vetor(math.cos(theta), math.sin(theta))
# imprime informacoes sobre o vetor
def get_info(self):
print "Coordenadas: ( %s, %s)" % (self.x, self.y)
# 'Coordenadas: (' + repr(self.x) + ', ' + repr(self.y) + ')'
# modifica as coordenadas do vetor
def set(self, x, y):
self.x = x
self.y = y
# verifica se o vetor e diferente de um outor vetor
def diferente(self, v):
return self.x != v.x or self.y != v.y
# calcula o modulo do vetor
def tamanho(self):
return math.sqrt(self.x**2 + self.y**2)
# calcula o modulo do vetor ao quadrado
def quadrado(self):
return self.x**2 + self.y**2
# calcula a distancia com relacao a outro vetor v
def distancia(self, v):
return math.sqrt((self.x - v.x)**2 + (self.y - v.y)**2)
# retorna a orientacao do vetor
def angulo(self):
return math.atan2(self.y, self.x)
# calcula produto escalar do vetor com outro vetor recebido
def produto_escalar(self, v):
return self.x*v.x + self.y*v.y
# calcula o angulo que o vetor forma com outro vetor recebido
def angulo_com(self, v):
modulo_self = self.tamanho()
modulo_v = v.tamanho()
if (modulo_self != 0 and modulo_v != 0):
return math.acos( self.produto_escalar(v) / (modulo_self*modulo_v) )
else:
return None
# calcula a coordenada z do produto vetorial com outro vetor no plano xy
def produto_vetorial(self, v):
return self.x*v.y - self.y*v.x
# calcula o angulo com outro vetor levando em conta se foi girado no sentido horario ou anti-horario
def delta_angulo_com(self, v):
modulo_self = self.tamanho()
modulo_v = v.tamanho()
produto = self.produto_vetorial(v)
if (produto == 0 and modulo_self != 0 and modulo_v != 0):
if (self.angulo() == v.angulo()): # paralelos, mesma direcao
return 0 # angulo e zero
return math.pi # parelelos, direcao contraria, angulo e pi
if (modulo_self != 0 and modulo_v != 0):
return (produto / abs(produto)) * Vetor.angulo_com(self, v)
return None
# transforma o vetor em um vetor unitario
def normaliza(self):
modulo = self.tamanho()
self.x /= modulo
self.y /= modulo
# retorna um vetor igual a soma de dois vetores
@classmethod
def soma(self, v1, v2):
return Vetor(v1.x + v2.x, v1.y + v2.y)
# retorna um vetor igual a subtracao de dois vetores
@classmethod
def subtrai(self, v1, v2):
return Vetor(v1.x - v2.x, v1.y - v2.y)
# multiplica um vetor por um escalar
@classmethod
def multiplica(self, v, escalar):
return Vetor(escalar * v.x, escalar * v.y)
# retorna um vetor igual ao vetor v girado de theta
@classmethod
def gira(self, v, theta):
cosseno = math.cos(theta)
seno = math.sin(theta)
x = v.x*cosseno - v.y*seno
y = v.x*seno + v.y*cosseno
return Vetor(x, y)
|
t=int(input())
for i in range(t):
even=0
odd=0
n=int(input())
numbers=list(map(int,input().split()))
for i in numbers:
if i%2==0:
even+=1
else:
odd+=1
if even>0 and odd==0:
print('Even')
elif odd>0 and even==0:
print('Odd')
else:
print('Mix')
|
n=int(input())
matrix=[]
l=[]
for i in range(n):
new=[]
for j in range(n):
new.append(1)
matrix.append(new)
if len(matrix)==1:
print(1)
exit(0)
for i in range(n):
if i==0:
continue
for j in range(n):
if j==0:
continue
matrix[i][j]=matrix[i-1][j]+matrix[i][j-1]
l.append(matrix[i][j])
print(max(l))
|
def IsPrime(n):
prime=[True for i in range(n+1)]
prime[0]=False
prime[1]=False
for i in range(2,n+1):
if prime[i]:
for j in range(i+i,n+1,i):
prime[j]=False
return prime
l,r=map(int,input().split())
total=0
count=0
p=IsPrime(1000001)
for i in range(l,r+1):
if p[i]:
count+=1
total+=i
print(total,count)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.