text stringlengths 37 1.41M |
|---|
# 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 levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
level_list = []
self.dfs(0, root, level_list)
return level_list[: : -1]
def dfs(self, level, root, level_list):
if None == root:
return
while len(level_list) <= level:
level_list.append([])
level_list[level].append(root.val)
self.dfs(level + 1, root.left, level_list)
self.dfs(level + 1, root.right, level_list)
|
#import statment to use sql
import sqlite3
#create sql database file called myemaildb.sql
conn = sqlite3.connect('myemaildb.sqlite')
cur = conn.cursor()
#if table exists, drop table
cur.execute('''
DROP TABLE IF EXISTS Counts''')
#if create table Counts
cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')
#usual prompt user for input and open file
fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'mbox-short.txt'
fh = open(fname)
#for loop to get parts we need from whole file
for line in fh:
#splits lines into just email address
if not line.startswith('From: ') : continue
pieces = line.split()
email = pieces[1]
###########################################
#this is to find domain name and it works
pieces2 = line.split('@') #split at '@' sign
org = pieces2[1]
org = org.rstrip() #elimn. new line char and whitespace from right
print org
###########################################
cur.execute('SELECT count FROM Counts WHERE org = ? ', (org, ))
#? in email = is placeholder to be filled in w/ whatever you need
#first thing in tuple is whats in question mark
#this is done to prevent sql injection
row = cur.fetchone() #instruction to get row that matches
if row is None:#if row does not exist then insert
cur.execute('''INSERT INTO Counts (org, count)
VALUES ( ?, 1 )''', ( org, ) )
else : #if it does then update the count
cur.execute('UPDATE Counts SET count=count+1 WHERE org = ?',
(org, ))
# This statement commits outstanding changes to disk each
# time through the loop - the program can be made faster
# by moving the commit so it runs only after the loop completes
conn.commit() ####need to move this to outside loop?
# https://www.sqlite.org/lang_select.html
#basically prints to screen when table is created and set up
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'
print
print "Counts:"
for row in cur.execute(sqlstr) :
print str(row[0]), row[1]
cur.close()
|
from random import randint
sum = 20000
bet = 500
loss = 0
profit = 0
chance = 0
sleact = int(input("Enter your Dice sleaction"))
while(sum >= 0):
profit = 0
chance += 1
x = randint(2, 12)
print("Bet = ", bet)
if x == sleact:
sum = sum + (bet * 3)
profit = profit + (bet*3)
bet = 500
else:
loss = loss + bet
sum = sum - bet
bet = bet + 500
print("Chances = ", chance)
print("Dice = ", x)
print("Total = ", sum)
print("Loss = ", loss)
print("Profit = ", profit)
print("Total profit = ", profit - loss)
input()
|
class PythonClassDemo:
'Sample demo class for Python study'
demoCount = 0;
def __init__(self, name):
self.name = name;
def incrementCount(self):
PythonClassDemo.demoCount += 1;
def printMyName(self):
print("My name is ", self.name);
def __del__(self):
class_name = self.__class__.__name__;
print (class_name, ",",self.name," DESTROYED");
demoObject1 = PythonClassDemo("Name1");
demoObject1.incrementCount();
demoObject1.printMyName();
print("demo count" , PythonClassDemo.demoCount);
demoObject2 = PythonClassDemo("Name2");
demoObject2.incrementCount();
demoObject2.printMyName();
print("demo count" , PythonClassDemo.demoCount);
demoObject3 = PythonClassDemo("Name3");
demoObject3.incrementCount();
demoObject3.printMyName();
print("demo count" , PythonClassDemo.demoCount);
demoObject4 = PythonClassDemo("Name4");
demoObject4.incrementCount();
demoObject4.printMyName();
print("demo count" , PythonClassDemo.demoCount);
demoObject5 = PythonClassDemo("Name5");
demoObject5.incrementCount();
demoObject5.printMyName();
print("demo count" , PythonClassDemo.demoCount);
if hasattr(demoObject5, 'name'):
print("demoObject5 has an attribute named name");
myname = getattr(demoObject5,'name');
print("My name is ", myname);
setattr(demoObject5, 'name', 'NewName5');
print("My modified name is ", demoObject5.name);
else:
print("demoObject5 does not have an attribute named name");
del(demoObject5);
print ("PythonClassDemo.__doc__:", PythonClassDemo.__doc__);
print ("PythonClassDemo.__name__:", PythonClassDemo.__name__);
print ("PythonClassDemo.__module__:", PythonClassDemo.__module__);
print ("PythonClassDemo.__bases__:", PythonClassDemo.__bases__);
print ("PythonClassDemo.__dict__:", PythonClassDemo.__dict__);
|
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
def print_list(head):
node = head
while node is not None:
random = node.random
zcs = -1 if random is None else random.val
print("[%d, %d]" % (node.val, zcs), end = " ")
node = node.next
print()
class Solution:
"""
解法2:
复制head为new_head(next和random指针也一样)并把new_head放入list,还要记录dict[head]=new_head
取出list队首节点,如果节点的next不为空,则查找dict中是否有next,没有则复制一下放入list后边,并在dict中记录dict[next]=new_next
然后修改刚刚取出的节点的next=new_next
刚刚取出的节点的random,做一样的处理
直到list为空
"""
def copyRandomList(self, head: 'Node') -> 'Node':
if head is None:
return None
node = head
while node is not None: #第一次遍历,复制每个节点插在原链表的后边
new_node = Node(node.val, node.next)
node.next = new_node
node = new_node.next
node = head
while node is not None: #第二次遍历,处理random指针
if node.random is not None:
node.next.random = node.random.next
node = node.next.next
# print_list(head)
node = head
ret_head = head.next
while node is not None and node.next.next is not None: #第三次遍历,拆出复制的链表
tmp1 = node.next
tmp2 = node.next.next.next
node = node.next.next
tmp1.next = tmp2
return ret_head
if __name__ == "__main__":
# [[7,null],[13,0],[11,4],[10,2],[1,0]]
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node1.random = node3
node2.next = node3
node3.random = node1
print_list(node1)
ret = Solution().copyRandomList(node1)
print_list(ret) |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root is None:
return 0
q = []
q.append((root, 0))
ret = 0
while q:
node, flag = q.pop(0)
if node.left is not None:
q.append((node.left, 1))
if node.right is not None:
q.append((node.right, 0))
if flag == 1 and node.left is None and node.right is None:
ret += node.val
return ret
root = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
print(Solution().sumOfLeftLeaves(root)) |
height = -1
while height < 0 or height > 23:
try:
height = int(input("Height: "))
except:
pass
for i in range(0, height):
print((height - i - 1) * " " + (i + 1) * "#" + "#") |
# tags: iniciante
a = int(input())
b = float(input())
print('{:.3f} km/l'.format(a / b))
|
# tags: pi, iniciante, volume da esfera
PI = 3.14159
r = int(input())
volume = (4.0/3) * PI * (r ** 3)
print('VOLUME = {:.3f}'.format(volume))
|
from enum import Enum
from typing import List
INPUT_TEST1 = '../inputs/day13_test1.txt'
INPUT_TEST2 = '../inputs/day13_test2.txt'
INPUT_PART2_TEST = '../inputs/day13_part2_test.txt'
INPUT = '../inputs/day13.txt'
class Cart(object):
def __init__(self, id: int, x: int, y: int, direction: str, tile: str):
self.id = id
self.x = x
self.y = y
self.direction = direction
self.tile = tile
self.intersection_count = 0
self.crashed = False
def move(self, track, carts):
if self.crashed:
return
if self.direction == '>':
self.x += 1
elif self.direction == '<':
self.x -= 1
elif self.direction == '^':
self.y -= 1
elif self.direction == 'v':
self.y += 1
new_tile = track[self.y][self.x]
if new_tile == '/':
if self.direction == '>':
self.direction = '^'
elif self.direction == '<':
self.direction = 'v'
elif self.direction == '^':
self.direction = '>'
elif self.direction == 'v':
self.direction = '<'
elif new_tile == '\\':
if self.direction == '>':
self.direction = 'v'
elif self.direction == '<':
self.direction = '^'
elif self.direction == '^':
self.direction = '<'
elif self.direction == 'v':
self.direction = '>'
elif new_tile == '+':
intersection_turn = self.intersection_count % 3
# Turn left
if intersection_turn == 0:
if self.direction == '^':
self.direction = '<'
elif self.direction == 'v':
self.direction = '>'
elif self.direction == '<':
self.direction = 'v'
elif self.direction == '>':
self.direction = '^'
# Turn right
elif intersection_turn == 2:
if self.direction == '^':
self.direction = '>'
elif self.direction == 'v':
self.direction = '<'
elif self.direction == '<':
self.direction = '^'
elif self.direction == '>':
self.direction = 'v'
self.intersection_count += 1
crashes = [c for c in carts
if c.id != self.id and c.x == self.x and c.y == self.y]
if crashes:
self.crashed = True
self.direction = 'x'
for c in [c for c in crashes if not c.crashed]:
c.crashed = True
c.direction = 'x'
self.tile = new_tile
def parsefile(input) -> List:
track = []
carts = []
with open(input, mode='r') as data:
lines = [l.rstrip() for l in data.readlines()]
for y, line in enumerate(lines):
line_tiles = []
for x, tile in enumerate(line):
actual_tile = tile
if tile == '>' or tile == '<' or tile == '^' or tile == 'v':
if tile == '>' or tile == '<':
actual_tile = '-'
else:
actual_tile = '|'
cart = Cart(len(carts) + 1, x, y, tile, actual_tile)
carts.append(cart)
line_tiles.append(actual_tile)
track.append(line_tiles)
return track, carts
def print_track(track: List[List[str]], carts: List[Cart]):
print('\n======')
for y, line in enumerate(track):
toprint = ''
for x, tile in enumerate(line):
cart = next((c for c in carts if c.x == x and c.y == y), None)
toprint += cart.direction if cart else tile
print(toprint)
print('======\n')
def part1(track: List[List[str]], carts: List[Cart]):
crashes = []
# print_track(track, carts)
while not crashes:
tick(track, carts)
crashes = [c for c in carts if c.crashed]
# print_track(track, carts)
# input()
print([(c.x, c.y) for c in crashes])
def tick(track: List[List[str]], carts: List[Cart]):
ordered_carts = sorted(carts, key=lambda c: (c.y, c.x))
for cart in ordered_carts:
cart.move(track, carts)
def part2(track: List[List[str]], carts: List[Cart]):
while len(carts) > 1:
tick(track, carts)
carts = [c for c in carts if not c.crashed]
print([(c.x, c.y) for c in carts])
def main():
track1, carts1 = parsefile(INPUT_TEST1)
part1(track1, carts1)
track2, carts2 = parsefile(INPUT_TEST2)
part1(track2, carts2)
track3, carts3 = parsefile(INPUT)
part1(track3, carts3)
track4, carts4 = parsefile(INPUT_PART2_TEST)
part2(track4, carts4)
part2(track3, carts3)
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
from random import randint
import simple_draw as sd
def tree_paint():
first_point = sd.get_point(1150, 150)
tree_color = sd.random_color()
while tree_color == (sd.COLOR_ORANGE or sd.COLOR_DARK_RED or sd.COLOR_DARK_YELLOW
or sd.background_color or (100, 100, 100)):
tree_color = sd.random_color()
def draw_branches(start_point, start_angle, start_length, start_color, width):
# two branches, left and right
branch_1 = sd.get_vector(start_point=start_point, angle=start_angle + 30, length=start_length, width=width)
branch_1.draw(start_color)
branch_2 = sd.get_vector(start_point=start_point, angle=start_angle - 30, length=start_length, width=width)
branch_2.draw(start_color)
# target 2, after first two branches changing length, angle, width and start point of drawing
start_length *= (0.75 + (randint(-10, 10) / 100))
start_point = branch_1.end_point
start_angle = branch_1.angle + randint(-12, 12)
width = width - 1
if start_length > 10:
# continuing of left root, recursion
draw_branches(start_point=start_point, start_angle=start_angle, start_length=start_length,
start_color=tree_color, width=width)
start_point = branch_2.end_point
rand_int = randint(-12, 12)
start_angle = branch_2.angle - rand_int
if start_length > 10:
# continuing of right root, recursion
draw_branches(start_point=start_point, start_angle=start_angle, start_length=start_length,
start_color=tree_color, width=width)
# first line, vertical part of tree
sd.line(sd.get_point(1150, 0), sd.get_point(1150, 150),color=tree_color, width=14)
draw_branches(start_point=first_point, start_angle=90, start_length=105, start_color=tree_color, width=12)
|
# Given 3 numbers {1, 3, 5}, we need to tell
# the total number of ways we can form a number 'N'
# using the sum of the given three numbers.
'''
sum > N:
return
sum == N:
print
return
sum < N:
choose[0]
f()
unchoose
choose[1]
f()
choose[2]
'''
def _sum(s, N, currentSum, memo):
# print "_sum (", s, " ", N, " ", currentSum, ")"
# global ways
if currentSum > N:
return 0
if currentSum == N:
return 1
if currentSum not in memo:
ways = 0
for x in s:
currentSum+= x
ways += _sum(s, N, currentSum, memo)
if currentSum not in memo:
memo[currentSum] = ways
currentSum-=x
return ways
else:
return memo[currentSum]
print _sum([1,3,5], 6, 0, {})
# print ways |
def minimumValue(dp, ele):
minVal = float('inf')
for num in dp:
add = num + ele
sub = num - ele
mul = num * ele
if ele != 0:
div = num / ele
else:
div = float('inf')
minVal = min(minVal, add, sub, mul, div)
return minVal
def maximumValue(dp, ele):
maxVal = float('-inf')
for num in dp:
add = num + ele
sub = num - ele
mul = num * ele
if ele != 0:
div = num / ele
else:
div = float('-inf')
maxVal = max(maxVal, add, sub, mul, div)
return maxVal
def findMaxValue(arr):
dp = [None] * len(arr)
if len(arr) == 0:
return 0
dp[0] = (arr[0], arr[0])
for i in range(1, len(arr)):
dp[i] = (minimumValue(dp[i-1], arr[i]), maximumValue(dp[i-1], arr[i]))
return max(dp[len(dp)-1])
print findMaxValue([-1, -2, -1])
|
class Node:
def __init__(self, val):
self.data = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, val):
if self.head is None:
self.head = Node(val)
else:
curr = self.head
while curr.next:
curr = curr.next
curr.next = Node(val)
def printList(self):
curr = self.head
while curr:
print curr.data
curr = curr.next
def reverse_ll(self):
if self.head is None:
return None
prev = None
cur = self.head
nxt = self.head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
self.head = prev
def reverse_k_elements(self, k):
def _reverse_k_elements(head, k):
prev = None
cur = head
nxt = head
count = 0
while cur and count < k:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
count += 1
if nxt is not None:
head.next = _reverse_k_elements(nxt, k)
return prev
self.head = _reverse_k_elements(self.head, k)
class CircularLinkedList():
def __init__(self):
self.head = None
def add(self, val):
if self.head is None:
self.head = Node(val)
self.head.next = self.head
else:
if self.head.next == self.head:
self.head.next = Node(val)
self.head.next.next = self.head
else:
curr = self.head
while curr.next != self.head :
curr = curr.next
curr.next = Node(val)
curr.next.next = self.head
def printList(self):
if self.head is None:
print None
else:
print self.head.data
if self.head.next is None:
print self.head.data
else:
curr = self.head.next
while curr != self.head:
print curr.data
curr = curr.next
def insertNodeIntoSortedLinkedList(self, val):
if self.head is None:
return False
else:
curr = self.head
if val < curr.data:
while curr.next != self.head:
curr = curr.next
curr.next = Node(val)
curr.next.next = self.head
self.head = curr.next
else:
while curr.next.data < val and curr.next != self.head:
curr=curr.next
temp = curr.next
curr.next = Node(val)
curr.next.next = temp
a = LinkedList()
a.add(1)
a.add(2)
a.add(3)
a.add(4)
a.add(5)
a.add(6)
a.add(7)
a.add(8)
a.reverse_k_elements(3)
a.printList() |
def isPalindromePermutation(string):
myMap = {}
for x in string:
if x not in myMap:
myMap[x] = 1
else:
myMap[x] = myMap[x] + 1
isOdd = False
print myMap
for m in myMap:
if myMap[m] %2 != 0:
if isOdd == True:
return False
isOdd = True
return True
print isPalindromePermutation('taaccocat')
|
def edit_distance(s1, s2, m, n, memo):
print "edit_distance for ", s1[m-1], s2[n-1]
if not m:
return n
if not n:
return m
if s1[m-1] == s2[n-1]:
return edit_distance(s1, s2, m-1, n-1, memo)
if (s1, s2) not in memo and (s2, s1) not in memo:
memo[(s1, s2)] = 1 + min( edit_distance(s1, s2, m, n-1, memo),
edit_distance(s1, s2, m-1, n, memo),
edit_distance(s1,s2, m-1, n-1, memo)
)
return memo[(s1, s2)]
s1 = "bridge"
s2 = "ebridg"
print edit_distance(s1, s2, len(s1), len(s2), {}) |
def fruit_basket(arr):
visited = set()
visited.add(arr[0])
queue = [(arr[0], 1)]
totalCount = 1
for i in range(1, len(arr)):
if arr[i] in visited:
if len(visited) < 2:
visited.add(arr[i])
totalCount += 1
queue.append(arr[i], 1)
else:
ele, count = queue.pop(0)
totalCount -= count
queue(arr[i], 1)
pass
arr = [1,2,1,3,4,3,4,5]
print fruit_basket(arr)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 17:15:37 2019
@author: Junya
"""
def insertionsort(A):
for j in range(2,len(A)):
key = A[j]
i = j-1
while (i > 0) and key < A[i]:
A[i+1]=A[i]
i=i-1
A[i+1] = key
return A
if __name__=="__main__":
x = [5,2,4,6,1,3]
insertionsort(x)
print (x)
|
import numpy as np
import nltk
# nltk.download('punkt')
from nltk.stem.porter import PorterStemmer
stemmer = PorterStemmer()
def tokenize(sentence):
"""
split sentence into array of words/tokens
a token can be a word or punctuation character, or number
"""
return nltk.word_tokenize(sentence)
def stem(word):
"""
stemming = find the root form of the word
examples:
words = ["organize", "organizes", "organizing"]
words = [stem(w) for w in words]
-> ["organ", "organ", "organ"]
"""
return stemmer.stem(word.lower())
def bag_of_words(tokenized_sentence, words):
"""
return bag of words array:
1 for each known word that exists in the sentence, 0 otherwise
example:
sentence = ["hello", "how", "are", "you"]
words = ["hi", "hello", "I", "you", "bye", "thank", "cool"]
bog = [ 0 , 1 , 0 , 1 , 0 , 0 , 0]
"""
# stem each word
sentence_words = [stem(word) for word in tokenized_sentence]
# initialize bag with 0 for each word
bag = np.zeros(len(words), dtype=np.float32)
for idx, w in enumerate(words):
if w in sentence_words:
bag[idx] = 1
return bag
#Pre-processing Demo
sentence="Hi, Our project is on Python Chatbot :)"
print(sentence)
stemmed_words=[]
tokenized_sentence=tokenize(sentence)
print("After Tokenising")
print(tokenized_sentence)
for i in tokenized_sentence:
stemmed_words.append(stem(i))
print("After Stemming")
print(stemmed_words)
all_words=["hello","hi","our", "semester","project","python","chatbot"]
bag=bag_of_words(tokenized_sentence,all_words)
print("all words")
print(all_words)
print("bag of words:")
print(bag)
input()
|
"""
Вам дан шаблон для функции test_substring , которая принимает два значения: full_string и substring.
Функция должна проверить вхождение строки substring в строку full_string с помощью оператора assert и, в случае несовпадения, предоставить исчерпывающее сообщение об ошибке.
"""
def test_substring(full_string, substring):
assert substring in full_string, f"expected '{substring}' to be substring of '{full_string}'"
if __name__ == '__main__':
test_substring('fulltext', 'some_value')
|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 19:49:45 2020
@author: omar
"""
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
df = pd.read_csv("college_datav3.csv")
# Display a regression plot for Tuition
sns.regplot(data=df,
y='Tuition',
x="SAT_AVG_ALL",
marker='^',
color='g')
plt.show()
plt.clf()
# Display the residual plot
sns.residplot(data=df,
y='Tuition',
x="SAT_AVG_ALL",
color='g')
plt.show()
plt.clf()
# Plot a regression plot of Tuition and the Percentage of Pell Grants
sns.regplot(data=df,
y='Tuition',
x="PCTPELL")
plt.show()
plt.clf()
# Create another plot that estimates the tuition by PCTPELL
sns.regplot(data=df,
y='Tuition',
x="PCTPELL",
x_bins=5)
plt.show()
plt.clf()
# The final plot should include a line using a 2nd order polynomial
sns.regplot(data=df,
y='Tuition',
x="PCTPELL",
x_bins=5,
order=2)
plt.show()
plt.clf()
# Create a scatter plot by disabling the regression line
sns.regplot(data=df,
y='Tuition',
x="UG",
fit_reg=False)
plt.show()
plt.clf()
# Create a scatter plot and bin the data into 5 bins
sns.regplot(data=df,
y='Tuition',
x="UG",
x_bins=5)
plt.show()
plt.clf()
# Create a regplot and bin the data into 8 bins
sns.regplot(data=df,
y='Tuition',
x="UG",
x_bins=8)
plt.show()
plt.clf()
# Create FacetGrid with Degree_Type and specify the order of the rows using row_order
g2 = sns.FacetGrid(df,
row="Degree_Type",
row_order=['Graduate', 'Bachelors', 'Associates', 'Certificate'])
# Map a pointplot of SAT_AVG_ALL onto the grid
g2.map(sns.pointplot, 'SAT_AVG_ALL')
# Show the plot
plt.show()
plt.clf()
# Create a factor plot that contains boxplots of Tuition values
sns.factorplot(data=df,
x='Tuition',
kind='box',
row='Degree_Type')
plt.show()
plt.clf()
# Create a facetted pointplot of Average SAT_AVG_ALL scores facetted by Degree Type
sns.factorplot(data=df,
x='SAT_AVG_ALL',
kind='point',
row='Degree_Type',
row_order=['Graduate', 'Bachelors', 'Associates', 'Certificate'])
plt.show()
plt.clf()
degree_ord = ['Graduate', 'Bachelors', 'Associates']
# Create a FacetGrid varying by column and columns ordered with the degree_order variable
g = sns.FacetGrid(df, col="Degree_Type", col_order=degree_ord)
# Map a scatter plot of Undergrad Population compared to PCTPELL
g.map(plt.scatter , 'UG', 'PCTPELL')
plt.show()
plt.clf()
# Re-create the plot above as an lmplot
sns.lmplot(data=df,
x='UG',
y='PCTPELL',
col="Degree_Type",
col_order=degree_ord)
plt.show()
plt.clf()
inst_ord= ['Public', 'Private non-profit']
# Create an lmplot that has a column for Ownership, a row for Degree_Type and hue based on the WOMENONLY column
sns.lmplot(data=df,
x='SAT_AVG_ALL',
y='Tuition',
col="Ownership",
row='Degree_Type',
row_order=['Graduate', 'Bachelors'],
hue='WOMENONLY',
col_order=inst_ord)
plt.show()
plt.clf()
|
# Import and initialize the pygame library
import pygame, sys, os
#A05.1 Mika Morgan
# This is a Python game similar to agar.io. This first part sets up the game window based on user input
# passed in as command line arguments. The user can designate the window title, screen size, background image,
# sprite image, and sprite size for the player. A GUI window will spawn to the specified size and the specified
# background image will fill the screen (scaled to fit). A single player will spawn in the middle of the window,
# using the image and size passed in.The player can be moved using the up, down, left, and right arrow keys on the
# keyboard. Because this is a 2D game using a top-down perspective, the up and down arrows move the player's
# y position on the screen, and the left and right arrows move the player's x position on the screen.
# Function that reads in the command line parameters and returns them as a dictionary, split around the =
def mykwargs(argv):
'''
Processes argv list into plain args and kwargs.
Just easier than using a library like argparse for small things.
Example:
python file.py arg1 arg2 arg3=val1 arg4=val2 -arg5 -arg6 --arg7
Would create:
args[arg1, arg2, -arg5, -arg6, --arg7]
kargs{arg3 : val1, arg4 : val2}
Params with dashes (flags) can now be processed seperately
Shortfalls:
spaces between k=v would result in bad params
Returns:
tuple (args,kargs)
'''
args = []
kargs = {}
for arg in argv:
if '=' in arg:
key,val = arg.split('=')
kargs[key] = val
else:
args.append(arg)
return args,kargs
def usage():
# Params in square brackets are optional
# The kwargs function script needs key=value to NOT have spaces
print("Usage: python basic.py title=string img_path=string img_path=string width=int height=int [jsonfile=string]")
print("Example:\n\n\t python basic.py title='Game 1' bg_path=bg.jpg img_path=sprite.png width=640 height=480 \n")
sys.exit()
# Background function that creates the background image using the file path and screen
# sizes passed in as params. This function will be used to spawn groups of sprites in future
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
x = int(kwargs['width'], 10)
y = int(kwargs['height'], 10)
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file)
self.image = pygame.transform.scale(self.image, (x, y))
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
# Main function that creates background and sprite, controls movement, and checks for updates (keyboard entry)
def main(**kwargs):
# Initialize PyGame
pygame.init()
# Use the width and height passed into dictionary to get game window size
# Need to convert values from string to int, specify using base 10
x = int(kwargs['width'], 10)
y = int(kwargs['height'], 10)
# Use the Background function to create a background using the file path passed in as a parameter
# Position it at 0,0 (top left corner of game window), and scale it to fit window size
BackGround = Background(kwargs['bg_path'], [0,0])
# Create a player using the file path passed in as a parameter
# Set the initial size to the width and height passed in as parameters
# Since the dictionary values are passed in as strings, convert them to ints in base 10 to use as size
player = pygame.image.load(kwargs['img_path'])
player = pygame.transform.scale(player, (int(kwargs['player_start_x'], 10), int(kwargs['player_start_y'],10)))
# Because the player size will change throughout the game, we need functions to continuously check size
# This information will be used to set boundary windows (keep sprite on screen) and compare the player
# size to virus sizes or other player sizes (needed for "eating")
p_w = player.get_width()
p_h = player.get_height()
# Spawn the player in the middle of the game window
p_x = x / 2 - p_w
p_y = y / 2 - p_h
# Set the window title to what was passed in as a parameter
pygame.display.set_caption(kwargs['title'])
# Set up the drawing window using the width and height passed in as parameters
screen = pygame.display.set_mode([x,y])
screen_rect=screen.get_rect()
# Load and play background music. -1 means loop forever
pygame.mixer.music.load('bg.mp3')
pygame.mixer.music.play(-1)
# Game update. Run until the user asks to quit
running = True
while running:
# Check to see if the quit button was pressed
# If it is, break out of the game play loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Player movement based on keyboard entry
# Use the arrow keys to change the player's x and y location
# Need to use get_pressed() method instead of get events to allow for continuous movement
# (if the button is held down). The 2 represents the player speed
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]: p_y -= 2
if keys[pygame.K_LEFT]: p_x -= 2
if keys[pygame.K_DOWN]: p_y += 2
if keys[pygame.K_RIGHT]: p_x += 2
# Boundary check to keep the player on the screen. The screen boundary is 0-screen width and
# 0-screen height. If the player tries to go beyond one of these boundaries, reset their location
# to the boundary line. Subtract the player's width and height while checking the upper limits
# because the player location is based on the top, left corner. Offset the limit so the player
# can't go offscreen the distance of the player size.
if p_x > (x - p_w): p_x = x - p_w
if p_x < 0: p_x = 0
if p_y > (y - p_h): p_y = y - p_h
if p_y < 0: p_y = 0
# Draw / render the screen. Continuously draw the background to cover up images of old
# player locations. Blit the player after the screen so it is top layer (visible)
screen.blit(BackGround.image, BackGround.rect)
screen.blit(player, (p_x, p_y))
pygame.display.flip()
# Done! Time to quit.
pygame.quit()
if __name__=='__main__':
"""
This example has 7 required parameters, so after stripping the file name out of
the list argv, I can test the len() of argv to see if it has 7 params in it.
"""
argv = sys.argv[1:]
if len(argv) < 7:
print(len(argv))
usage()
args,kwargs = mykwargs(argv)
# Create the game window passing in the dictionary of command line arguments
main(**kwargs) |
# Import and initialize the pygame library
import pygame, sys, os, glob
#P01.3 Mika Morgan
# This is a Python game similar to agar.io. This second part expands on the game setup and player movement created in
# P01.2. The updated game code does the same as before, with the addition of a player animation. The planet player
# (used as an example sprite) now has an animated comet tail that follows behind the player. The tail grows as the player
# grows and fades as the player moves. The sample planet sprite provided will also turn to face the direction of movement,
# based on keyboard input. The player sprite spins when it hits a world border, in addition to displaying the red border wall.
# Function that reads in the command line parameters and returns them as a dictionary, split around the =
def mykwargs(argv):
'''
Processes argv list into plain args and kwargs.
Just easier than using a library like argparse for small things.
Example:
python file.py arg1 arg2 arg3=val1 arg4=val2 -arg5 -arg6 --arg7
Would create:
args[arg1, arg2, -arg5, -arg6, --arg7]
kargs{arg3 : val1, arg4 : val2}
Params with dashes (flags) can now be processed seperately
Shortfalls:
spaces between k=v would result in bad params
Returns:
tuple (args,kargs)
'''
args = []
kargs = {}
for arg in argv:
if '=' in arg:
key,val = arg.split('=')
kargs[key] = val
else:
args.append(arg)
return args,kargs
def usage():
# Params in square brackets are optional
# The kwargs function script needs key=value to NOT have spaces
print("Usage: python basic.py title=string img_path=string img_path=string width=int height=int [jsonfile=string]")
print("Example:\n\n\t python basic.py title='Game 1' bg_path=bg.jpg img_path=sprite.png width=640 height=480 \n")
sys.exit()
# Background function that creates the background image using the file path and screen
# sizes passed in as params. This function will be used to spawn groups of sprites in future
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
x = int(kwargs['width'], 10)
y = int(kwargs['height'], 10)
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file)
self.image = pygame.transform.scale(self.image, (x * 5, y * 5))
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
# Sprite function that creates the player sprite and comet tail animation using the images in the folder
# file path passed in as params. It includes functions to get a sprite's width and height, and play all
# images in succession. This is used to loop the comet tail animation, and spin the player sprite
class BasicSprite(pygame.sprite.Sprite):
def __init__(self, folder_name):
super(BasicSprite, self).__init__()
self.images = []
for image in glob.glob('./'+ folder_name +'/*.png'):
self.images.append(pygame.image.load(image))
self.index = 0
self.image = self.images[self.index]
def update(self):
self.index += 1
if self.index >= len(self.images):
self.index = 0
self.image = self.images[self.index]
def get_width(self):
p_x = self.image.get_width()
return p_x
def get_height(self):
p_y = self.image.get_height()
return p_y
# Main function that creates background and sprite, controls movement, and checks for updates (keyboard entry)
def main(**kwargs):
# Initialize PyGame
pygame.init()
# Use the width and height passed into dictionary to get game window size
# Need to convert values from string to int, specify using base 10
x = int(kwargs['width'], 10)
y = int(kwargs['height'], 10)
# Create variables to hold "camera position" for part of game world to display
camX = 0
camY = 0
# Create colors for the world border alerts and empty background padding
RED = (255,0,0)
BLACK = (0,0,0)
# Use the Background function to create a background using the file path passed in as a parameter
# Position it offset from the world boundary so the camera can stay with player, even on world edge
empty_surface = pygame.Surface((1000, 1000))
empty_surface.fill(BLACK)
BackGround = Background(kwargs['bg_path'], [x/2,y/2])
# Create a player using the file path passed in as a parameter
# Set the initial size to the width and height passed in as parameters
# Since the dictionary values are passed in as strings, convert them to ints in base 10 to use as size
player = BasicSprite(kwargs['img_path'])
player.image = player.images[4]
player.image = pygame.transform.scale(player.image, (int(kwargs['player_start_x'], 10), int(kwargs['player_start_y'],10)))
# Because the player size will change throughout the game, we need functions to continuously check size
# This information will be used to set boundary windows (keep sprite on screen) and compare the player
# size to virus sizes or other player sizes (needed for "eating")
p_w = player.get_width()
p_h = player.get_height()
# Spawn the player in the middle of the game window
p_x = x / 2 - p_w
p_y = y / 2 - p_h
# Create the comet tail animation sprite
# Set the initial x and y offsets to 0
comet = BasicSprite('comet_tail')
com_X = 0
com_Y = 0
# Set the window title to what was passed in as a parameter
pygame.display.set_caption(kwargs['title'])
# Set up the drawing window using the width and height passed in as parameters
screen = pygame.display.set_mode([x,y])
# Load and play background music. -1 means loop forever
pygame.mixer.music.load('bg.mp3')
pygame.mixer.music.play(-1)
# Game update. Run until the user asks to quit
running = True
while running:
# Reset the comet tail offset each loop
com_X = 0
com_Y = 0
# Check to see if the quit button was pressed
# If it is, break out of the game play loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Player movement based on keyboard entry
# Use the arrow keys to change the player's x and y location
# Need to use get_pressed() method instead of get events to allow for continuous movement
# (if the button is held down). The 2 represents the player speed
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
p_y -= 2
camY -= 2
com_Y += p_h
player.image = player.images[4]
if keys[pygame.K_LEFT]:
p_x -= 2
camX -= 2
com_X += p_w
player.image = player.images[2]
if keys[pygame.K_DOWN]:
p_y += 2
camY += 2
com_Y -= p_h
player.image = player.images[0]
if keys[pygame.K_RIGHT]:
p_x += 2
camX += 2
com_X -= p_w
player.image = player.images[6]
if keys[pygame.K_UP] and keys[pygame.K_LEFT]:
player.image = player.images[3]
if keys[pygame.K_UP] and keys[pygame.K_RIGHT]:
player.image = player.images[5]
if keys[pygame.K_DOWN] and keys[pygame.K_LEFT]:
player.image = player.images[1]
if keys[pygame.K_DOWN] and keys[pygame.K_RIGHT]:
player.image = player.images[7]
x = x * 5
y = y * 5
# Create boolean flags to hold whether or not the player is hitting a world border
# These will be used to make the red border walls appear, and play hitting world
# edge animation (spin the planet sprite)
x_min = False
x_max = False
y_min = False
y_max = False
# Boundary check to keep the camera within the world. The screen boundary is 0-screen width and
# 0-screen height. If the camera tries to go beyond one of these boundaries, reset it's location
# to the boundary line. Subtract the screen's width and height while checking the upper limits.
if camX < (-x/10): camX = (-x/10)
if camX > (x - (x/5)): camX = x - (x/5)
if camY < (-y/10): camY = (-y/10)
if camY > (y - (y/5)): camY = y - (y/5)
# Boundary check to keep the player on the screen. The screen boundary is 0-screen width and
# 0-screen height. If the player tries to go beyond one of these boundaries, reset their location
# to the boundary line. Subtract the player's width and height while checking the upper limits
# because the player location is based on the top, left corner. Offset the limit so the player
# can't go offscreen the distance of the player size.
if p_x > (x - p_w):
p_x = x - p_w
x_max = True
if p_x < 0:
p_x = 0
x_min = True
if p_y > (y - p_h):
p_y = y - p_h
y_max = True
if p_y < 0:
p_y = 0
y_min = True
x = x / 5
y = y / 5
# The update function causes all 28 frames to play in succession, making the comet tail animation loop forever
# The planet sprite must be re-scaled because the frame is changed depending on the direction
comet.update()
player.image = pygame.transform.scale(player.image, (int(kwargs['player_start_x'], 10), int(kwargs['player_start_y'],10)))
# If the player is hitting a world boundary, play all sprite frames in succession, to give the appearance of spinning
# The images have to be re-scaled again, because the frame is changed
if x_min or x_max or y_min or y_max:
player.update()
player.image = pygame.transform.scale(player.image, (int(kwargs['player_start_x'], 10), int(kwargs['player_start_y'],10)))
# Draw / render the screen. Continuously draw the background to cover up images of old
# player locations. Blit the player after the screen so it is top layer (visible)
screen.blit(empty_surface, (0, 0))
screen.blit(BackGround.image, (0 - camX,0 - camY))
screen.blit(comet.image,(((p_x - p_w * 2) - camX + com_X),((p_y - p_h) - camY + com_Y)))
screen.blit(player.image,(p_x - camX,p_y - camY))
## If the player is hitting a world border, display a red border line
if x_min: pygame.draw.rect(screen,RED,(x/2,(0-y/2),5,y * 5))
if y_min: pygame.draw.rect(screen,RED,((0-x/2),y/2,x * 5,5))
if x_max: pygame.draw.rect(screen,RED,(x-5,(0-y/2),5,y*5))
if y_max: pygame.draw.rect(screen,RED,((0-x/2),y-5,x*5,5))
pygame.display.flip()
# Done! Time to quit.
pygame.quit()
if __name__=='__main__':
"""
This example has 7 required parameters, so after stripping the file name out of
the list argv, I can test the len() of argv to see if it has 7 params in it.
"""
argv = sys.argv[1:]
if len(argv) < 7:
print(len(argv))
usage()
args,kwargs = mykwargs(argv)
# Create the game window passing in the dictionary of command line arguments
main(**kwargs) |
import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: document identifier
# value: document contents
matrix = record[0]
value = record[3]
if matrix == 'a':
for k in xrange(0,5):
mr.emit_intermediate((record[1] , k), record)
elif matrix == 'b':
for i in xrange(0,5):
mr.emit_intermediate((i ,record[2]), record)
def reducer(key, list_of_values):
# key: word
# value: list of occurrence counts
total = 0
emit = False
for a in list_of_values:
if a[0] == 'a' and a[1] == key[0]:
for b in list_of_values:
if b[0] == 'b' and b[2] == key[1] and a[2] == b[1]:
total += a[3] * b[3]
emit = True
if emit:
mr.emit((key[0], key[1], total))
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
# IS602 Week 3 Assignment
# Paul Garaud
import Tkinter, tkFileDialog
import re
root = Tkinter.Tk()
root.withdraw()
def load_data():
"""
Load csv specified in pop-up dialog into memory
:return: list of elements for each row in csv
"""
file_path = tkFileDialog.askopenfilename()
out = None
if file_path != '':
try:
openfile = open(file_path, 'r')
out = [line.strip().split(',') for line in openfile]
except IOError:
print 'File could not be loaded.'
finally:
openfile.close()
return out
def create_data_structure(data, valid_dict, colnames=None):
"""
Create hash of column name -> element i in each row in data; assigns numbers if colnames omitted
:param data: list of lists
:valid_dict: a dictionary mapping columns to tuple of valid values
:param colnames: iterable with column names
:return: dictionary
"""
if colnames is None:
colnames = range(len(data[0]))
out = {colnames[i]: [] for i in xrange(len(colnames))}
for line in data:
for col in colnames:
value = line[colnames.index(col)]
check_value(col, value, valid_dict)
out[col] += [value, ]
return out
def check_value(col_name, value, valid_dict):
"""
Validates data and throws error if invalid.
:param col_name: column value appears in
:param value: value to check
:valid_dict: a dictionary mapping columns to tuple of valid values
:return:
"""
if value not in valid_dict[col_name]:
raise ValueError("'{0}' is not a valid value in column '{1}'.".format(
value, col_name
))
def check_keys(data, keys):
"""
Validates data dict keys (ie columns); raises KeyError if invalid
:param data: dict
:param keys: str or iterable
:return: None
"""
if type(keys) is str:
keys = [keys, ]
for k in keys:
if k not in data.keys():
raise KeyError('{0} is not a valid column name.'.format(k))
def save_data(data, col_order=None):
"""
Saves the data to a CSV file
:param data: a dictionary object mapping column names -> lists of data
:return: None
"""
if type(data) is not dict:
raise TypeError('Data must be a dictionary, not {0}'.format(type(data)))
if col_order is None:
cols = data.keys()
else:
check_keys(data, col_order)
cols = col_order
file_path = tkFileDialog.asksaveasfilename()
if file_path == '':
return None
try:
save_file = open(file_path, 'w')
for row in xrange(len(data[cols[0]])):
record = ''
for col in cols:
record += '{0},'.format(data[col][row])
save_file.write(record + '\n')
finally:
save_file.close()
def sort_rows(data, sort_on, order='desc'):
"""
Order rows in data on the sort_on column name ordered on order argument
:param data: a dictionary object mapping column names -> lists of data
:param sort_on: column name to sort on
:param order: 'asc' or 'desc'
:return: dict
"""
val_map = {'vhigh': 3, 'high': 2, 'med': 1, 'low': 0,
'5more': 5, 'more': 5,
'big': 2, 'med': 1, 'small': 0}
check_keys(data, sort_on) # check column names for validity
tmp_data = []
i = 0
for element in data[sort_on]:
if re.match(r'^[0-9]$', element):
value = int(element)
else:
value = val_map[element]
tmp_data.append((value, i, element))
i += 1
tmp_data.sort(reverse=order == 'desc')
index = [a[1] for a in tmp_data]
sort_data = {}
for col in data.keys():
sort_data[col] = [data[col][ind] for ind in index]
return sort_data
def find_rows(data, cols, regex=None):
"""
Returns rows for specified columns matching regex expression
nb regex must match for ALL columns in a record
:param data: a dictionary object mapping column names -> lists of data
:param cols: one (string) or more columns (iterable) to search within
:param regex: regex pattern
:return: dict
"""
check_keys(data, cols) # check column names for validity
pattern = re.compile(regex)
# if single col, make iterable
if type(cols) is str:
cols = [cols, ]
rows = len(data[cols[0]])
return_rows = [] # store row qualifying indices
for i in xrange(rows):
for col in cols:
match = re.search(pattern, data[col][i])
if not match:
if i in return_rows:
return_rows.remove(i)
break # no need to check other columns--this row is out
elif match and i not in return_rows:
return_rows.append(i)
return_data = {}
for col in data.keys():
return_data[col] = []
for j in return_rows:
return_data[col] += [data[col][j]]
return return_data
def print_rows(data, col_order=None, nrows=None):
"""
Prints rows of the data set passed in the data arg
:param data: a dictionary object mapping column names -> lists of data
:param col_order: a list of columns defining order in which to print
:param nrows: limit output to first n rows; None -> print all
:return: None
"""
if col_order is None:
columns = data.keys()
else:
check_keys(data, col_order)
columns = col_order
# ensure that the formatting of the output is aligned properly
template = "{0}{1: >12}{2: >12}{3: >12}{4: >12}{5: >12}"
print template.format(*tuple(columns))
for i in xrange(len(data[columns[0]])):
if nrows is not None and nrows <= i:
break
print template.format(*tuple([data[col][i] for col in columns]))
def select_rows(data, sort_on=None, which=None, num=5, order='desc',
rcols=None, regex=None, col_order=None):
"""
Calls sort_rows, find_rows (if necessary), & print_rows using args passed
:param data: a dictionary object mapping column names -> lists of data
:param which: return 'top' or 'bottom' num columns; else return all
:param num: if which is specified, limits results to num records
:param sort_on: column name to sort on
:param order: 'asc' or 'desc'
:param rcols: one (string) or more columns (iterable) to search within;
if None, regex must match all columns to return record
:param regex: regex pattern
:param col_order: column order of printed output
:returns: None
"""
# find subset of columns (if rcols/regex specified)
tmp_data = data
if regex is not None:
if rcols is not None:
check_keys(data, rcols)
else:
rcols = data.keys()
tmp_data = find_rows(data, rcols, regex)
# sort
if sort_on is not None:
check_keys(data, sort_on)
tmp_data = sort_rows(tmp_data, sort_on, order)
# top/bottom
if num < 1:
which = None
if which == 'top':
tmp_data = {col: tmp_data[col][:num] for col in data.keys()}
elif which == 'bottom':
tmp_data = {col: tmp_data[col][-num:] for col in data.keys()}
# print
print_rows(tmp_data, col_order)
return tmp_data
if __name__ == '__main__':
raw_data = load_data()
columns = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety']
data_dict = {'buying': ('low', 'med', 'high', 'vhigh'),
'maint': ('low', 'med', 'high', 'vhigh'),
'doors': ('2', '3', '4', '5more'),
'persons': ('2', '4', 'more'),
'lug_boot': ('small', 'med', 'big'),
'safety': ('low', 'med', 'high')}
cars = create_data_structure(raw_data, data_dict, colnames=columns)
# a. Print to the console the top 10 rows of the data sorted by 'safety'
# in descending order
select_rows(cars, sort_on='safety', order='desc', which='top', num=10,
col_order=columns)
# b. Print to the console the bottom 15 rows of the data sorted by 'maint'
# in ascending order
select_rows(cars, sort_on='maint', order='asc', which='bottom', num=15,
col_order=columns)
# c. Print to the console all rows that are high or vhigh in fields
# 'buying', 'maint', and 'safety', sorted by 'doors' in ascending order.
select_rows(cars, sort_on='doors', order='asc',
rcols=['buying', 'maint', 'safety'],
regex=r'v?high',
col_order=columns)
# d. Save to a file all rows (in any order) that are: 'buying': vhigh,
# 'maint': med, 'doors': 4, and 'persons': 4 or more.
to_save = select_rows(cars, rcols='buying', regex='vhigh')
to_save = select_rows(to_save, rcols='maint', regex='med')
to_save = select_rows(to_save, rcols='doors', regex='4')
to_save = select_rows(to_save, rcols='persons', regex='(4|more)')
save_data(to_save, col_order=columns)
|
'''
This class contains code to implement the different types of noises that we encounter
while learning Digital Communication.
'''
# Works only with integral values of starting_time, ending_time and time_period
# Learn why does samples taken from gaussian function consitutes a white_noise.
# Next I HAVE TO IMPLEMENT A WAY TO CALCULATE THE POWER SPECTRAL DENSITY OF THE WHITE_NOISE
# FROM SAMPLES TAKEN BY THE white_noise function
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import time
class GaussianNoise(object):
def __init__(self, standard_deviation, starting_time, ending_time, time_period):
# For a white gaussian Noise the value of mean is always zero
self.pi = np.pi
self.standard_deviation = standard_deviation
self.starting_time = starting_time
self.ending_time = ending_time
self.time_period = time_period
# This func makes samples of white gaussian noise in a given timeperiod
# loc defines mean, scale defines standard deviation
def gaussian_white_noise(self, number_of_samples, scaling_factor):
samples = []
for _ in range (int((self.ending_time - self.starting_time)/self.time_period)):
samples.append(np.random.normal(loc = 0, scale = self.standard_deviation, size = number_of_samples))
return (np.dot(scaling_factor,samples).flatten() ,np.append(np.dot(scaling_factor, samples).flatten() ,
np.random.normal(loc = 0, scale = self.standard_deviation))
)
# SAMPLES ARE OF THE TYPE np.ndarray
def print_gaussian_white_noise_samples(self, number_of_samples, scaling_factor):
samples = self.gaussian_white_noise(number_of_samples, scaling_factor)[1]
print(len(samples))
print(samples)
def counter(self, number):
count = 0
while number % 10 == 0:
count += 1
number /=10
return count
def sampling_frequency(self, number_of_samples):
timeStampsIncrements = (self.time_period/number_of_samples)
timeStamps = []
for i in range(int((self.ending_time-self.starting_time)/self.time_period)):
x = self.starting_time + self.time_period*i
while(float(format(x, '.'+'{}'.format(self.counter(number_of_samples))+'f')) < self.starting_time + self.time_period*(i+1)):
timeStamps.append(float(format(x, '.'+'{}'.format(self.counter(number_of_samples))+'f')))
x += timeStampsIncrements
timeStamps.append(self.ending_time)
return timeStamps
def seaborn_plot_gaussian(self, number_of_samples, scaling_factor):
df = pd.DataFrame(dict(TimeStamps = self.sampling_frequency(number_of_samples),
NoiseAmplitude = self.gaussian_white_noise(number_of_samples, scaling_factor)[1]))
g = sns.relplot(x= "TimeStamps", y= "NoiseAmplitude", kind="line", data= df)
plt.grid(color='black', linestyle='-', linewidth=.5)
plt.title('GAUSSIAN WHITE NOISE WITH S.D = {0:.2f}'.format(scaling_factor*self.standard_deviation/3, '.2f'))
plt.show(g)
if __name__ == "__main__":
NoiseObject = GaussianNoise(standard_deviation = 1, starting_time = -100, ending_time = 100, time_period = 2)
# print(len(NoiseObject.gaussian_white_noise(number_of_samples = 100,scaling_factor = 1)))
# print(len(NoiseObject.sampling_frequency(number_of_samples = 100)))
NoiseObject.seaborn_plot_gaussian(number_of_samples = 2, scaling_factor = 1)
# def plot():
# WhiteNoiseObject = GaussianNoise(1.2, 'GAUSSIAN WHITE NOISE')
# print("#################################################################################")
# print(WhiteNoiseObject.name)
# print()
# number_of_samples = int(input('Total number of samples \n'))
# print("#################################################################################")
# WhiteNoiseObject.plot_gaussian_white_noise(number_of_samples,scaling_factor = 1)
# def print_samples():
# WhiteNoiseObject = GaussianNoise (1.2, 'GAUSSIAN WHITE NOISE')
# print("#################################################################################")
# print(WhiteNoiseObject.name)
# print()
# number_of_samples = int(input('Total number of samples \n'))
# scaling_factor = int(input('Enter the scaling factor to increase or decrease the amplitude of noise '))
# print("#################################################################################")
# WhiteNoiseObject.print_gaussian_white_noise_samples(number_of_samples, scaling_factor )
# def seaborn_plot():
# WhiteNoiseObject = GaussianNoise(0.9, 'GAUSSIAN WHITE NOISE')
# print("#################################################################################")
# print(WhiteNoiseObject.name)
# print()
# number_of_samples = int(input('Total number of samples \n'))
# scaling_factor = int(input('Enter the scaling factor to increase or decrease the amplitude of noise '))
# print("#################################################################################")
# WhiteNoiseObject.seaborn_plot_gaussian(number_of_samples, scaling_factor)
# seaborn_plot()
|
import sqlite3
import DB1
import datetime
def newUser(userName, fName, lName, mobile, dOB, sQues, sAns, password):
conn = sqlite3.connect("Username_Passwords.sqlite")
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS Username_Passwords_DB
(Username text, Firstname text, Lastname text, Mobile text, Date_Of_Birth text, SecurityQuestion text, SQAnswer text, Password text, Last_Login text)''')
cur.execute('''INSERT INTO Username_Passwords_DB VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)''', (userName, fName, lName, mobile, dOB, sQues, sAns, password, "None"))
conn.commit()
conn.close()
return
def deleteUser(userName):
conn = sqlite3.connect("Username_Passwords.sqlite")
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS Username_Passwords_DB
(Username text, Password text)''')
cur.execute('''DELETE FROM Username_Passwords_DB WHERE Username=?''', (userName,))
conn.commit()
conn.close()
DB1.deleteData(userName)
return
def updatePassword(userName, password):
conn = sqlite3.connect("Username_Passwords.sqlite")
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS Username_Passwords_DB
(Username text, Password text)''')
cur.execute('''UPDATE Username_Passwords_DB SET Password=? WHERE Username=?''', (password, userName))
conn.commit()
conn.close()
return
def getDetails(userName):
conn = sqlite3.connect("Username_Passwords.sqlite")
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS Username_Passwords_DB
(Username text, Password text)''')
cur.execute('''SELECT * FROM Username_Passwords_DB WHERE Username=?''', (userName,))
details = cur.fetchall()
if len(details) == 0:
return []
else:
return details[0]
def updateLastLogin(userName):
conn = sqlite3.connect("Username_Passwords.sqlite")
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS Username_Passwords_DB
(Username text, Password text)''')
date = datetime.datetime.now()
date = str(date)[:16]
cur.execute('''UPDATE Username_Passwords_DB SET Last_Login=? WHERE Username=?''', (date, userName))
conn.commit()
conn.close()
return
|
# Числа
# В некоторой школе занятия начинаются в 9:00. Продолжительность урока — 45 минут, после 1-го, 3-го,
# 5-го и т.д. уроков перемена 5 минут, а после 2-го, 4-го, 6-го и т.д. — 15 минут. Дан номер урока number (число от 1
# до 10). Определите когда заканчивается указанный урок. Выведите в переменную result время окончания урока в часах и
# минутах (HH:MM) тип переменной str.
#
# Пример входных данных:
# number = 7.
#
# Пример выходных данных:
# result = '15:15'.
# number - номер урока
mm = number * 45 + (number // 2) * 5 + ((number + 1) // 2 - 1) * 15
result = "{0:0=2d}".format(9 + mm // 60) + ':' + "{0:0=2d}".format(mm % 60)
#
# Обратная связь с человеком
# Оценщик присвоил 2,50/2,50 очков. |
'''
dic={"a":"apple","b":"banana","c":"cat","d":"dog"}
print("A for",dic["a"])
'''
'''
fruits={"a":"apple","b":"banana","c":"coconut","d":"durian"}
print("Keys are "+str(fruits.keys()))
print("Content is "+str(fruits.values()))
'''
products=[]
def AddProduct(prod):
global products
products.append(prod)
num=int(input("number of product: "))
for i in range(num):
name=input("name: ")
model=input("model: ")
company=input("company: ")
dict={}
dict.update({"name": name})
dict.update({"model": model})
dict.update({"company": company})
AddProduct(dict)
|
x=int(input("x="))
if((x%3==0) | (x%5==0) | (x%7==0)):
print("The number can divide by 3,5,7")
elif((x%2==0) | (x%4==0) | (x%6==0)):
print("The number can divide by 2,4,6")
else:
print("0") |
def Search(txt,w):
words=txt.split(" ")
for word in words:
if word.lower() == w.lower():
return True
return False
def CapWord(txt):
words=txt.split(" ")
newWords=[]
for i in range(len(words)):
newWords.append(words[i].capitalize())
return " ".join(newWords)
words="i learn PYTHON language from home."
words2=" Online study "
lWords=words.split(" ")
print("string: ",words)
print("string length: ", len(words))
print("string index 0: ", words[0])
print("string range: ", words[0:7])
print("string Capitalize: ", words.capitalize())
print("string lower case: ", words.lower())
print("string lower case: ", words.upper())
print("string cut space on left:"+words2.lstrip()+">>>")
print("string cut space on left:"+words2.rstrip()+">>>")
print("string cut space on left:"+words2.strip()+">>>")
print("string to list: ", lWords)
print("list to string: ", ",".join(lWords))
print("replace string: ", words.replace("from", "at"))
print("search text: ", Search(words,"lear"))
print("Capital letter: ", CapWord(words))
print("Aasdfsd 2323 werw#$%^&*~234/".isascii())
#chr support value from 0 to 1114111
print(ord("€"), ord("æ"), ord("I"), ord("i"))
print(chr(29), chr(6016), chr(1114111))
print("chr support value from 0 to 1114111".title() )
print("Chr support valuE from 0 tO 1114111 ".swapcase())
#print(int('0x110000',16))
#IBAN: 000-890-908-789
#palindrome: level kayak mom refer noon rotor moon value |
secret = 4
guess = int(input("Enter number: "))
if secret == guess:
print("You win!")
else:
print("You lose!")
|
import random
import math
def getRandom():
return random.uniform(0.0,1.0)
class Point:
def __init__(self):
self.first = getRandom()
self.last = getRandom()
def isInCircle(self):
squaredFirst = self.first*self.first
squaredLast = self.last*self.last
d = math.sqrt(squaredFirst + squaredLast)
return d<1
def estimate_pi():
list = []
total_count = 1000000
for i in range(0,total_count):
list.append(Point())
in_circle_count = 0
for p in list:
if p.isInCircle(): in_circle_count +=1
print(4 * in_circle_count / total_count)
estimate_pi()
|
import numpy as np
import pandas as pd
import question_02
def count_movies_with_genre(movies, genre):
return len(movies[movies["genres"].str.contains(genre)])
def count_movies_with_release_year(movies, release_year):
return len(movies[movies["release_year"] == release_year])
def count_thriller_with_release_year(movies, genre, year):
is_genre = movies["genres"].str.contains(genre)
is_year = movies["release_year"] == year
return len(movies[(is_genre) & (is_year)])
def main():
movies_df = pd.read_csv("./resources/movies.csv")
question_02.create_release_year_column(movies_df)
print(count_thriller_with_release_year(movies_df, "Thriller", 2016))
if __name__ == "__main__":
main() |
#!/usr/bin/env python
import math
import numpy as np
from . import linalg as la
from . import eulang
#Euler angle sequence: XYZ (world). First rotation about X, second rotation
#about Y, and the third rotation about Z axis of the world(i.e. fixed) frame.
#This is the same as the sequence used in Blender.
#In contrast, the XYZ sequence is understood in the Aerospace community as:
#First rotation about Z-axis, second rotation about Y-axis, and the third
#rotation about X-axis of the body frame.
#Axis_angle------------------------------------------------------------
def fix_axis_angle(axis, angle, normalize=True):
if normalize:
norm = np.linalg.norm(axis)
if not math.isclose(norm, 1.0, abs_tol=1e-14, rel_tol=1e-14):
axis /= norm
angle = math.fmod(angle, 2*math.pi)
if angle < 0.0:
angle = -angle
axis = -axis
if angle > math.pi:
angle = 2*math.pi - angle
axis = -axis
return (axis, angle)
def get_rand_axis_angle():
'''
Generates a random pair of axis-angle. The axis is a random vector from
the surface of a unit sphere. Algorithm from Allen & Tildesley p. 349.
'''
axis = np.zeros((3,))
#Generate angle: A uniform random number from [0.0, 2*pi)
angle = 2.0*math.pi*np.random.random()
while True:
#Generate two uniform random numbers from [-1, 1)
zeta1 = 2.0*np.random.random() - 1.0
zeta2 = 2.0*np.random.random() - 1.0
zetasq = zeta1**2 + zeta2**2
if zetasq <= 1.0:
break
rt = np.sqrt(1.0-zetasq)
axis[0] = 2.0*zeta1*rt
axis[1] = 2.0*zeta2*rt
axis[2] = 1.0 - 2.0*zetasq
return fix_axis_angle(axis, angle)
def axis_angle_to_quat(axis, angle):
w = math.cos(angle/2)
v = math.sin(angle/2)*axis
q = np.array([w, v[0], v[1], v[2]])
return normalize_quat(q)
def axis_angle_to_euler(axis, angle, seq='XYZ', world=True):
rotmat = get_rotmat_axis_angle(axis, angle)
euler = factorize_rotmat(rotmat, seq=seq, world=world)
return euler
def axis_angle_to_dcm(axis, angle):
dcm = get_shiftmat_axis_angle(axis, angle, forward=True)
return dcm
def any_to_axis_angle(orientation):
ori_repr = orientation['repr']
if ori_repr == 'quat':
quat = np.array(orientation['quat'])
axis, angle = quat_to_axis_angle(quat)
elif ori_repr == 'euler':
euler = np.array(orientation['euler'])
seq = orientation['seq']
world = orientation['world']
axis, angle = euler_to_axis_angle(euler, seq=seq, world=world)
elif ori_repr == 'axis_angle':
axis = np.array(orientation['axis'])
angle = orientation['angle']
elif ori_repr == 'dcm':
axis, angle = dcm_to_axis_angle(orientation['dcm'])
else:
raise ValueError(
'Unrecognized orientation repr {0}'.format(ori_repr))
return axis, angle
def rotate_vector_axis_angle(v, axis, angle):
'''
Rotates vectors about axis by angle.
'''
rotmat = get_rotmat_axis_angle(axis, angle)
return np.dot(v, rotmat.T)
def get_rotmat_axis_angle(axis, angle):
R = np.zeros((3,3))
sin = np.sin(angle)
cos = np.cos(angle)
icos = 1.0 - cos
R[0,0] = axis[0]*axis[0]*icos + cos
R[0,1] = axis[0]*axis[1]*icos - axis[2]*sin
R[0,2] = axis[0]*axis[2]*icos + axis[1]*sin
R[1,0] = axis[0]*axis[1]*icos + axis[2]*sin
R[1,1] = axis[1]*axis[1]*icos + cos
R[1,2] = axis[1]*axis[2]*icos - axis[0]*sin
R[2,0] = axis[2]*axis[0]*icos - axis[1]*sin
R[2,1] = axis[1]*axis[2]*icos + axis[0]*sin
R[2,2] = axis[2]*axis[2]*icos + cos
return R
def extract_axis_angle_from_rotmat(rotmat):
trace = np.trace(rotmat)
angle = math.acos((trace-1)/2)
if angle > 0:
if angle < math.pi:
u0 = rotmat[2,1] - rotmat[1,2]
u1 = rotmat[0,2] - rotmat[2,0]
u2 = rotmat[1,0] - rotmat[0,1]
else:
#Find the largest entry in the diagonal of rotmat
k = np.argmax(np.diag(rotmat))
if k == 0:
u0 = math.sqrt(rotmat[0,0]-rotmat[1,1]-rotmat[2,2]+1)/2
s = 1.0/(2*u0)
u1 = s*rotmat[0,1]
u2 = s*rotmat[0,2]
elif k == 1:
u1 = math.sqrt(rotmat[1,1]-rotmat[0,0]-rotmat[2,2]+1)/2
s = 1.0/(2*u1)
u0 = s*rotmat[0,1]
u2 = s*rotmat[1,2]
elif k == 2:
u2 = math.sqrt(rotmat[2,2]-rotmat[0,0]-rotmat[1,1]+1)/2
s = 1.0/(2*u2)
u0 = s*rotmat[0,2]
u1 = s*rotmat[1,2]
else:
u0 = 1.0
u1 = 0.0
u2 = 0.0
return fix_axis_angle(np.array([u0, u1, u2]), angle, normalize=True)
def shift_vector_axis_angle(v, axis, angle, forward=False):
shiftmat = get_shiftmat_axis_angle(axis, angle, forward=forward)
return np.dot(v, shiftmat.T)
def shift_tensor2_axis_angle(a, axis, angle, forward=False):
shiftmat = get_shiftmat_axis_angle(axis, angle, forward=forward)
return np.einsum('ip,jq,pq', shiftmat, shiftmat, a)
def shift_tensor3_axis_angle(a, axis, angle, forward=False):
shiftmat = get_shiftmat_axis_angle(axis, angle, forward=forward)
return np.einsum('ip,jq,kr,pqr', shiftmat, shiftmat, shiftmat, a)
def get_shiftmat_axis_angle(axis, angle, forward=False):
shiftmat = get_rotmat_axis_angle(-axis, angle)
if not forward:
shiftmat = shiftmat.T
return shiftmat
#Direction cosine matrix-----------------------------------------------
def dcm_from_axes(A, B):
'''
Returns the direction cosine matrix of axes(i.e. frame) B w.r.t.
axes(i.e. frame) A.
Parameters
----------
A : (3,3) ndarray
The rows of A represent the orthonormal basis vectors of frame A.
B : (3,3) ndarray
The rows of B represent the orthonormal basis vectors of frame B.
Returns
-------
(3,3) ndarray
The dcm of frame B w.r.t. frame A.
'''
return np.dot(B, A.T)
def dcm_to_quat(dcm):
mat = get_rotmat_dcm(dcm)
axis, angle = extract_axis_angle_from_rotmat(mat)
return axis_angle_to_quat(axis, angle)
def dcm_to_euler(dcm, seq='XYZ', world=True):
mat = get_rotmat_dcm(dcm)
euler = factorize_rotmat(mat, seq=seq, world=world)
return euler
def dcm_to_axis_angle(dcm):
mat = get_rotmat_dcm(dcm)
axis, angle = extract_axis_angle_from_rotmat(mat)
return (axis, angle)
def any_to_dcm(orientation):
ori_repr = orientation['repr']
if ori_repr == 'quat':
quat = np.array(orientation['quat'])
dcm = quat_to_dcm(quat)
elif ori_repr == 'euler':
euler = np.array(orientation['euler'])
seq = orientation['seq']
world = orientation['world']
dcm = euler_to_dcm(euler, seq=seq, world=world)
elif ori_repr == 'axis_angle':
axis = np.array(orientation['axis'])
angle = orientation['angle']
dcm = axis_angle_to_dcm(axis, angle)
elif ori_repr == 'dcm':
dcm = dcm_to_quat(orientation['dcm'])
else:
raise ValueError(
'Unrecognized orientation repr {0}'.format(ori_repr))
return dcm
def rotate_vector_dcm(v, dcm):
rotmat = get_rotmat_dcm(dcm)
return np.dot(v, rotmat.T)
def get_rotmat_dcm(dcm):
return dcm.T
def shift_vector_dcm(v, dcm, forward=False):
shiftmat = get_shiftmat_dcm(dcm, forward=forward)
return np.dot(v, shiftmat.T)
def shift_tensor2_dcm(a, dcm, forward=False):
shiftmat = get_shiftmat_dcm(dcm, forward=forward)
return np.einsum('ip,jq,pq', shiftmat, shiftmat, a)
def shift_tensor3_dcm(a, dcm, forward=False):
shiftmat = get_shiftmat_dcm(dcm, forward=forward)
return np.einsum('ip,jq,kr,pqr', shiftmat, shiftmat, shiftmat, a)
def get_shiftmat_dcm(dcm, forward=False):
shiftmat = dcm
if not forward:
shiftmat = shiftmat.T
return shiftmat
#Euler angle-----------------------------------------------------------
def factorize_rotmat(rotmat, seq='XYZ', world=True):
return eulang.factor_rotmat(rotmat, seq=seq, world=world)
def euler_to_euler(euler, seq, world, to_seq, to_world):
rotmat = get_rotmat_euler(euler, seq=seq, world=world)
return factorize_rotmat(rotmat, seq=to_seq, world=to_world)
def euler_to_quat(euler, seq='XYZ', world=True):
axis, angle = euler_to_axis_angle(euler, seq=seq, world=world)
return axis_angle_to_quat(axis, angle)
def euler_to_dcm(euler, seq='XYZ', world=True):
dcm = get_shiftmat_euler(euler, seq=seq, world=world, forward=True)
return dcm
def euler_to_axis_angle(euler, seq='XYZ', world=True):
rotmat = get_rotmat_euler(euler, seq=seq, world=world)
axis, angle = extract_axis_angle_from_rotmat(rotmat)
return (axis, angle)
def any_to_euler(orientation, to_seq, to_world):
ori_repr = orientation['repr']
if ori_repr == 'quat':
quat = np.array(orientation['quat'])
euler = quat_to_euler(quat, seq=to_seq, world=to_world)
elif ori_repr == 'euler':
euler = np.array(orientation['euler'])
seq = orientation['seq']
world = orientation['world']
euler = euler_to_euler(euler, seq, world, to_seq, to_world)
elif ori_repr == 'axis_angle':
axis = np.array(orientation['axis'])
angle = orientation['angle']
euler = axis_angle_to_euler(axis, angle, seq=to_seq, world=to_world)
elif ori_repr == 'dcm':
euler = dcm_to_euler(orientation['dcm'], seq=to_seq, world=to_world)
else:
raise ValueError(
'Unrecognized orientation repr {0}'.format(ori_repr))
return euler
def rotate_vector_euler(v, euler, seq='XYZ', world=True):
'''
Rotates vectors about axis by angle.
'''
rotmat = get_rotmat_euler(euler, seq=seq, world=world)
return np.dot(v, rotmat.T)
def get_rotmat_euler(euler, seq='XYZ', world=True):
return eulang.rotmat_euler(euler, seq=seq, world=world)
def shift_vector_euler(v, euler, seq='XYZ', world=True, forward=False):
shiftmat = get_shiftmat_euler(euler, seq=seq, world=world, forward=forward)
return np.dot(v, shiftmat.T)
def shift_tensor2_euler(a, euler, forward=False):
shiftmat = get_shiftmat_euler(euler, forward=forward)
return np.einsum('ip,jq,pq', shiftmat, shiftmat, a)
def shift_tensor3_euler(a, euler, forward=False):
shiftmat = get_shiftmat_euler(euler, forward=forward)
return np.einsum('ip,jq,kr,pqr', shiftmat, shiftmat, shiftmat, a)
def get_shiftmat_euler(euler, seq='XYZ', world=True, forward=False):
rotmat = get_rotmat_euler(euler, seq=seq, world=world)
if forward:
shiftmat = rotmat.T
else:
shiftmat = rotmat
return shiftmat
#Quaternion-----------------------------------------------------------
def get_rand_quat():
q = np.random.random((4,))
return normalize_quat(q)
def get_identity_quat():
return np.array([1.0, 0.0, 0.0, 0.0])
def get_rand_quat():
axis, angle = get_rand_axis_angle()
return axis_angle_to_quat(axis, angle)
def get_perturbed_quat(q):
raise NotImplementedError
def quat_to_axis_angle(q):
angle = 2*math.acos(q[0])
sin = math.sqrt(1.0-q[0]**2)
if angle > 0.0:
if angle < math.pi:
axis = q[1:4]/sin
else:
rotmat = get_rotmat_quat(q)
axis, angle = extract_axis_angle_from_rotmat(rotmat)
else:
axis = np.array([1.0, 0.0, 0.0])
return fix_axis_angle(axis, angle, normalize=True)
def quat_to_euler(q, seq='XYZ', world=True):
rotmat = get_rotmat_quat(q)
return factorize_rotmat(rotmat, seq=seq, world=world)
def quat_to_dcm(q):
return get_shiftmat_quat(q, forward=True)
def any_to_quat(orientation):
ori_repr = orientation['repr']
if ori_repr == 'quat':
quat = np.array(orientation['quat'])
elif ori_repr == 'euler':
euler = np.array(orientation['euler'])
seq = orientation['seq']
world = orientation['world']
quat = euler_to_quat(euler, seq=seq, world=world)
elif ori_repr == 'axis_angle':
axis = np.array(orientation['axis'])
angle = orientation['angle']
quat = axis_angle_to_quat(axis, angle)
elif ori_repr == 'dcm':
quat = dcm_to_quat(orientation['dcm'])
else:
raise ValueError(
'Unrecognized orientation repr {0}'.format(ori_repr))
return quat
def rotate_vector_quat(v, q):
rotmat = get_rotmat_quat(q)
return np.dot(v, rotmat.T)
def get_rotmat_quat(q):
rotmat = np.empty((3,3))
q0sq = q[0]**2
q1sq = q[1]**2
q2sq = q[2]**2
q3sq = q[3]**2
q0q1 = q[0]*q[1]
q0q2 = q[0]*q[2]
q0q3 = q[0]*q[3]
q1q2 = q[1]*q[2]
q1q3 = q[1]*q[3]
q2q3 = q[2]*q[3]
rotmat[0,0] = 2*(q0sq + q1sq) - 1.0
rotmat[0,1] = 2*(q1q2 - q0q3)
rotmat[0,2] = 2*(q1q3 + q0q2)
rotmat[1,0] = 2*(q1q2 + q0q3)
rotmat[1,1] = 2*(q0sq + q2sq) - 1.0
rotmat[1,2] = 2*(q2q3 - q0q1)
rotmat[2,0] = 2*(q1q3 - q0q2)
rotmat[2,1] = 2*(q2q3 + q0q1)
rotmat[2,2] = 2*(q0sq + q3sq) - 1.0
return rotmat
def shift_vector_quat(v, q, forward=False):
shiftmat = get_shiftmat_quat(q, forward=forward)
return np.dot(v, shiftmat.T)
def shift_tensor2_quat(a, quat, forward=False):
shiftmat = get_shiftmat_quat(quat, forward=forward)
return np.einsum('ip,jq,pq', shiftmat, shiftmat, a)
def shift_tensor3_quat(a, quat, forward=False):
shiftmat = get_shiftmat_quat(quat, forward=forward)
return np.einsum('ip,jq,kr,pqr', shiftmat, shiftmat, shiftmat, a)
def get_shiftmat_quat(q, forward=False):
if forward:
shiftmat = get_rotmat_quat(get_conjugated_quat(q))
else:
shiftmat = get_rotmat_quat(q)
return shiftmat
def conjugate_quat(q):
'''
Conjugates a quaternion in-place.
'''
q[1:4] = -q[1:4]
return q
def get_conjugated_quat(q):
'''
Conjugates a quaternion and returns a copy.
'''
p = np.copy(q)
p[1:4] = -p[1:4]
return p
def invert_quat(q):
'''
Inverts a quaternion in-place.
'''
return conjugate_quat(q)
def get_inverted_quat(q):
'''
Inverts a quaternion and returns it as a new instance.
'''
p = np.copy(q)
return conjugate_quat(p)
def normalize_quat(q):
'''
Normalizes a quaternion in-place.
'''
q /= np.linalg.norm(q)
return q
def get_normalized_quat(q):
'''
Normalizes a quaternion and returns it as a copy.
'''
p = np.copy(q)
return normalize_quat(p)
def quat_is_normalized(q):
norm = np.linalg.norm(q)
if math.isclose(norm, 1.0, rel_tol=1e-14):
return True
else:
return False
def get_quat_prod(p, q):
p0, p1, p2, p3 = tuple(p)
prod_mat = np.array([[p0, -p1, -p2, -p3],
[p1, p0, -p3, p2],
[p2, p3, p0, -p1],
[p3, -p2, p1, p0]])
pq = normalize_quat(np.dot(prod_mat, q))
return pq
def interpolate_quat(q1, q2, t):
theta = get_angle_between_quat(q1, q2)
q = (q1*math.sin((1.0-t)*theta)
+ q2*math.sin(t*theta))/math.sin(theta)
return normalize_quat(q)
def get_angle_between_quat(p, q):
'''
Returns the angle between two quaternions p and q.
'''
return math.acos(np.dot(p,q))
def quat_deriv_to_ang_vel(q, qdot):
mat = quat_deriv_to_ang_vel_mat(q)
return np.dot(mat, qdot)
def quat_deriv_to_ang_vel_mat(q):
q0, q1, q2, q3 = tuple(q)
return 2*np.array([[-q1, q0, -q3, q2],
[-q2, q3, q0, -q1],
[-q3, -q2, q1, q0]])
def ang_vel_to_quat_deriv(q, ang_vel):
mat = ang_vel_to_quat_deriv_mat(q)
qdot = np.dot(mat, ang_vel)
return qdot
def ang_vel_to_quat_deriv_mat(q):
q0, q1, q2, q3 = tuple(q)
return 0.5*np.array([[-q1, -q2, -q3],
[ q0, q3, -q2],
[-q3, q0, q1],
[ q2, -q1, q0]])
#Other functions------------------------------------------------------
def translate(v, delta):
'''
Translates vectors inplace by delta.
'''
n = v.shape[0]
for i in range(n):
v[i,:] += delta
return v
def align(v, old, new):
'''
old and new represent coordinate axes. They must be unit vectors.
'''
assert old.shape[0] == new.shape[0]
n = old.shape[0]
if n == 1:
angle = math.acos(np.dot(old, new))
axis = la.unitized(np.cross(old, new))
return rotate_vector_axis_angle(v, axis, angle)
elif n == 2:
z_old = la.unitized(np.cross(old[0,:], old[1,:]))
z_new = la.unitized(np.cross(new[0,:], new[1,:]))
axes_old = np.vstack((old, z_old))
axes_new = np.vstack((new, z_new))
dcm = dcm_from_axes(axes_old, axes_new)
return rotate_vector_dcm(v, dcm)
elif n == 3:
dcm = dcm_from_axes(old, new)
return rotate_vector_dcm(v, dcm)
def mat_is_dcm(mat):
return mat_is_rotmat(mat)
def mat_is_rotmat(mat):
det_is_one = math.isclose(np.linalg.det(mat), 1.0, abs_tol=1e-12, rel_tol=1e-12)
is_orthogonal = np.allclose(np.dot(mat, mat.T), np.identity(3))
return is_orthogonal and det_is_one
|
from wkbnch import powerset
def test_powerset():
"""If set A has n elements than P(A) has 2ⁿ elements."""
A = 'abc'
assert len(powerset.powerset(A)) == 2**len(A)
B = [1, 2, 3, 4, 5]
assert len(powerset.powerset(B)) == 2**len(B)
C = []
assert len(powerset.powerset(C)) == 2**len(C)
|
#ENTRADA
import os
os.system("cls")
lista_nombre=[]
lista_grado=[]
lista_dni=[]
lista_cursos=[]
Horario_Cursos=[]
lista_apellido=[]
i = 0
#PROCESO
print("------------Bienvenido al Aula Virtual------------")
nivel = input("Ingrese su nivel educativo<Primaria o Secuandaria>: ").lower()
while nivel !="primaria" and nivel != "secundaria":
print("-------Error-------")
nivel = input("Ingresa el nivel educativo correcto: ")
if nivel =="secundaria" :
grado= int(input("Ingresa el grado que estas cursando: "))
while grado > 5:
print("-----Error-----")
grado = int(input("Ingresa el grado correcto: "))
if nivel =="primaria" :
grado= int(input("Ingresa el grado que estas cursando: "))
while grado > 6:
print("-----Error-----")
grado = int(input("Ingresa el grado correcto: "))
edad = int(input("Ingresa tu edad: "))
while True:
if edad > 18:
print("-------Error------")
print("Ingrese dato correcto")
edad = int(input("Ingresa tu edad: "))
else:
break
colegio = input("Ingresa el nombre de tu colegio: ")
while True:
if colegio == "":
print("Error, ingrese dato correcto")
colegio = input("Ingresa el nombre de tu colegio: ")
else:
break
nombre = input("Escriba su nombre: ")
while True:
if nombre == "":
print("Error, ingrese dato correcto")
nombre = input("Escriba su nombre: ")
else:
break
apellido = input("Escriba su apellido: ")
while True:
if apellido == "":
print("Error, ingrese dato correcto")
apellido = input("Escriba su apellido: ")
else:
break
dni = int(input("Escriba el numero de su DNI: "))
lista_dni.append(dni)
while True:
if dni <= 0:
print("Error, ingrese dato correcto")
dni = int(input("Escriba el numero de su DNI: "))
else:
break
if nivel =="secundaria":
print("-----Los cursos que tienes por elegir son:-----")
print("Matemática, Lenguaje, Fisica, Química, Historia, Literatura, Raz.Matematica, Raz.Verbal, Computación, Ingles")
for i in range (0,7):
cursos = input("Escriba el nombre del curso que va a llevar:")
lista_cursos.append(cursos)
i += 1
if nivel =="primaria":
print("Los cursos que tienes por elegir son:")
print("Matemática, Comunicación, Ingles, Personal Social, Literatura, Raz.Matematica, Raz.Verbal, Computación, Ciencia, Educación fisica")
for i in range (0,5):
cursos = input("Escriba el nombre del curso que va a llevar:")
lista_cursos.append(cursos)
i += 1
#SALIDA
print("---------Datos del Alumno-----------")
print("Alumno:", nombre)
print("Edad:", edad)
print("Grado y nivel:", grado, nivel)
print("Registrado con el dni:", dni)
print("Cursos escogidos:", lista_cursos)
#horario de clases
Horario0 = "7:00 am - 7:45 am"
Horario1 = "7:45 am - 8:30 am"
Horario2 = "8:30 am - 9:15 am"
Horario3 = "9:15 am - 10:00 am"
Recreo1 = "10:00 am - 10:15 am"
Horario4 = "10:15 am - 11:00 am"
Horario5 = "11:00 am - 11:45 am"
Recreo2 = "11:45 am - 12:00 pm"
Horario6 = "12:00 pm - 12:45 pm"
Horario7 = "12:45 pm - 1:30 pm"
print("-------------Horarios--------------")
if nivel == "primaria":
print("-----Lunes-----")
print(lista_cursos[0],"este curso lo llevaras a las",Horario1)
print(lista_cursos[0],"este curso lo llevaras a las",Horario2)
print(lista_cursos[1],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[1],"este curso lo llevaras a las",Horario4)
print(lista_cursos[2],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[2],"este curso lo llevaras a las",Horario6)
print("-----Martes-----")
print(lista_cursos[3],"este curso lo llevaras a las",Horario1)
print(lista_cursos[3],"este curso lo llevaras a las",Horario2)
print(lista_cursos[4],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[4],"este curso lo llevaras a las",Horario4)
print(lista_cursos[1],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[1],"este curso lo llevaras a las",Horario6)
print("-----Miercoles-----")
print(lista_cursos[2],"este curso lo llevaras a las",Horario1)
print(lista_cursos[2],"este curso lo llevaras a las",Horario2)
print(lista_cursos[4],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[4],"este curso lo llevaras a las",Horario4)
print(lista_cursos[3],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[3],"este curso lo llevaras a las",Horario6)
print("-----Jueves-----")
print(lista_cursos[0],"este curso lo llevaras a las",Horario1)
print(lista_cursos[0],"este curso lo llevaras a las",Horario2)
print(lista_cursos[3],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[3],"este curso lo llevaras a las",Horario4)
print(lista_cursos[4],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[4],"este curso lo llevaras a las",Horario6)
print("-----Viernes-----")
print(lista_cursos[2],"este curso lo llevaras a las",Horario1)
print(lista_cursos[2],"este curso lo llevaras a las",Horario2)
print(lista_cursos[3],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[3],"este curso lo llevaras a las",Horario4)
print(lista_cursos[4],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[4],"este curso lo llevaras a las",Horario6)
if nivel == "secundaria":
print("-----Lunes-----")
print(lista_cursos[0],"este curso lo llevaras a las",Horario0)
print(lista_cursos[0],"este curso lo llevaras a las",Horario1)
print(lista_cursos[1],"este curso lo llevaras a las",Horario2)
print(lista_cursos[1],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[2],"este curso lo llevaras a las",Horario4)
print(lista_cursos[2],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[3],"este curso lo llevaras a las",Horario6)
print(lista_cursos[3],"este curso lo llevaras a las",Horario7)
print("-----Martes-----")
print(lista_cursos[4],"este curso lo llevaras a las",Horario0)
print(lista_cursos[4],"este curso lo llevaras a las",Horario1)
print(lista_cursos[5],"este curso lo llevaras a las",Horario2)
print(lista_cursos[5],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[6],"este curso lo llevaras a las",Horario4)
print(lista_cursos[6],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[0],"este curso lo llevaras a las",Horario6)
print(lista_cursos[0],"este curso lo llevaras a las",Horario7)
print("-----Miercoles-----")
print(lista_cursos[1],"este curso lo llevaras a las",Horario0)
print(lista_cursos[1],"este curso lo llevaras a las",Horario1)
print(lista_cursos[3],"este curso lo llevaras a las",Horario2)
print(lista_cursos[3],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[2],"este curso lo llevaras a las",Horario4)
print(lista_cursos[2],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[4],"este curso lo llevaras a las",Horario6)
print(lista_cursos[4],"este curso lo llevaras a las",Horario7)
print("-----Jueves-----")
print(lista_cursos[5],"este curso lo llevaras a las",Horario0)
print(lista_cursos[5],"este curso lo llevaras a las",Horario1)
print(lista_cursos[6],"este curso lo llevaras a las",Horario2)
print(lista_cursos[6],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[1],"este curso lo llevaras a las",Horario4)
print(lista_cursos[1],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[0],"este curso lo llevaras a las",Horario6)
print(lista_cursos[0],"este curso lo llevaras a las",Horario7)
print("-----Viernes-----")
print(lista_cursos[4],"este curso lo llevaras a las",Horario0)
print(lista_cursos[4],"este curso lo llevaras a las",Horario1)
print(lista_cursos[5],"este curso lo llevaras a las",Horario2)
print(lista_cursos[5],"este curso lo llevaras a las",Horario3)
print("El recreo empieza a las",Recreo1)
print(lista_cursos[2],"este curso lo llevaras a las",Horario4)
print(lista_cursos[2],"este curso lo llevaras a las",Horario5)
print("El siguiente recreo empieza a las",Recreo2)
print(lista_cursos[1],"este curso lo llevaras a las",Horario6)
print(lista_cursos[1],"este curso lo llevaras a las",Horario7)
print("-----Material Didactico------")
print("-----MATEMATICAS-----")
print("|||||| |||| |||| |||||| ")
print(" || ||| ||| || ||||||||")
print("|||| |||| |||| ")
print("|| ||| ||| || ||||||||")
print("|||||| |||| |||| |||||| ")
a = int(input("Resolver el siguiente problema: "))
while True:
if a == 4:
print("Respuesta Correcta!")
break
else:
print("Respuesta Incorrecta :( ")
a = int(input("Resolver el siguiente problema: "))
print("-----CIENCIAS-----")
print(" ||||| ||||||| ||||| ")
print(" |||||||| |||||||| ")
print(" |||||||||| ")
print(" |||| ")
print(" || ")
print(" || ||| ")
print(" |||| ")
print(" || ")
print(" || ")
b = input("Que funcion en la planta le da el color verde?: ")
while True:
if b == "fotosintesis":
print("Respuesta Correcta!")
break
else:
print("Respuesta Incorecta :c!")
b = input("Que funcion en la planta le da el color verde?: ")
print("-----COMPUTACION-----")
print(" ||||||||||||||||||||||||| ||||||| ")
print(" || || ||| ||| ")
print(" || || || || ")
print(" || || ||| ||| ")
print(" ||||||||||||||||||||||||| || | || ")
print(" |||| || | || ")
print(" |||||||| ||||||| ")
c = input("La computadora esta formado por dos partes principales, Cuales son?: ")
while True:
if c == "hardware y sofware" or c=="sofware y hardware":
print("Respuesta Correcta!")
break
else:
print("Respuesta Incorecta :c!")
c = input("La computadora esta formado por dos partes principales, Cuales son?: ")
for i in apellido:
if i == 'a':
lista_apellido.append(i)
elif i == 'e':
lista_apellido.append(i)
elif i == 'i':
lista_apellido.append(i)
elif i == 'o':
lista_apellido.append(i)
elif i == 'u':
lista_apellido.append(i)
print("---------Simulación de su promedio-----------")
if lista_apellido[0]=="a":
print("Su promedio de todos los cursos hasta el momento es : 15")
elif lista_apellido[0]=="e" :
print("Su promedio de todos los cursos hasta el momento es : 13")
elif lista_apellido[0]=="i":
print("Su promedio de todos los cursos hasta el momento es : 14")
elif lista_apellido[0]=="o":
print("Su promedio de todos los cursos hasta el momento es : 16")
elif lista_apellido[0]=="u":
print("Su promedio de todos los cursos hasta el momento es : 17")
|
class Company:
def __init__(self):
self.SNHgroup = None
class SNHgroup:
def __init__(self,name):
self.name = name
self.Group = None
class Group:
def __init__(self,group):
self.group = group
self.GNZ = None
class GNZ:
def __init__(self,team):
self.team = team
self.teamNII = None
class TeamNII:
def __init__(self,name):
self.jing = None
self.name = name
class Jing:
def __init__(self,nm,pd,ut):
self.nm = nm
self.pd = pd
self.ut = ut
Star48 = Company()
Star48.SNHgroup = SNHgroup("SNHgroup")
Star48.SNHgroup.group = Group(["SNH","GNZ","CKG"])
Star48.SNHgroup.group.GNZ = GNZ(["teamG","teamNIII","teamZ"])
Star48.SNHgroup.group.GNZ.teamNII = TeamNII(["jing","xixi"])
Star48.SNHgroup.group.GNZ.teamNII.jing = Jing("lu-jing","SNH 6","my boy")
print(Star48.SNHgroup.group.GNZ.teamNII.jing) |
# Needed librarys to complete the lab
import numpy as np
import pandas
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
df = pandas.read_csv("sample_stocks.csv", skiprows=0)
# creating the K means cluster
k_means = KMeans(n_clusters=3)
k_means.fit(df)
# labeling each point and then predicting closest cluster to X
print(k_means.labels_)
print("------")
k_mean = k_means.predict(df)
print(k_mean)
centers = np.array(k_means.cluster_centers_)
plt.scatter(centers[:,0], centers[:,1], marker="x", color='r')
plt.scatter(df.returns, df.dividendyield, c=k_mean)
plt.show() |
# esto lo ha hecho dmarquetal
lista_mis_deportes_favoritos = ["baloncesto", "balonmano", "tenis", "padel", "futbol"]
# print(lista_mis_deportes_favoritos)
for deporte in lista_mis_deportes_favoritos:
if deporte == "futbol":
print "futbol puagggg"
else:
print "me gusta el ", deporte
|
class Solution:
def validWordAbbreviation(self, word: str, abbr: str) -> bool:
lw = len(word)
labbr = len(abbr)
w_ptr = 0
a_ptr = 0
w_num = ""
while w_ptr < lw and a_ptr < labbr:
while a_ptr < labbr and abbr[a_ptr].isnumeric():
if len(w_num) == 0 and abbr[a_ptr] == '0':
return False
w_num += abbr[a_ptr]
a_ptr += 1
if len(w_num) > 0:
w_ptr += int(w_num)
if w_ptr >= lw:
return w_ptr == lw and a_ptr == labbr
w_num = ""
continue
if abbr[a_ptr].isalpha():
if abbr[a_ptr] != word[w_ptr]:
print('w2')
return False
a_ptr += 1
w_ptr += 1
return w_ptr == lw and a_ptr == labbr
|
class Trie:
def __init__(self):
# character:next_tree
self.children = {}
def insert(self, word: str) -> None:
if len(word) == 0:
self.children['*'] = None
else:
ch = word[0]
if ch not in self.children:
self.children[ch] = Trie()
self.children[ch].insert(word[1:])
def search(self, word: str) -> bool:
if len(word) == 0:
return '*' in self.children
ch = word[0]
if ch not in self.children:
return False
return self.children[ch].search(word[1:])
def startsWith(self, prefix: str) -> bool:
if len(prefix) == 0:
return True
ch = prefix[0]
if ch not in self.children:
return False
return self.children[ch].startsWith(prefix[1:])
|
from create import *
from insert_data import *
# Query 1: Find the top 5 offices with the most sales for that month.
month = 11
top_offices = session.query(Offices.name, func.sum(Houses.price), func.extract('month', Sales.date)).join(Houses, and_(Offices.ID == Houses.office_id)).join(Sales, and_(Sales.house_id == Houses.ID)).group_by(Offices.ID).order_by(func.sum(Houses.price).desc()).filter(func.extract('month', Sales.date) == month).limit(5).statement
top_offices = pd.read_sql(top_offices, session.bind)
top_offices.columns=['Office', 'Sales', 'Month']
print(top_offices)
# Query 5: For all houses that were sold that month, calculate the average selling price
# Change the month variable above and run both сells to see results for other months.
if len(top_offices) >= 1:
print("The average selling price for the {0}th month is ${1}".format(month, int(top_offices.mean()[0])))
else:
print("No houses were sold in the {0}th month".format(month))
# Query 2: Find the top 5 estate agents who have sold the most (include their contact
# details and their sales details so that it is easy contact them and congratulate them).
# Names and contact info
top_agents = session.query(Agents.name, Agents.email, func.count(Houses.price), func.sum(Houses.price)).join(Houses, and_(Agents.ID == Houses.agent_id)).group_by(Agents.name).order_by(func.sum(Houses.price).desc()).limit(5).statement
top_agents = pd.read_sql(top_agents, session.bind)
top_agents.columns=['Agent', 'Email', 'Houses Sold','Sales']
print(top_agents)
#Sales details
agent = "Fenni Hoasner"
sales= session.query(Sales.ID, Buyers.name, Sellers.name, Sales.date, Houses.price).join(Houses, and_(Sales.house_id == Houses.ID)).join(Buyers, and_(Buyers.ID == Sales.buyer_id)).join(Agents, and_(Houses.agent_id == Agents.ID)).join(Sellers, and_(Houses.seller_id == Sellers.ID)).order_by(Sales.date).filter(Agents.name == agent).limit(5).statement
sales = pd.read_sql(sales, session.bind)
sales.columns=['Sale ID', 'Buyer', 'Seller','Date',"Price"]
print(sales)
# Query 3: Calculate the commission that each estate agent must receive and store the results in a separate table.
commissions_per_agent = session.query(Agents.name, func.sum(Commissions.amount), func.count(Commissions.amount)).join(Commissions, and_(Commissions.agent_id == Agents.ID)).group_by(Agents.name).order_by(func.sum(Commissions.amount).desc()).statement
commissions_per_agent = pd.read_sql(commissions_per_agent, session.bind)
commissions_per_agent.columns=['Agent', 'Total Commission', 'Number of Sales']
print(commissions_per_agent)
# Query 4: For all houses that were sold that month, calculate the average number of days that the house was on the market.
month = 4
dates = session.query(Houses.ID, Sales.date, Houses.date).join(Sales, and_(Sales.house_id == Houses.ID)).all()
n_days = []
for date in dates:
n_days.append(date[1]-date[2])
avg_days = np.mean(n_days).days
print("Average number of days that the house was on the market is {0}.".format(avg_days))
# Query 6: Find the zip codes with the top 5 average sales prices
zip_codes = session.query(Houses.zip_code, func.sum(Houses.price)).group_by(Houses.zip_code).order_by(func.sum(Houses.price).desc()).limit(5).statement
zip_codes = pd.read_sql(zip_codes, session.bind)
zip_codes.columns=['Zip Code', 'Average Price']
print(zip_codes)
# Cleanup
session.close()
Base.metadata.drop_all(bind=engine)
|
def read(name):
file = open(name,"r")
word_arr = []
for line in file:
for word in line.split():
word_arr.append(word)
return word_arr
def BubbleSort(words):
k = len(words)
for i in range(k):
for z in range(0, k - i - 1):
if (words[z + 1].upper() < words[z].upper()):
words[z], words[z + 1] = words[z + 1], words[z]
return words
def FrequencyFind(Sorted_arr,word):
k=0
a=len(Sorted_arr)
for i in range(a):
if(word in Sorted_arr[i] and len(word)== len(Sorted_arr[i])):
k=k+1
return k
name = input("Enter the file name: ")
word=[]
word = read(name)
sort =[]
sort = BubbleSort(word)
print(sort)
search = input("\nEnter words :")
Freq = FrequencyFind(sort, search)
if (Freq == 0):
print("The words that you are searching does not exist in the text file")
else:
print("\n")
print(search, "Repeats", Freq, "Times")
|
##classes, iterations
##REVIEW
class Dog:
def __init__(self,name,age=1): #must have self, must init class
self.name = name #self.parameter = init(parameter)
self.age = age #age=1 unless self.age value is entered
self.owner = "John" #owner defaults to John with no option to change
def walk(self):
print("Walking")
def eat(self,food):
print(f"Eating {food}.")
dane = Dog("Flurffy",7)
print(dane.name,dane.age,dane.owner)
dane.owner = "Robert" #will need to change owner like this since there is no owner parameter is class Dog
dane.walk() #runs function walk() as is
dane.eat("tacos") #inserts tacos into food parameter then runs eat()
class BankAccount:
def __init__(self,driver_license,initial_deposit,type_of_account):
self.driver_license = driver_license
self.balance = initial_deposit
self.type_of_account = type_of_account
def deposit(self,amount):
self.balance += amount
bank_account = BankAccount("GA055569224", 100.00, "checking")
print(bank_account.balance)
bank_account.deposit(50.00)
print(bank_account.balance)
#################################################################
name = "John" #define name as john
another_name = name #create a new value for name
another_name = "Mary"
print(name)
print(another_name)
numbers = [1,2,3,4,5] #making a copy of numbers and allowing us to modify it without changing the original copy
another_numbers = numbers
another_numbers.append(99)
print(numbers)
##This is called a REFERENCE TYPE ##########
#REFERENCE TYPES are stored in the memory; called HEAP
#The HEAP points the stored REFERENCE to a particular value (the array, not the variable)
#When you make a copy and assign it, this is called a VALUE TYPE
##REFERENCE TYPE == original, VALUE TYPES == modified from copy of original
##REFERENCE TYPES == ARRAYS, CLASSES
#If you change the REFERENCE TYPE it changes the value for all subsequent calls
class Cat:
def __init__(self,name):
self.name = name
def __repr__(self): #changing how default outputs are represented (disable and see how print(cats) displays)
return self.name
cat1 = Cat("Cat 1")
cat2 = cat1
print(cat1.name)
print(cat2.name)
cat2.name = "Cat 99"
print(cat2.name)
print(cat1.name)
cat3 = Cat("Cat 3")
cats = [cat1,cat3]
print(cats) #reference line 56 and 57
cat1.name = "Another Cat"
for cat in cats:
print(cat.name)
### NHERITENCE ##################
class Car:
def __init__(self,make,model):
self.make = make
self.model = model
self.speed = 100
self.color = "Yellow"
def drive(self):
print("\nDrive.\n")
def brake(self):
print("\nBrake.\n")
def fill_up_gas(self):
print("\nFilling up now.\n")
class ElectricCar(Car): #ElectricCar Class INHERITS from Car class
def __init__(self,make,model): #initializing is a good idea since superclass tends to have more info
#super means parent class (Car is SUPER to ElectricCar)
super().__init__(make,model)
#car already defines what make and model are, and electriccar inherits them
#drive and brake are inherited, so you do not need to type them again
#super will call self.color, so when ElectricCar.color is called it uses the value of Car.color
def fill_up_gas(self):
print("\nYour electric car needs gas???\n") ##override values of fill_up_gas() with new value
#using SUPER is important to save time
electric_car = ElectricCar("Tesla","Model 3")
print(electric_car.make, electric_car.model, electric_car.color)
#INHERITENCE saves a ton of time by avoiding typing or copying code over and over
electric_car.drive()
electric_car.fill_up_gas() #will not run Car.fill_up_gas since ElectricCar overrides it
##Another example
class Animal:
def __init__(self,name):
self.name = name
print("initialized")
def eat(self):
print("eating")
def sleep(self):
print("sleeping...")
##NOTE: if a function doesnt pull, user super.function or copy function
## calling functions isnt always the best optiong
class Cat(Animal):
def __init__(self):
super().__init__(name)
self.speed = 65
class Cheetah(Cat):
def __init__(self):
super().__init__(name)
## you can create an endless heirarchy of SUPER and SUB CLASSES
##Cheetah is a cat; a cat is an animal
#Cheetah can have properties which the superclasses do not have
#Transportation == SUPER
#LandVehicles, WaterVehicles, AirVehicles, SpaceVehicles == SUB of SUPER
#Cars, ElectricCars, Motorcycles == SUB of LandVehicles
#Trucks, SUVs, Suburbans, Sedans == SUB of Cars
class Address:
def __init__(self,street,city,state,zip):
self.street = street
self.city = city
self.state = state
self.zip = zip
def __repr__(self):
return self.street
def __repr__(self):
return self.city
def __repr__(self):
return self.state
def __repr__(self):
return self.zip
class User:
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
self.addresses = []
def __repr__(self):
return self.first_name
def __repr__(self):
return self.last_name
user = User("John","Doe")
address1 = Address("Street","City","Texas","77380")
user.addresses = address1
print(user.addresses.street, user.addresses.city, user.addresses.state, user.addresses.zip)
print(user, "THIS IS WHAT IM LOOKING FOR")
print(user.addresses)
##NOT FULLY FUNCTION; cannot append array and print it
|
### STACK DATA STRUCTURES
#think of a stack of dishes; you have to move the top to get to the next one
#the last one you put on the stack is the first one to come off
#its standard to call your insert function push() when using stack
#push(1), push(2), push(dog), push(potato)
#potato, dog, 2, 1 with potato on top and 1 on bottom
#pop() is pulling the top item off and using it
#pop() == potato
#pop() == dog since potato has previously been removed
#pop() == 2, pop() ==1, pop() == no value to pop (try: pop(): except: return xyz)
#understanding the data structure and the functions of a STACK is important
#STACK may or may not be something you ever use
### QUEUE DATA STRUCTURES
#first in, first out (think lines of people at the grocery store checkout)
#enqueue() and dequeue() are the same as push() and pop()
#enqueue(1), enqueue(23), dequeue() == 1, dequeue() == 23
import random
array1 = []
class Stack:
def __init__(self, value):
self.value = value
def push(self, value):
array1.append(value)
def pop(self):
array1.pop()
x = 1
test1 = Stack(x)
print(array1)
test1.push(x)
print(array1)
test1.push(7)
test1.push(8)
test1.pop()
print(array1)
from collections import deque
queue = deque(["eric", "john", "michael"])
queue.append("terry")
queue.append("graham")
print(queue)
queue.popleft()
print(queue)
queue.popleft()
print(queue)
### BUBBLE SORT
#when data is entered in any order you can pull the data out in a specific order
#most common example is random numbers put into an array and pulled out from smallest to largest
#any SORT BY option could be using BUBBLE SORTING (price, size, color, time, distance)
arr = [14,456,34,213456,65,4444,3,567,65,23]
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
bubbleSort(arr)
for i in range(len(arr)):
print("%d" %arr[i])
|
import re
l=[]
l1=[]
l=[x for x in input().split(',')]
c=0
for i in l:
if(len(i)<6 or len(i)>12):
pass
else:
if not re.search("[a-z]",i):
continue
elif not re.search("[A-Z]",i):
continue
elif not re.search("[0-9]",i):
continue
elif not re.search("[$#@]",i):
continue
else:
pass
l1.append(i)
print(l1)
|
#!/usr/bin/env python
# coding: utf-8
# # Data Gathering
#
# ## Process
# 1. Understand how audio is processed
# 2. Determine what features to extract from the audio signal
# 3. Understand what each feature represents and how it is calculated
# 4. Write a function that reads and extracts important numeric features from audio signals from a given directory
# 5. Write a function that reads audio signals and extracts the mel spectrograms
#
# **IMPORTANT NOTE:** after downloading the data from http://marsyas.info/downloads/datasets.html, I combined all of the files into a single folder and named it "wavfiles." Make sure to do this if you are going through this notebook, and place the "wavfiles" folder in the empty "data" folder.
#
# ## Tests with Single Audio File (Toy Example)
# In[3]:
def unzip_data_dir(zip_file):
from zipfile import ZipFile
# zip_file = "../fma_metadata.zip"
with ZipFile(zip_file, 'r') as zip:
# printing all the contents of the zip file
zip.printdir()
# extracting all the files
print('Extracting all the files now...')
zip.extractall()
print('Done!')
# In[4]:
# unzip_data_dir("../fma_metadata.zip")
# In[5]:
# Imports
import os
import pandas as pd
import numpy as np
# In[6]:
import librosa
import librosa.display
import matplotlib.pyplot as plt
# ### Extracting an Audio Signal
#
# A **signal** is a variation in a quantity over time. For audio, the quantity that varies is air pressure. We can represent a signal digitally by taking samples of the air pressure over time. We are left with a waveform for the signal. Librosa is a python library that allows us to extract waveforms from audio files along with several other features. This is the primary package that will be used for this project.
# In[7]:
# import utils
# In[8]:
# tracks = utils.load('data/fma_metadata/tracks.csv')
# genres = utils.load('data/fma_metadata/genres.csv')
# features = utils.load('data/fma_metadata/features.csv')
# echonest = utils.load('data/fma_metadata/echonest.csv')
# In[9]:
# Extracting the wave, "y", and sampling rate, "sr", of the audio file
# y, sr = librosa.load('../data/blues/blues.00000.wav')
y, sr = librosa.load('../fma_data/Hip-Hop/10192.mp3', duration=30.0)
# y, sr = librosa.load(librosa.util.example_audio_file(), duration=5.0)
# In[10]:
# Checking the shape of the wave
y.shape
# In[11]:
# Checking the sampling rate
sr
# In[12]:
# Plotting the wave
plt.plot(y);
plt.title('Signal');
plt.xlabel('Time (samples)');
plt.ylabel('Amplitude');
# ### Fast Fourier Transform (FFT)
#
# An audio signal is comprised of several single-frequency sound waves. When taking samples of the signal over time, we only capture the resulting amplitudes. The **Fourier transform** is a mathematical formula that allows us to decompose a signal into it’s individual frequencies and the frequency’s amplitude. In other words, it converts the signal from the time domain into the frequency domain. The result is called a **spectrum**. The **fast Fourier transform** is an efficient way to compute the Fourier transform.
#
# 
# citation: https://towardsdatascience.com/understanding-audio-data-fourier-transform-fft-spectrogram-and-speech-recognition-a4072d228520
# In[13]:
# Computing the fast Fourier transform on a single short time window of length 2048 (standard for music audio)
n_fft = 2048
ft = np.abs(librosa.stft(y[:n_fft], hop_length = n_fft+1))
# In[14]:
# Plotting the signal after applying the FFT
plt.plot(ft);
plt.title('spectrum');
plt.xlabel('Frequency Bin');
plt.ylabel('Amplitude');
# ### Mel Spectrograms
#
# **Spectrograms** are a way to visually represent a signal's loudness, or amplitude, as it varies over time at different frequencies. The horizontal axis is time, the vertical axis is frequency, and the color is amplitude. It is calculated using the fast Fourier transform on short time windows of the signal and transforming the vertical axis (frequency) to log scale and the colored axis (amplitude) to decibals. Now, what about the "mel" part? Humans are better at detecting differences in lower frequencies than higher frequencies. The **mel scale** transforms the frequency scale such that sounds at equal distances from each other also sound equal in distance. A **mel spectrogram** is a spectrogram where the frequencies are converted to the mel scale.
# In[15]:
# Computing the spectrogram
spec = np.abs(librosa.stft(y, hop_length=512))
spec = librosa.amplitude_to_db(spec, ref=np.max) # converting to decibals
# Plotting the spectrogram
plt.figure(figsize=(8,5));
librosa.display.specshow(spec, sr=sr, x_axis='time', y_axis='log');
plt.colorbar(format='%+2.0f dB');
plt.title('Spectrogram');
# In[16]:
# Computing the mel spectrogram
spect = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024)
spect = librosa.power_to_db(spect, ref=np.max) # Converting to decibals
# Plotting the mel spectrogram
plt.figure(figsize=(8,5))
librosa.display.specshow(spect, y_axis='mel', fmax=8000, x_axis='time');
plt.title('Mel Spectrogram');
plt.colorbar(format='%+2.0f dB');
# ### Mel Frequency Cepstral Coefficients (MFCC)
# MMCCs are commonly used features in the field of music information retrieval (MIR). They are tyically used to measure timbre.
# In[17]:
# Extracting mfccs from the audio signal
mfcc = librosa.feature.mfcc(y=y, sr=sr, hop_length=512, n_mfcc=13)
# In[18]:
# Displaying the mfccs
plt.figure(figsize=(8,5));
librosa.display.specshow(mfcc, x_axis='time');
plt.title('MFCC');
# In[19]:
# Scaling the mfccs
mfccscaled = np.mean(mfcc.T, axis=0)
mfccscaled
# In[20]:
# Creating an empty list to store sizes in
sizes = []
import warnings
warnings.filterwarnings("ignore")
# Looping through each audio file
data_dir = '../fma_data'
"""
for folder in os.scandir(data_dir):
# print('Traversing folder ', folder.name)
if(os.path.isdir(folder)):
for file in os.scandir(folder):
if(file.name.endswith('.mp3')):
# Loading in the audio file
# print('Opening ', file.name)
y, sr = librosa.core.load(str(data_dir + '/' + folder.name + '/' + file.name), duration=30.0)
# Computing the mel spectrograms
spect = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024)
spect = librosa.power_to_db(spect, ref=np.max)
# Adding the size to the list
sizes.append(spect.shape)
# Checking if all sizes are the same
print(f'The sizes of all the mel spectrograms in our data set are equal: {len(set(sizes)) == 1}')
# Checking the max size
print(f'The maximum size is: {max(sizes)}')
"""
# **Note:** The Sizes are not the same, so we will have to pad the smaller arrays with zeros to make them all the same size.
# In[21]:
def extract_mel_spectrogram(directory):
'''
This function takes in a directory of audio files in .wav format, computes the
mel spectrogram for each audio file, reshapes them so that they are all the
same size, and stores them in a numpy array.
It also creates a list of genre labels and maps them to numeric values.
Parameters:
directory (int): a directory of audio files in .wav format
Returns:
X (array): array of mel spectrogram data from all audio files in the given
directory
y (array): array of the corresponding genre labels in numeric form
'''
# Creating empty lists for mel spectrograms and labels
labels = []
mel_specs = []
# Looping through each file in the directory
for folder in os.scandir(directory):
if(os.path.isdir(folder)):
for file in os.scandir(folder):
# Loading in the audio file
# y, sr = librosa.load(file)
y, sr = librosa.load(str(data_dir + '/' + folder.name + '/' + file.name), duration=30.0)
# Extracting the label and adding it to the list
label = str(file).split('.')[0][11:]
labels.append(label)
# Computing the mel spectrograms
spect = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024)
spect = librosa.power_to_db(spect, ref=np.max)
# Adjusting the size to be 128 x 660
if spect.shape[1] != 660:
spect.resize(128,660, refcheck=False)
# Adding the mel spectrogram to the list
mel_specs.append(spect)
# Converting the list or arrays to an array
X = np.array(mel_specs)
# Converting labels to numeric values
labels = pd.Series(labels)
label_dict = {
'jazz': 1,
'reggae': 2,
'rock': 3,
'blues': 4,
'hiphop': 5,
'country': 6,
'metal': 7,
'classical': 8,
'disco': 9,
'pop': 10
}
y = labels.map(label_dict)
# Returning the mel spectrograms and labels
return X, y
# In[22]:
# Using the function to read and extract mel spectrograms from the GTZAN Genre Dataset audio files
#X, y = extract_mel_spectrogram('../fma_data')
# **Note:** I will use this function in the first CNN notebook to gather and preprocess the data.
# ## Function to Read and Extract Mel Spectrograms from Audio Files
#
# #### Checking the Size of the Mel Spectrograms
# In order to feed the mel spectrogram data into a neural network, they must all be the same size, so I check that here.
# ## Function to Read and Extract Mel Spectrograms from Audio Files and Convert to DataFrame
# In[23]:
def make_mel_spectrogram_df(directory):
'''
This function takes in a directory of audio files in .wav format, computes the
mel spectrogram for each audio file, reshapes them so that they are all the
same size, flattens them, and stores them in a dataframe.
Genre labels are also computed and added to the dataframe.
Parameters:
directory (int): a directory of audio files in .wav format
Returns:
df (DataFrame): a dataframe of flattened mel spectrograms and their
corresponding genre labels
'''
# Creating empty lists for mel spectrograms and labels
labels = []
mel_specs = []
i = 0
# Looping through each file in the directory
for folder in os.scandir(directory):
if(os.path.isdir(folder)):
for file in os.scandir(folder):
if(file.name.endswith('.mp3')):
# Loading in the audio file
# y, sr = librosa.load(file)
y, sr = librosa.load(str(data_dir + '/' + folder.name + '/' + file.name), duration=30.0)
# Extracting the label and adding it to the list
label = str(folder.name)
labels.append(label)
# Computing the mel spectrograms
spect = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024)
spect = librosa.power_to_db(spect, ref=np.max)
# Adjusting the size to be 128 x 660
if spect.shape[1] != 660:
spect.resize(128,660, refcheck=False)
# Flattening to fit into dataframe and adding to the list
spect = spect.flatten()
mel_specs.append(spect)
i += 1
print(i)
# Converting the lists to arrays so we can stack them
mel_specs = np.array(mel_specs)
labels = np.array(labels).reshape(7994,1)
# Create dataframe
df = pd.DataFrame(np.hstack((mel_specs,labels)))
# Returning the mel spectrograms and labels
return df
# In[24]:
# Using the above function to create a dataframe with all of the flattened mel spectrograms and genre labels
df = make_mel_spectrogram_df('../fma_data')
# #### Export
# In[ ]:
df.to_csv('../fma_data/genre_mel_specs.csv', index=False)
# ## Function to Read and Extract Numeric Features from Audio Files
# In[ ]:
def extract_audio_features(directory):
'''
This function takes in a directory of .wav files and returns a
DataFrame that includes several numeric features of the audio file
as well as the corresponding genre labels.
The numeric features incuded are the first 13 mfccs, zero-crossing rate,
spectral centroid, and spectral rolloff.
Parameters:
directory (int): a directory of audio files in .wav format
Returns:
df (DataFrame): a table of audio files that includes several numeric features
and genre labels.
'''
# Creating an empty list to store all file names
files = []
labels = []
zcrs = []
spec_centroids = []
spec_rolloffs = []
mfccs_1 = []
mfccs_2 = []
mfccs_3 = []
mfccs_4 = []
mfccs_5 = []
mfccs_6 = []
mfccs_7 = []
mfccs_8 = []
mfccs_9 = []
mfccs_10 = []
mfccs_11 = []
mfccs_12 = []
mfccs_13 = []
i = 0
# Looping through each file in the directory
for folder in os.scandir(directory):
if(os.path.isdir(folder)):
for file in os.scandir(folder):
if(file.name.endswith('.mp3')):
i+=1
print("2: ", i)
# Loading in the audio file
# y, sr = librosa.core.load(file)
y, sr = librosa.load(str(data_dir + '/' + folder.name + '/' + file.name), duration=30.0)
# Adding the file to our list of files
files.append(file)
# Adding the label to our list of labels
label = str(folder.name)
labels.append(label)
# Calculating zero-crossing rates
zcr = librosa.feature.zero_crossing_rate(y)
zcrs.append(np.mean(zcr))
# Calculating the spectral centroids
spec_centroid = librosa.feature.spectral_centroid(y)
spec_centroids.append(np.mean(spec_centroid))
# Calculating the spectral rolloffs
spec_rolloff = librosa.feature.spectral_rolloff(y)
spec_rolloffs.append(np.mean(spec_rolloff))
# Calculating the first 13 mfcc coefficients
mfcc = librosa.feature.mfcc(y=y, sr=sr, hop_length=512, n_mfcc=13)
mfcc_scaled = np.mean(mfcc.T, axis=0)
mfccs_1.append(mfcc_scaled[0])
mfccs_2.append(mfcc_scaled[1])
mfccs_3.append(mfcc_scaled[2])
mfccs_4.append(mfcc_scaled[3])
mfccs_5.append(mfcc_scaled[4])
mfccs_6.append(mfcc_scaled[5])
mfccs_7.append(mfcc_scaled[6])
mfccs_8.append(mfcc_scaled[7])
mfccs_9.append(mfcc_scaled[8])
mfccs_10.append(mfcc_scaled[9])
mfccs_11.append(mfcc_scaled[10])
mfccs_12.append(mfcc_scaled[11])
mfccs_13.append(mfcc_scaled[12])
# Creating a data frame with the values we collected
df = pd.DataFrame({
'files': files,
'zero_crossing_rate': zcrs,
'spectral_centroid': spec_centroids,
'spectral_rolloff': spec_rolloffs,
'mfcc_1': mfccs_1,
'mfcc_2': mfccs_2,
'mfcc_3': mfccs_3,
'mfcc_4': mfccs_4,
'mfcc_5': mfccs_5,
'mfcc_6': mfccs_6,
'mfcc_7': mfccs_7,
'mfcc_8': mfccs_8,
'mfcc_9': mfccs_9,
'mfcc_10': mfccs_10,
'mfcc_11': mfccs_11,
'mfcc_12': mfccs_12,
'mfcc_13': mfccs_13,
'labels': labels
})
# Returning the data frame
return df
# In[ ]:
# Using the function to read and extract the audio files from the GTZAN Genre Dataset
df = extract_audio_features('../fma_data')
# #### Export
# In[ ]:
df.to_csv('../fma_data/genre.csv', index=False)
# In[ ]:
|
# Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
# def isListPalindrome(l):
# """ Time & Space: O(n)"""
# s = []
# tmp = l
# while tmp:
# s.append(tmp.value)
# tmp = tmp.next
# tmp = l
# while tmp:
# if s.pop() != tmp.value:
# return False
# tmp = tmp.next
# return True
def isListPalindrome(l):
""" Time O(n), Space O(1) """
if not l or not l.next:
return True
mid_ptr = l # jump 1 pointer
end_ptr = l # jump 2 pointers
odd = False
# Find mid pointer and if list is odd length
while end_ptr:
end_ptr = end_ptr.next
if end_ptr:
mid_ptr = mid_ptr.next
end_ptr = end_ptr.next
else:
odd = True
# Reverse second list
if odd:
mid_ptr = mid_ptr.next
prev_ptr = None
curr_ptr = mid_ptr
next_ptr = None
while curr_ptr:
next_ptr = curr_ptr.next
curr_ptr.next = prev_ptr
prev_ptr = curr_ptr
curr_ptr = next_ptr
# Compare two lists
while prev_ptr:
if l.value != prev_ptr.value:
return False
prev_ptr = prev_ptr.next
l = l.next
return True
|
def find_sum(n):
temp = 0
while n > 0:
d = n % 10
n = n//10
temp += d
return temp
z = 0
for a in range(2,100):
for b in range(2,100):
v = find_sum(a**b)
z = v if v > z else z
print(z)
|
import re
your_string = input("input your string : ")
pattern = input("input your patter : ")
special_char = "[a-z.*]"
check_string = re.match(special_char, your_string)
check_pattern = re.match(special_char, pattern)
if (not check_pattern) or (not check_string):
print("your pattern/string wrong")
exit()
result = re.match(pattern, your_string)
if result:
print("result :", True)
else:
print("result :", False)
|
# a=2
# b=20
# c=a*b
# print(c)
# print('c')
# print("c")
#
# #
# jj=4**2
# print(jj)
#
# ff=jj%5 # reminder
# print(ff)
#
# ddd='hi '+ 'prasad'
# print(ddd)
# type(ddd)
# j=input('who are you?')
# print('welcome ',j)
# floor=input('enter floor number : ')
# us_floor=1+int(floor)
# print('ur floor is ', us_floor, 'in usa system')
# file_name = input("Enter your file_name")
# print('Hello ', file_name)
# hrs = input("Enter Hours:")
# rate=input("Enter rate per hour")
# pay=int(hrs)*float(rate)
# print(pay)
# astr = 'Hello Bob'
# istr = 0
# try:
# istr = int(astr)
# except:
# istr = -1
# print(istr)
hrs = input("Enter Hours:")
rate = input("Enter rate per hour:")
try:
h = float(hrs)
r = float(rate)
except:
print("Error, please enter numerical value")
quit()
print(h, r)
if h > 40:
pay = 40 * r + (h - 40) * r * 1.5
elif h <= 40:
pay = h * r
print(pay)
|
file_name = 'mbox-short.txt' #input('Enter file:')
# print(len(file_name))
# if len(file_name) < 1 : #file_name = "mbox-short.txt"
text = open(file_name)
maxauthor = dict()
# print(maxauthor)
# print(text)
for line in text:
line.rstrip()
if not line.startswith("From "): continue
words = line.split()
maxauthor[words[1]] = maxauthor.get(words[1],0)+1
largest = None
largest_author = None
for key in maxauthor:
if largest is None: largest = maxauthor[key]
if largest < maxauthor[key]:
largest = maxauthor[key]
largest_author = key
print (largest_author, largest)
|
#!/usr/bin/python
#coding=utf-8
class Node(object):
def __init__(self,val,next = None):
self.value = val
self.next = next
class Linklist(object):
def __init__(self):
self.head = None
def initlist(self,data):
self.head = Node(0)
p = self.head
for i in data:
node = Node(i)
p.next = node
p = p.next
def show(self):
p = self.head.next
while p != None:
print p.value,
p = p.next
print ""
def clear(self):
self.head = None
def append(self,value):
p = self.head
while p.next != None:
p = p.next
p.next = Node(value)
def insert(self,index,value):
p = self.head
i = 0
while p.next != None and i < index:
p = p.next
i += 1
q = Node(value)
q.next = p.next
p.next = q
self.delete(index + 1)
def delete(self,index):
p = self.head
i = 0
while p.next != None and i < index:
p = p.next
i += 1
if p.next == None:
print "index is error"
else:
p.next = p.next.next
def index(self,value):
p = self.head.next
i = 0
while p != None and not (p.value == value):
p = p.next
i += 1
if p == None:
return -1
else:
return i
l = Linklist()
l.initlist([1,2,3,4,5])
l.show()
print "增加"
l.append(10)
l.show()
print "改"
l.insert(2,30)
l.show()
print "删"
l.delete(3)
l.show()
print "查"
print l.index(30)
|
board_dimension = 10
count = 0
while count < board_dimension:
if count % 2 == 0:
print("_#" * (board_dimension//2))
else:
print("#_" * (board_dimension//2))
count += 1
|
# try block means try to run this code
# if it contains any exception then hand over that exception
# to except block
# except block handles runtime errors (exceptions)
# we can have multiple except blocks
# each block is dedicated for handling a specific type of exception like ValuError, IndexError
# if exception doesn't matches with any except block
# then the last block having BaseException consumes each exception and prints out th error message as required
# finally block - always execute code will go here
# file close, database connetion closing, user thanku msg
while True:
try:
file = None
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
q = num1 / num2
print("Quotient is ", q)
list1 = [1, 2, 3, 4, 5]
# print(list1[100])
file = open('patterns.py')
print(file.read())
file.close()
except ValueError:
print("Only integers are allowed...")
except ZeroDivisionError:
print("Please don't enter 0 for num2")
except IndexError as error:
print("Some error occured...", error)
except BaseException as error:
print("Some error occured...", error)
else:
print("Everything worked perfectly")
break
finally:
print("Finally ran...")
if file != None:
file.close()
# while True:
# numberValid = True
# num1 = input("Enter first number: ")
# for digit in num1:
# if ord(digit) >= 48 and ord(digit) <= 57:
# continue
# else:
# print("Number not valid")
# numberValid = False
# break
# if numberValid:
# break
# num2 = int(input("Enter second number: "))
|
import random
from termcolor import colored
gamePositions = [1, 2, 3, 4, 5, 6, 7, 8, 9]
winningPositions = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [
0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
print("\033[91m \033[1m \033[4m Tic Tac Toe \033[0m".center(22))
# print(colored("Tic Tac Toe".center(22), "red"))
while True:
userChoice = input("What do you want to use (X/O): ")
if userChoice == 'x' or userChoice == 'X':
userChoice = "X"
cpuChoice = "O"
print("You selected X")
break
elif userChoice == "O" or userChoice == 'o' or userChoice == '0':
userChoice = "O"
cpuChoice = "X"
print("You selected O")
break
else:
print("Invalid choice...")
print(f'''
{gamePositions[0]} | {gamePositions[1]} | {gamePositions[2]}
---------
{gamePositions[3]} | {gamePositions[4]} | {gamePositions[5]}
---------
{gamePositions[6]} | {gamePositions[7]} | {gamePositions[8]}
''')
isUserTurn = True
userTurnsPlayed = 0
isGameFinished = False
while not isGameFinished and userTurnsPlayed < 5:
if isUserTurn:
userInput = int(input("Enter the position: "))
if userInput in gamePositions:
gamePositions[userInput - 1] = userChoice
userTurnsPlayed += 1
isUserTurn = False
else:
print("Position already occupied...")
continue
else:
cpuInput = random.choice(gamePositions)
print("cpu input is", cpuInput)
if cpuInput == "X" or cpuInput == "O":
continue
gamePositions[cpuInput - 1] = cpuChoice
isUserTurn = True
print(f'''
{gamePositions[0]} | {gamePositions[1]} | {gamePositions[2]}
---------
{gamePositions[3]} | {gamePositions[4]} | {gamePositions[5]}
---------
{gamePositions[6]} | {gamePositions[7]} | {gamePositions[8]}
''')
if userTurnsPlayed >= 3:
for position in winningPositions:
# print(position) [0,1,2] [3,4,5]
if gamePositions[position[0]] == gamePositions[position[1]] and gamePositions[position[0]] == gamePositions[position[2]]:
isGameFinished = True
print("CPU wins") if isUserTurn else print("User wins")
# if isUserTurn:
# print("CPU wins")
# else:
# print("User wins")
break
if not isGameFinished:
print("Game draw")
|
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> 1 + 2
3
>>> print
<built-in function print>
>>> print() paranthesis
SyntaxError: invalid syntax
>>>
>>> comments
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
comments
NameError: name 'comments' is not defined
>>>
>>> # svknslvksnklsnbslkbn
>>> # this is a note (single line comment)
>>>
>>> # print() -> () paranthesis
>>> print()
>>> # print() ->by default it gives us a new line
>>> print(" My nane is Ram ")
My nane is Ram
>>> print(" My name is Ram ")
My name is Ram
>>> print("Hello, world")
Hello, world
>>> a = 10 # dynamically typed
>>> b = 20
>>> print("a")
a
>>> print(a)
10
>>> print(b)
20
>>> c = a + b
>>> print(c)
30
>>> print("Sum of a and b is c")
Sum of a and b is c
>>> print("C is c")
C is c
>>> print("C is", c)
C is 30
>>> print(" Sum of ", a, "and", b, "is", c)
Sum of 10 and 20 is 30
>>> print("C is %d" %a)
C is 10
>>> print(" Sum of %d and %d is %d " %a,b,c )
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
print(" Sum of %d and %d is %d " %a,b,c )
TypeError: not enough arguments for format string
>>> print(" Sum of %d and %d is %d " %(a,b,c) ) # (a,b,c) -> tuple -> array
Sum of 10 and 20 is 30
>>> print(" Sum of %d and %d is %d " %(a,b, "thirty" ) )
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
print(" Sum of %d and %d is %d " %(a,b, "thirty" ) )
TypeError: %d format: a number is required, not str
>>>
>>>
>>> print("Sum of {} and {} is {}".format(a,b,c) )
Sum of 10 and 20 is 30
>>> print("Sum of {} and {} is {}".format(a,b,"thirty") )
Sum of 10 and 20 is thirty
>>> print("Sum of {} and {} is {}".format(a,b, True) )
Sum of 10 and 20 is True
>>> print("Sum of {} and {} is {}".format(a,b, a+b ) )
Sum of 10 and 20 is 30
>>> print("Sum of {} and {} is {}".format(a,b, d=
) )
SyntaxError: invalid syntax
>>> print("Sum of {} and {} is {}".format(a,b, d=a+b ) )
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
print("Sum of {} and {} is {}".format(a,b, d=a+b ) )
IndexError: tuple index out of range
>>>
>>>
>>> d
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
d
NameError: name 'd' is not defined
>>>
>>>
>>> # walrus operator
>>> print("Sum of {} and {} is {}".format(a,b, d:=a+b ) )
SyntaxError: invalid syntax
>>> print("Sum of {} and {} is {}".format(a,b, d=a+b ) )
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
print("Sum of {} and {} is {}".format(a,b, d=a+b ) )
IndexError: tuple index out of range
>>> print("Sum of {} and {} is {}".format(a,b, a+b ) )
Sum of 10 and 20 is 30
>>>
>>> print("Sum of {} and {} is {}, Diff btw {} and {} is {}, Product of {} and {} is {}, Quotient of {} and {} is {}".format(a,b, a+b, a,b, a-b, a,b, a*b, a,b, a/b ) )
Sum of 10 and 20 is 30, Diff btw 10 and 20 is -10, Product of 10 and 20 is 200, Quotient of 10 and 20 is 0.5
>>> print(" Sum of {} and {} is {},\n Diff btw {} and {} is {},\n Product of {} and {} is {},\n Quotient of {} and {} is {}".format(a,b, a+b, a,b, a-b, a,b, a*b, a,b, a/b ) )
Sum of 10 and 20 is 30,
Diff btw 10 and 20 is -10,
Product of 10 and 20 is 200,
Quotient of 10 and 20 is 0.5
>>> print(" Sum of {} and {} is {},\n Diff btw {} and {} is {},\n Product of {} and {} is {},\n Quotient of {} and {} is {}".format(a,b, a+b, a-b, a*b, a/b) )
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
print(" Sum of {} and {} is {},\n Diff btw {} and {} is {},\n Product of {} and {} is {},\n Quotient of {} and {} is {}".format(a,b, a+b, a-b, a*b, a/b) )
IndexError: tuple index out of range
>>> print(" Sum of {0} and {1} is {2},\n Diff btw {0} and {1} is {3},\n Product of {0} and {1} is {4},\n Quotient of {0} and {1} is {5}".format(a,b, a+b, a-b, a*b, a/b) )
Sum of 10 and 20 is 30,
Diff btw 10 and 20 is -10,
Product of 10 and 20 is 200,
Quotient of 10 and 20 is 0.5
>>>
>>> print(" Sum of a and b is a+b,\n Diff btw {0} and {1} is {3},\n Product of {0} and {1} is {4},\n Quotient of {0} and {1} is {5}")
Sum of a and b is a+b,
Diff btw {0} and {1} is {3},
Product of {0} and {1} is {4},
Quotient of {0} and {1} is {5}
>>> print(" Sum of {a} and {b} is {a+b},\n Diff btw {0} and {1} is {3},\n Product of {0} and {1} is {4},\n Quotient of {0} and {1} is {5}")
Sum of {a} and {b} is {a+b},
Diff btw {0} and {1} is {3},
Product of {0} and {1} is {4},
Quotient of {0} and {1} is {5}
>>> print(f" Sum of {a} and {b} is {a+b},\n Diff btw {0} and {1} is {3},\n Product of {0} and {1} is {4},\n Quotient of {0} and {1} is {5}")
Sum of 10 and 20 is 30,
Diff btw 0 and 1 is 3,
Product of 0 and 1 is 4,
Quotient of 0 and 1 is 5
>>>
>>> print(f" Sum of {a} and {b} is {a+b},\n Diff btw {a} and {b} is {a-b},\n Product of {a} and {b} is {a*b},\n Quotient of {a} and {b} is {a/b}")
Sum of 10 and 20 is 30,
Diff btw 10 and 20 is -10,
Product of 10 and 20 is 200,
Quotient of 10 and 20 is 0.5
>>>
>>> print(f" Sum of {a=} and {b} is {a+b},\n Diff btw {a} and {b} is {a-b},\n Product of {a} and {b} is {a*b},\n Quotient of {a} and {b} is {a/b}")
SyntaxError: invalid syntax
>>>
>>> print('''
ajjcana,nalv
svsbsbsbs
sbsbsb
bsb
sbbsbsb
''')
ajjcana,nalv
svsbsbsbs
sbsbsb
bsb
sbbsbsb
>>> print(f"""
Sum of {a} and {b} is {a+b}
Diff btw {a} and {b} is {a-b}
Product of {a} and {b} is {a*b}
Quotient of {a} and {b} is {a/b}""") #text block
Sum of 10 and 20 is 30
Diff btw 10 and 20 is -10
Product of 10 and 20 is 200
Quotient of 10 and 20 is 0.5
>>> print(f"""Result is:
Sum of {a} and {b} is {a+b}
Diff btw {a} and {b} is {a-b}
Product of {a} and {b} is {a*b}
Quotient of {a} and {b} is {a/b}""") #text block
Result is:
Sum of 10 and 20 is 30
Diff btw 10 and 20 is -10
Product of 10 and 20 is 200
Quotient of 10 and 20 is 0.5
>>> # f-string -> fast, formatting
>>> #Type "help", "copyright", "credits" or "license" for more information.
>>> a = 10
>>> b = 20
>>> print("Sum of {} and {} is {}".format(a,b, d = a+b))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: Replacement index 2 out of range for positional args tuple
>>> print("Sum of {} and {} is {}".format(a,b, d := a+b))
Sum of 10 and 20 is 30
>>> d
30
>>> print(f"Sum of {a} and {b} is {a+b}")
Sum of 10 and 20 is 30
>>> print(f"Sum of {a=} and {b=} is {a+b=}")
Sum of a=10 and b=20 is a+b=30
>>>
|
import csv
# comma separated values
print('''
1. Login
2. Register
''')
choice = int(input("Enter choice: "))
# if choice == 1:
# isLoginSuccessful = False
# usernameOrEmail = input("Enter username/email: ")
# password = input("Enter password: ")
# with open("users.csv") as fileStream:
# reader = csv.reader(fileStream)
# for row in reader:
# if usernameOrEmail == row[0] or usernameOrEmail == row[2]:
# if password == row[3]:
# print("Login successful!")
# isLoginSuccessful = True
# break
# if not isLoginSuccessful:
# print("Login failed")
if choice == 1:
usernameOrEmail = input("Enter username/email: ")
password = input("Enter password: ")
with open("users.csv") as fileStream:
reader = csv.reader(fileStream)
for row in reader:
if usernameOrEmail == row[0] or usernameOrEmail == row[2]:
if password == row[3]:
print("Login successful!")
break
else:
print("Login failed!")
# for-else block
# else says now I'm a follower of for block
# if 'for' loop ends gracefully, else will run
# but if we break the for loop(terminate it abruptly) then else is also terminated hence 'else' block will not run
elif choice == 2:
emailExists = False
username = input("Enter username: ")
fullname = input("Enter fullname: ")
email = input("Enter email: ")
password = input("Enter password: ")
# fileStream = open("users.csv", "w")
# fileStream.close()
with open("users.csv") as fileStream:
reader = csv.reader(fileStream)
for row in reader:
# print(row)
emailFromDB = row[2]
if email == emailFromDB:
print("Email already registered..please login")
emailExists = True
break
if not emailExists:
with open("users.csv", "a", newline='') as fileStream:
writer = csv.writer(fileStream)
writer.writerow([username, fullname, email, password])
print("Registered successfully...")
|
import turtle
screen = turtle.Screen()
screen.bgcolor('black')
pen = turtle.Pen()
pen.color('yellow')
pen.width(3)
pen.turtlesize(2)
pen.shape('turtle')
pen.speed(10)
# for(int i = 0; i < 3; i++){
# for(int j = 0; j < 5; j++){
# print("%d",i);
# }
# }
#only 1 argument -> range(stop)
#2 arguments -> range(start, stop)
#3 arguments -> range(start, stop, step)
'''for i in range(10,300,5):
print(i)'''
'''
for i in range(30):
#print(15*i)
pen.forward(15*i)
pen.left(120)
'''
'''
pen.fillcolor('darkblue')
pen.begin_fill()
for i in range(1):
for j in range(4):
pen.forward(300)
pen.left(90)
pen.end_fill()'''
'''
for i in range(50): pen.circle(5 * i)
'''
#for i in range(10):
while True: # infinite loop
pen.fillcolor('darkblue')
pen.begin_fill()
user_input = input("Enter shape name:")
if user_input == "circle":
pen.circle(100)
elif user_input == "square":
for i in range(4):
pen.forward(200)
pen.left(90)
elif user_input == "triangle":
for i in range(3):
pen.forward(200)
pen.left(120)
elif user_input == "hexagon":
for i in range(6):
pen.forward(150)
pen.left(60)
elif user_input == "pentagon":
for i in range(5):
pen.forward(200)
pen.left(72)
else:
print("Shape doesn't exist")
pen.end_fill()
|
def reverse_url(url):
arr = url.split('/')
rev = ''
for i in reversed(arr):
rev += i + '/'
rev = rev[0:-1]
return rev
|
def pow(num):
if num ==0:
return 1
else:
return 2*pow(num-1)
print pow(565)
|
class Calculator1():
def add(*val1, **val2):
sum = 0
for m in val1:
sum = sum + m
for n in val2.values():
sum = sum + n
return sum
def minus(*val1, **val2):
minus = 0
for m in val1:
minus = minus - m
for n in val2.values():
minus = minus - n
return minus
def mul(*val1, **val2):
mul = 0
for m in val1:
mul = mul * m
for n in val2.values():
mul = mul * n
return mul
def divisions(*val1, **val2):
divisions = 0
for m in val1:
divisions = divisions / m
for n in val2.values():
divisions = divisions / n
return divisions
|
'''def helloWorld():
print("hello world!")
helloWorld()
'''
'''
def func(name):
print("Hi",name)
func("john")
'''
#example 3:
'''def sum(a,b):
return a+b
a=int(input("enter a:"))
b=int(input("enter b:"))
print("sum=",sum(a,b))'''
#example 4
'''
def change_list(list1):
list1.append(20)
list1.append(30)
print("list inside function=",list1)
list1=[10,30,40,50]
change_list(list1)'''
#print("list outside function",list1)
#example 5
'''
def change_String(str):
str =str + "how are you"
print("printing the string inside function:",str)
str="hi i am there"
change_String(str)
'''
#type of argument
'''
:type of argument
1.Required argument
2.keyword argument
3.default argument
4.variable length argument
'''
#Required argument
#example 1
'''def func(name):
message="Hi"+name
return message
name = input("enter the name?")
print(func(name))
'''
#example 2
'''def simple_interest(p,t,r):
return (p*t*r)/100
p=float(input("Enter the principal amount?"))
r=float(input("enter the rate of interest ?"))
t=float(input("enter time in years?"))
print("simple interest",simple_interest(p,r,t))
'''
#example 3
'''def calculate(a,b):
return a+b
#print(calculate(1,6))
a=int(input("a:"))
b=int(input("b:"))
print("result is:",calculate(a,b))'''
#keyword argument
#example 1
'''def func(name,message):
print("print the message with",name,"and",message)
func(name="john",message="hello")
'''
#example 2
'''def simple_interest(p,r,t):
return (p*r*t)/100
print("simpe interest",simple_interest(p=1000,r=5,t=5))
'''
#example 3
'''def simple_interest(p,r,t):
return (p*r*t)/100
print("simple interest",simple_interest(time=5,r=5,p=1000))'''
#default argument
#example 1
'''def printme(name,age=22):
print("my name is",name,"and age is",age)
printme(name="john")
'''
#variable_length argument
'''def printme(*names):
print("type of passed argument is",type(names))
print("print the passed arguments...")
for name in names:
print(name)
printme("john","david","smith","nike")
'''
#scope of variable
#example
def calculate(*args):
sum=0
for arg in args:
sum=sum+arg
print("the sum is ",sum)
sum=0
calculate(10,20,30)
print("result",sum) |
#python set -using curly braces
'''days={"monday","tuesday","wednesday","thusday","friday","saturday","sunday"}
print(days)
print(type(days))
print("looping bthrown the set of element...")
for i in days:
print(i)
'''
#by using set() method
'''days=(["monday","tuesday","wednesday","thusday","friday","saturday","sunday"])
print(days)
print(type(days))
print("looping thrown the set element...")
for i in days:
print(i)
'''
#python set operation
#Adding item in set
'''months=set(["jun","feb","mar","apr","may","june"])
print("\norignal set..")
print(months)
print("\nAdding an item in set...")
months.add("july")
months.add("aug")
print("\nmodified set...")
print(months)
print("looping through the set...")
for i in months:
print(i)'''
#example
'''
months=set(["jan","feb","mar","apr","may","june"])
print(months)
months.add("july")
print("new set...")
print(months)
months.update(["aug","sep","oct","nov","dec"])
print("update set...")
print(months)
#removing item by set
months.discard("may")
months.remove("sep")
print("updated set...")
print(months)
#remove the last item..
months.pop()
months.pop()
print(months)
#remove all item by set...
months.clear()
print(months)'''
#diff. between discard and remove
'''name=set(["k","r","i","p","a"])
name.discard("m")
#name.remove("m")
print(name)
'''
#union of two sets-By using union operator
num=set([1,2,3,4,5,7])
num1=set([5,6,7,8])
'''print(num|num1)
#By using union () method
print(num.union(num1))'''
#intersection of two set..
#by using intersection operator
'''print(num&num1)
print(num.intersection(num1))
'''
'''num2=([7,9,10])
num.intersection_update(num1,num2)
print(num)'''
#difference of two set
'''print(num-num1)
#using different method
print(num.difference(num1))
'''
#set comparision
'''a={1,2,3,4}
b={5,6,7,8}
c={1,3,4,6,7}
d={1,2,3,4,"x","y"}
print(d>a)
print(b>c)
print(a==b)
print(c<b)
print(a==d)
'''
|
import csv
class WordSearch():
grid = []
target_words = []
solved_words = {}
def read_file(self, file_name):
self.grid = []
self.target_words = []
self.solved_words = {}
with open(file_name) as word_search_csv:
grid_reader = csv.reader(word_search_csv)
for i, row in enumerate(grid_reader):
# The first row is the list of words in the grid, those following are the grid
if i == 0:
for word in row:
self.target_words.append(word.upper())
else:
# Since we are treating the grid coordinates as traditional x and y cartesian coords,
# this will input the letters flipped across the diagonal for easy work later
for j, letter in enumerate(row):
if j >= len(self.grid):
self.grid.append([])
self.grid[j].append(letter.upper())
def solve_grid(self):
self.solved_words = {}
for current_word in self.target_words:
word_coords = []
# Search the grid until we find the first letter of the word
for x, row in enumerate(self.grid):
for y, letter in enumerate(row):
if letter == current_word[0]:
# Once we find the first letter, begin a depth-first search in all directions for the rest of the word
word_coords.append((x,y))
x_direction = 0
y_direction = 0
letter_index_in_word = 1
search_coords_stack = []
search_coords_stack.append((x - 1, y))
search_coords_stack.append((x + 1, y))
search_coords_stack.append((x, y - 1))
search_coords_stack.append((x, y + 1))
search_coords_stack.append((x - 1, y - 1))
search_coords_stack.append((x + 1, y - 1))
search_coords_stack.append((x - 1, y + 1))
search_coords_stack.append((x + 1, y + 1))
while len(word_coords) < len(current_word) and len(search_coords_stack) > 0:
next_coord = search_coords_stack.pop()
if len(self.grid) > next_coord[0] >= 0 and len(self.grid[x]) > next_coord[1] >= 0:
current_x_direction = next_coord[0] - x
current_y_direction = next_coord[1] - y
if current_x_direction != 0:
current_x_direction = current_x_direction / abs(current_x_direction)
if current_y_direction != 0:
current_y_direction = current_y_direction / abs(current_y_direction)
if current_x_direction != x_direction or current_y_direction != y_direction:
letter_index_in_word = 1
word_coords = [(x,y)]
x_direction = int(current_x_direction)
y_direction = int(current_y_direction)
if self.grid[next_coord[0]][next_coord[1]] == current_word[letter_index_in_word]:
word_coords.append(next_coord)
if len(word_coords) < len(current_word):
search_coords_stack.append((next_coord[0] + x_direction,
next_coord[1] + y_direction))
letter_index_in_word += 1
else:
# Found the whole word!
self.solved_words[current_word] = word_coords
print(current_word, " : ", word_coords) |
import MapReduce
import sys
"""
Joining records using the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
def mapper(record):
# table: identifies the table the record originates from.
# Can be "line_item" or "order"
# rid: record id, used to join line item to orders
order_id = record[1]
mr.emit_intermediate(order_id, record)
def reducer(order_id, records):
# order_id
# records: list of all records with that order id
for ith, record in enumerate(records):
for record_to_join in records[ith:]:
if record[0] != record_to_join[0]: # if from different tables
mr.emit(record + record_to_join)
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
# split both string a and b into lists of substrings of length n
a = "#include <cs50.h>int main(void){ // get two strings string s = get_string(" "); string t = get_string(" "); // compare strings' addresses if (s == t) { printf(""); } else { printf(""); }"
b = "#include <cs50.h>#include <stdio.h>int main(void){ // get two strings char *s = get_string(" "); char *t = get_string(" "); // compare strings' addresses if (s == t) { printf(""); } else { printf(""); }}"
a = "foobar"
b = "foobar"
n = 6
compList = []
if a == b:
compList.append(a)
else:
aSub = []
for i in range(len(a)):
if len(a) >= n:
aSub.append(a[i:(n+i)])
bSub = []
for i in range(len(b)):
if len(a) >= n:
bSub.append(b[i:(n+i)])
# removing substrings smaller than n
# make a list of substrings that appear in both a and b
for i in range(len(aSub)):
for j in range(len(bSub)):
if aSub[i] == bSub[j]:
compList.append(aSub[i])
# return the list with no duplicates
compList = list(dict.fromkeys(compList))
compList = [x for x in compList if len(x) == n]
print(compList)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 12 20:53:22 2018
@author: 2000
"""
cardapio = {"Sanduíche":12.00, "Suco":6.20, "Nescau":4.50, "Açaí":11.90}
comanda = {}
print("Comanda Eletrônica")
print("0 - Sair da Comanda Eletrônica")
print("1 - Imprimir Cardápio")
print("2 - Adicionar Item à Comanda")
print("3 - Remover Item da Comanda")
print("4 - Imprimir Comanda")
e = int(input("Faça sua escolha:"))
print("\n")
while e != 0:
if e == 1:
print("O cardápio possui os seguintes itens:")
for h in cardapio:
print("{0} (R${1})".format(h, cardapio[h]))
print("\n")
print("Comanda Eletrônica")
print("0 - Sair")
print("1 - Imprimir Cardápio")
print("2 - Adicionar Item")
print("3 - Remover Item")
print("4 - Imprimir Comanda")
e = int(input("Faça sua escolha:"))
elif e == 2:
print("Você selecionou a opção Adicionar Item.")
produto = input("Qual o nome do item a ser adicionado?")
quantidade = float(input("Qual a quantidade pedida?"))
if produto not in cardapio:
print("O produto requisitado não pode ser adquirido nesse comércio.")
elif produto in cardapio and produto not in comanda:
comanda[produto] = quantidade
print("\n")
print("Comanda Eletrônica")
print("0 - Sair")
print("1 - Imprimir Cardápio")
print("2 - Adicionar Item")
print("3 - Remover Item")
print("4 - Imprimir Comanda")
e = int(input("Faça sua escolha:"))
else:
comanda[produto] += quantidade
print("\n")
print("Comanda Eletrônica")
print("0 - Sair")
print("1 - Imprimir Cardápio")
print("2 - Adicionar Item")
print("3 - Remover Item")
print("4 - Imprimir Comanda")
e = int(input("Faça sua escolha:"))
elif e == 3:
print("Você selecionou a opção Remover Item.")
produto2 = input("Qual o nome do item a ser removido?")
quantidade2 = int(input("Qual a quantidade a ser removida?"))
if quantidade >= comanda:
del comanda[produto2]
else:
comanda[produto2] -= quantidade2
elif e == 4:
if len(comanda) == 0:
print("Não há produtos na comanda.")
else:
print("A comanda possui os seguintes itens:")
for h in comanda:
print("{0}, quantidade: {1}".format(h, comanda[h]))
print("\n")
print("Comanda Eletrônica")
print("0 - Sair")
print("1 - Imprimir Cardápio")
print("2 - Adicionar Item")
print("3 - Remover Item")
print("4 - Imprimir Comanda")
e = int(input("Faça sua escolha:"))
print("Até mais.") |
"""
Author: Phillip Riskin
Date: 2020
Project: hackerearth.com practice.
Section: Algorithms
Subsection: Searching
Type: Linear Search
Problem: Maximum Sum
Description:
You are given an array of integers A, you need to find the maximum sum that can be obtained by picking some
non-empty subset of the array. If there are many such non-empty subsets, choose the one with the maximum number of
elements. Print the maximum sum and the number of elements in the chosen subset.
Input:
The first line contains an integer N, denoting the number of elements of the array. Next line contains N
space-separated integers, denoting the elements of the array.
Output:
Print 2 space-separated integers, the maximum sum that can be obtained by choosing some subset and the maximum
number of elements among all such subsets which have the same maximum sum.
Constraints:
1 <= N <= 10^5
-10^9 <= A_i <= 10^9
Sample input:
5
1 2 -4 -2 3
Sample output:
6 3
Explanation:
The chosen subset is {1, 2, 3}
My thoughts:
for number in array:
if negative:
add to negative num set.
if non-negative:
add to non-negative num set.
if non-negative set is not empty:
add all nums in non-negative set
return sum and num nums
else if negative set not empty:
add all nums in negative set
return sum and num nums
else
return default 0, 0
Apparently this problem is worded incorrectly. Subset by definition does not have repeated elements but this
problem expects "subsets" to have repeated elements, therefore it is required to use lists instead of sets.
"""
import os
num_input_lines = 2
def calculate(n: int, nums: list) -> (int, int):
"""
Calculate the maximum sum obtainable by any subset of the given list.
Also calculate the number of elements in the chosen subset.
:param n: The length of the given list.
:param nums: The given list.
:return (int, int): (max sum, num elements in subset).
>>> calculate(5, [1, 2, -4, -2, 3])
(6, 3)
"""
neg_set = list()
non_neg_set = list()
for num in nums:
if num < 0:
neg_set.append(num)
else:
non_neg_set.append(num)
set_sum = 0
num_elements = 0
if len(non_neg_set) > 0:
for element in non_neg_set:
set_sum += element
num_elements += 1
elif len(neg_set) > 0:
set_sum = max(neg_set)
num_elements = 1
return set_sum, num_elements
def parse_input(lines: list) -> (int, list):
"""
Parse two user lines.
Line one: The number of nums.
Line two: The nums.
:param lines: The lines to parse.
:return (int, list): (n, nums).
"""
n = int(lines[0])
line_two = lines[1].split(" ")
nums = [int(x) for x in line_two]
return n, nums
def get_input(num_lines: int) -> list:
"""
Get lines of user input equal to num_lines.
:param num_lines: The number of lines to get from the user.
:return list: A list of user input lines.
"""
lines = []
for i in range(num_lines):
lines.append(input())
return lines
def main():
"""
Get user input, calculate result, print result.
"""
lines = get_input(num_input_lines)
# lines = list()
# with open(os.path.dirname(__file__) + "/input1.txt", "r") as test_input:
# for line in test_input.readlines():
# lines.append(line)
args = parse_input(lines)
list_sum, element_num = calculate(*args)
print(list_sum, element_num)
if __name__ == '__main__':
# import doctest
# doctest.testmod()
main()
|
#!/usr/bin/env python
"""
Author: Adam White, Matthew Schlegel, Mohammad M. Ajallooeian, Sina Ghiassian
Purpose: Skeleton code for Monte Carlo Exploring Starts Control Agent
for use on A3 of Reinforcement learning course University of Alberta Fall 2017
"""
from utils import rand_in_range, rand_un
import numpy as np
import pickle
policy = None
Q = None
Reward = np.zeros((99,99))
Num = np.zeros((99,99))
hit = None
epsilon = 0.1 #you may need change it
def agent_init():
global Q,Num,Reward,epsilon,policy,hit
"""
Hint: Initialize the variables that need to be reset before each run begins
Returns: nothing
"""
#initialize the policy array in a smart way
policy = [min(i,100-i) for i in range(1,100)]
#print policy
Q = np.full((99,99),0.00000000001)
Reward = np.zeros((99,99))
Num = np.full((99,99),1)
resethit()
def agent_start(state):
global Q,Num,Reward,epsilon,policy
"""
Hint: Initialize the variavbles that you want to reset before starting a new episode
Arguments: state: numpy array
Returns: action: integer
"""
# pick the first action, don't forget about exploring starts
action = rand_in_range(min(state[0],100-state[0]))+1
hit[state[0]-1][action-1] += 1
return action
def agent_step(reward, state): # returns NumPy array, reward: floating point, this_observation: NumPy array
global Q,Num,Reward,epsilon,policy
"""
Arguments: reward: floting point, state: integer
Returns: action: integer
"""
# select an action, based on Q
action = policy[state[0]-1]
hit[state[0]-1][action-1] += 1
return action
def agent_end(reward):
global Q,Num,Reward,epsilon,policy,hit
"""
Arguments: reward: floating point
Returns: Nothing
"""
# do learning and update pi
Reward += (hit*reward) #add reward
Num += hit #add hit number
resethit()
Q = Reward/Num #calculae average
for i in range(99):
policy[i] = np.argmax(Q[i])+1
return
def agent_cleanup():
"""
This function is not used
"""
# clean up
return
def agent_message(in_message): # returns string, in_message: string
global Q
"""
Arguments: in_message: string
returns: The value function as a string.
This function is complete. You do not need to add code here.
"""
# should not need to modify this function. Modify at your own risk
if (in_message == 'ValueFunction'):
return pickle.dumps(np.max(Q, axis=1), protocol=0)
else:
return "I don't know what to return!!"
def resethit():
global hit
hit = np.zeros((99,99)) |
""" Nama : Daffa Kenny Nabil Fayyaadh Priadi
NIM : 081911633040
Hari/Tgl: Jum'at, 15 Januari 2021 """
# import parent class
from Parent import Pekerjaan
# Class 'Dosen' akan menjadi child class dengan parent class "Pekerjaan"
class Dosen(Pekerjaan):
# Constructor Overloading dan Overriding dengan super() atau parent class
def __init__(self, owner = None, gender = None, gaji = None, jobdesk = None):
if (gaji != None and jobdesk != None):
self.jobdesk = jobdesk
self.gaji = gaji
super().__init__(owner, gender)
elif (gaji != None):
print("Jobdesk tidak diinputkan, akan diset dengan nilai default 'Minum Kopi'")
self.jobdesk = "Minum Kopi"
self.gaji = gaji
super().__init__(owner, gender)
else:
print("Jobdesk dan Gaji tidak diinputkan, akan diset dengan nilai default")
print("Gaji -> diberi nilai '1500000' ")
self.gaji = 1500000
print("Jobdesk -> diberi nilai 'Minum Kopi' ")
self.jobdesk = "Minum Kopi"
super().__init__(owner, gender)
# Overriding method
def cetak(self):
print("Pekerjaan:", "Dosen")
super().cetak()
print("Gaji : Rp.", self.gaji)
print("Job Desk :", self.jobdesk)
# Class 'WebDeveloper' akan menjadi child class dengan parent class "Pekerjaan"
class WebDeveloper(Pekerjaan):
# Constructor Overloading dan Overriding dengan super() atau parent class
def __init__(self, owner = None, gender = None, gaji = None, jobdesk = None):
if (gaji != None and jobdesk != None):
self.jobdesk = jobdesk
self.gaji = gaji
super().__init__(owner, gender)
elif (gaji != None):
print("Jobdesk tidak diinputkan, akan diset dengan nilai default 'Nyantai di depan laptop'")
self.jobdesk = "Nyantai di depan laptop"
self.gaji = gaji
super().__init__(owner, gender)
else:
print("Jobdesk dan Gaji tidak diinputkan, akan diset dengan nilai default")
print("Gaji -> diberi nilai '7500000' ")
self.gaji = 7500000
print("Jobdesk -> diberi nilai 'Nyantai di depan laptop' ")
self.jobdesk = "Nyantai di depan laptop"
super().__init__(owner, gender)
# Overriding method
def cetak(self):
print("Pekerjaan:", "Web Developer")
super().cetak()
print("Gaji : Rp.", self.gaji)
print("Job Desk :", self.jobdesk)
# Class 'Gamer' akan menjadi child class dengan parent class "Pekerjaan"
class Gamer(Pekerjaan):
# Constructor Overloading dan Overriding dengan super() atau parent class
def __init__(self, owner = None, gender = None, gaji = None, jobdesk = None):
if (gaji != None and jobdesk != None):
self.jobdesk = jobdesk
self.gaji = gaji
super().__init__(owner, gender)
elif (gaji != None):
print("Jobdesk tidak diinputkan, akan diset dengan nilai default 'Main Game'")
self.jobdesk = "Main Game"
self.gaji = gaji
super().__init__(owner, gender)
else:
print("Jobdesk dan Gaji tidak diinputkan, akan diset dengan nilai default")
print("Gaji -> diberi nilai '3750000' ")
self.gaji = 3750000
print("Jobdesk -> diberi nilai 'Main Game' ")
self.jobdesk = "Main Game"
super().__init__(owner, gender)
# Overriding method
def cetak(self):
print("Pekerjaan:", "Pro Player")
super().cetak()
print("Gaji : Rp.", self.gaji)
print("Job Desk :", self.jobdesk)
# Class 'Presiden' akan menjadi child class dengan parent class "Pekerjaan"
class Presiden(Pekerjaan):
# Constructor Overloading dan Overriding dengan super() atau parent class
def __init__(self, owner = None, gender = None, gaji = None, jobdesk = None):
if (gaji != None and jobdesk != None):
self.jobdesk = jobdesk
self.gaji = gaji
super().__init__(owner, gender)
elif (gaji != None):
print("Jobdesk tidak diinputkan, akan diset dengan nilai default 'Ngatur Negara'")
self.jobdesk = "Ngatur Negara"
self.gaji = gaji
super().__init__(owner, gender)
else:
print("Jobdesk dan Gaji tidak diinputkan, akan diset dengan nilai default")
print("Gaji -> diberi nilai '1000000000' ")
self.gaji = 1000000000
print("Jobdesk -> diberi nilai 'Ngatur Negara' ")
self.jobdesk = "Ngatur Negara"
super().__init__(owner, gender)
# Overriding method
def cetak(self):
print("Pekerjaan:", "Presiden")
super().cetak()
print("Gaji : Rp.", self.gaji)
print("Job Desk :", self.jobdesk) |
""" Nama : Daffa Kenny Nabil Fayyaadh Priadi
NIM : 081911633040
Hari/Tgl: Jum'at, 15 Januari 2021 """
# Class 'Pekerjaan' akan menjadi parent class untuk child class yang akan dibuat
class Pekerjaan:
# Constructor Overloading
def __init__(self, owner = None, gender = None):
if (owner == None and gender == None):
print("Owner dan Gender tidak diinputkan, dan akan diset secara default")
print("Owner -> diberi nilai 'Bpk. Daffa Kenny' ")
self.owner = "Bpk. Daffa Kenny"
print("Gender-> diberi nilai 'L/P'")
self.gender = "L/P"
elif (gender == None):
print("Gender tidak diinputkan, akan diset dengan nilai default 'L/P'")
self.gender = "L/P"
self.owner = owner
elif (owner == None):
print("Owner tidak diinputkan, akan diset dengan nilai default 'Bpk. Daffa Kenny'")
self.owner = "Bpk. Daffa Kenny"
self.gender = gender
else:
self.owner = owner
self.gender = gender
# Overriding pada child class
def cetak(self):
print("Owner :", self.owner)
print("Gender :", self.gender) |
from pack.data_structures import Stack
left = Stack("A")
center = Stack("B")
right = Stack("C")
def move_tower(height, from_pole, to_pole, with_pole):
if height >= 1:
move_tower(height - 1, from_pole, with_pole, to_pole)
move_disk(from_pole, to_pole, with_pole)
move_tower(height - 1, with_pole, to_pole, from_pole)
def move_disk(from_pole, to_pole, with_pole):
move = from_pole.pop()
to_pole.push(move)
print("moved disk", move, "from tower", from_pole, "to tower", to_pole)
print(from_pole.items)
print(to_pole.items)
print(with_pole.items)
def main():
start_height = 3
for i in range(start_height, 0, -1):
left.push(i)
move_tower(start_height, left, center, right) |
import turtle
import random
hilbert = turtle.Turtle()
hilbert.speed("fastest")
hilbert.pensize("3")
space = turtle.Screen()
def curve(turtle, size, angle, order):
selector = []
for i in range(order + 1, 0, -1):
selector.append(i)
h_line = "--- " * selector[order]
indent = " " * selector[order]
colors = ["red", "green", "blue"]
if order == 0:
pass
else:
turtle.color(random.choice(colors))
print(h_line, "Curve Start |", "Color:", turtle.pencolor(), "|", "Order:", order, h_line, "\n")
turtle.right(angle)
print(indent, "turning", angle, "degrees","\n")
curve(turtle, size, -angle, order - 1)
print("1st Recursive Call", "Order is", order, "\n")
turtle.forward(size)
print(indent, "going forward", size, "\n")
turtle.left(angle)
print(indent, "turning", angle, "degrees", "\n")
curve(turtle, size, angle, order - 1)
print("2nd Recursive Call", "Order is", order, "\n")
turtle.forward(size)
print(indent, "going forward", size, "\n")
curve(turtle, size, angle, order - 1)
print("3rd Recursive Call", "Order is", order, "\n")
turtle.left(angle)
print(indent, "turning", angle, "degrees", "\n")
turtle.forward(size)
print(indent, "going forward", size, "\n")
curve(turtle, size, -angle, order - 1)
print("4th Recursive Call", "Order is", order, "\n")
turtle.right(angle)
print(indent, "turning", angle, "degrees", "\n")
print(h_line, "Curve End", h_line, "\n")
turtle.color("black")
def main():
curve(hilbert, 10, 90 , 40)
space.exitonclick() |
# similar to dictionary
# hashed and immutable
# used less often
# good for cleaning up data
farm_animals = {"sheep", "cow", "hen"}
print(farm_animals)
for animal in farm_animals:
print(animal)
print("=" * 40)
wild_animals = set(["lion", "tiger", "panther", "elephant", "hare"])
print(wild_animals)
for animal in wild_animals:
print(animal)
farm_animals.add("horse")
wild_animals.add("horse")
print(farm_animals)
print(wild_animals)
# no inherint ordering
# user set() to create an empty set
empty_set = set()
# empty_set_2 = {} // doesn't create empty set
empty_set.add("a")
# empty_set_2.add("a") // cannot add
even = set(range(0, 42, 2))
print(even)
squares_tuple = (4, 6, 9, 16, 25)
squares = set(squares_tuple)
print(squares)
print(len(even))
print(len(squares))
print(even.union(squares))
print(len(even.union(squares)))
print(squares.union(even))
print("-" * 40)
print(even.intersection(squares))
print(even & squares)
print(squares.intersection(even))
print(squares & even)
print("-" * 40)
print(sorted(even))
print(sorted(squares))
print("even minus squares")
print(sorted(even.difference(squares)))
print(sorted(even - squares))
print("squares minus even")
print(squares.difference(even))
print(sorted(squares - even))
print("=" * 40)
print(sorted(even))
print(squares)
# even.difference_update(squares) // commented bc of symmertric_diff
print(sorted(even))
print("-" * 40)
print("symmetric even minus squares")
print(sorted(even.symmetric_difference(squares)))
print("symmetric squares minus even")
print(squares.symmetric_difference(even))
print(squares ^ even) # shorthand
# don't rely on python to sort
print("-" * 40)
# discard vs remove, remove raises error if no object
squares.discard(4)
squares.remove(16)
squares.discard(8) # no error, does nothing
# squares.remove(8) # error
print(squares)
try:
squares.remove(8)
except KeyError:
print("The item 8 is not a member of the set")
print("=-" * 20)
even = set(range(0, 40, 2))
squares_tuple = (4, 6, 16)
squares = set(squares_tuple)
if squares.issubset(even):
print("squares is a subset of even")
if even.issuperset(squares):
print("even is a superset of squares")
print("*" * 40)
even = frozenset(range(0, 100, 2))
print(even)
even.add(3) # error frozen set
|
from typing import List
def sort_priority(values: List[int], group: set) -> bool:
found = False
def helper(x: int) -> (int, int): # type: ignore
nonlocal found # nonlocalを宣言することで、クロージャ内のfoundが、helper以外で定義された変数と認識する
print(f"x: {x}")
if x in group:
found = True
return (0, x)
return (1, x)
values.sort(key=helper)
return found
numbers = [1, 3, 8, 9, 2, 5]
group = {2, 3, 5, 7}
found = sort_priority(numbers, group)
print(f"sorted numbers: {numbers}, found: {found}")
|
from math import log10
from typing import List, Optional
def display_solution(solution: List[int], assignments, time: float = None, solution_nbr: Optional[int] = None) -> None:
# solution is a list of col variables, i.e., for each column, the row in which the queen appears.
if len(solution) <= 50:
solution = {row: col for (col, row) in enumerate(solution)}
sol = sorted([(r, c) for (r, c) in solution.items()])
# To print the board must convert solution to a list of row variables,
# i.e., for each row, the column in which the queen appears.
placement_vector = [c for (_, c) in sol]
solution_display = layout(placement_vector)
if solution_nbr:
print(f'\n{solution_nbr}.', end='')
print(f'\n{solution_display}')
if time:
print(f'\nFound a solution after {assignments} assignments.')
print(f'Time: {time} sec.')
def layout(placement_vector: [int]) -> str:
"""
Format the placement_vector for display.
The placement_vector is a series of col numbers, one for each row.
"""
board_size = len(placement_vector)
# Generate the column headers.
col_hdrs = ' '*(4+int(log10(board_size))) + \
' '.join([f'{n:2}' for n in range(1, board_size+1)]) + ' col#\n'
display = col_hdrs + '\n'.join([one_row(r, c, board_size)
for (r, c) in enumerate(placement_vector)])
return display
def one_row(row: int, col: int, board_size: int) -> str:
""" Generate one row of the board. """
# (row, col) is the queen position expressed in 0-based indices for this row.
# Since we want 1-based labels increment row and col by 1.
return f'{space_offset(row+1, board_size)}{row+1}) ' + \
f'{" . "*col} Q {" . "*(board_size-col-1)} {space_offset(col+1, board_size)}({col+1})'
def space_offset(n: int, board_size: int) -> str:
return " "*(int(log10(board_size)) - int(log10(n)))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from itertools import permutations
def combinatorial_analysis(value):
'''
Utilizando os métodos de programação funcional, complete o método combinatorial_analysis e caso de teste, de modo que o mesmo receba como
parâmetro um número inteiro positivo N (0 < N < 1000), e retorne uma lista com as combinações possíveis para os algarismos
que compõem N, observando ainda as seguintes restrições:
( i ) não devem ser considerados no resultado números, iniciados por 0;
( ii ) não devem ser geradas combinações repetidas;
Exemplo: 120 -> [102, 120, 201, 210]
Para gerar as combinações possíveis, utilize o método permutations do módulo itertools, visite o link:
https://docs.python.org/3.7/library/itertools.html#itertools.permutations
'''
x = str(value)
y = list(x)
z = map(lambda x: ''.join(x), permutations(y, len(y)))
w = list(set(z))
# sort combinations
k = list(filter(lambda x: not x.startswith('0'), w))
result = list(map(int, k))
# delete numbers starts with 0
# while(combinations[0].startswith('0')): combinations.pop(0)
result.sort()
return result |
############################################################
######## EP1 DE MECANICA COMPUTACIONAL - PMR3401
# ##### ALUNOS:
# Gustavo Correia Neves Carvas - NUSP 10335962
# Luana Marsano da Costa Nunes - NUSP 10333640
#
############################################################
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import subplot
from sympy import *
import matplotlib.animation as animation
######## Classe que servirá para guardar todas as variavéis que utilizaremos para fazer contas e para a plotagem dos gráficos
class MatrizTudo(object):
def __init__(self, n,*args, **kwargs):
# Matriz de dimensão 6 x n, uma linha para cada variável,nesta ordem:
# theta1
# theta2
# theta1_dot
# theta2_dot
# theta1_2dot
# theta2_2dot
#
# O tamanho n é definido pelo tempo que a simulação vai ocorrer dividido pelo passo
self._matriz = np.zeros((6,n))
def variaveis(self, k):
# Função que retorna o vetor [ theta1, theta2, theta1_dot, theta2_dot ] na posição k (iteração)
return self._matriz[0:4,k]
def set_variaveis(self,array, k):
# Função para definir os valores do vetor [ theta1, theta2, theta1_dot, theta2_dot ] na posição k (iteração)
# Utilizada para guardar os valores de k+1 nas contas de cada um dos métodos
self._matriz[0:4,k] = array
def derivadas(self, k):
# Função que retorna o vetor [ theta1_dot, theta2_dot, theta1_2dot, theta2_2dot ] na posição k (iteração)
# Utilizada no método Euler para simplificação da conta
return self._matriz[2:6,k]
def cond_iniciais(self,array):
# Função utilizada no inicio do programa para setar a primeira coluna de variaveis, ou seja, condições iniciais
self._matriz[:,0] = array
def theta1(self,k):
# Função retorna a variavel theta1 na posição k
return self._matriz[0,k]
def theta2(self,k):
# Função retorna a variavel theta2 na posição k
return self._matriz[1,k]
def theta1_dot(self,k):
# Função retorna a variavel theta1_dot na posição k
return self._matriz[2,k]
def theta2_dot(self,k):
# Função retorna a variavel theta2_dot na posição k
return self._matriz[3,k]
def theta1_2dot(self,k):
# Função retorna a variavel theta1_2dot na posição k
return self._matriz[4,k]
def set_theta1_2dot(self,value,k):
# Função guarda o valor da variavel theta1_2dot na posição k
# Utilizado para guardar os valores calculados em cada iteração, com o intuito de permitir a plotagem dos gráficos
self._matriz[4,k] = value
def theta2_2dot(self,k):
# Função retorna a variavel theta2_2dot na posição k
return self._matriz[5,k]
def set_theta2_2dot(self,value,k):
# Função guarda o valor da variavel theta2_2dot na posição k
# Utilizado para guardar os valores calculados em cada iteração, com o intuito de permitir a plotagem dos gráficos
self._matriz[5,k] = value
def calc_theta1_2dot(theta1,theta2,theta1_dot,theta2_dot,A):
# A0 = (L1**2)*L2*R*(m2*math.cos(2*theta1-2*theta2)-2*m1-m2)
# A1 = (L1**2)*L2*R*m2*math.sin(2*theta1-2*theta2)
# A2 = 2*L1*(L2**2)*R*m2*math.sin(theta1-theta2)
# A3 = -2*L2*mi*Iz*Vel
# A4 = -2*L1*mi*Iz*Vel*math.cos(theta1-theta2)
# A5 = -R*L1*(L2eixo*F2*math.sin(theta1-2*theta2)+2*math.sin(theta1)*(F1*L2+(L2eixo*F2)/2))
return ((A[1](theta1,theta2)*theta1_dot**2+A[2](theta1,theta2)*theta2_dot**2+A[3](theta1,theta2)*theta1_dot+A[4](theta1,theta2)*theta2_dot + A[5](theta1,theta2))/A[0](theta1,theta2))
def calc_theta2_2dot(theta1,theta2,theta1_dot,theta2_dot,theta1_2dotvar,B):
# B0 = (L2**2)*R*m2
# B1 = -L1*L2*R*m2*math.cos(theta1-theta2)
# B2 = L1*L2*R*m2*math.sin(theta1-theta2)
# B3 = -mi*Iz*Vel
# B4 = L2eixo*math.sin(theta2)*R*F2
return ((B[1](theta1,theta2)*theta1_2dotvar+B[2](theta1,theta2)*theta1_dot**2+B[3](theta1,theta2)*theta2_dot+B[4](theta1,theta2))/B[0](theta1,theta2))
def eulerMethod(MatrizTd, h, n, A, B):
for k in range(n-1):
theta1_2dot = calc_theta1_2dot(MatrizTd.theta1(k),MatrizTd.theta2(k),MatrizTd.theta1_dot(k),MatrizTd.theta2_dot(k),A)
MatrizTd.set_theta1_2dot(theta1_2dot,k)
theta2_2dot = calc_theta2_2dot(MatrizTd.theta1(k),MatrizTd.theta2(k),MatrizTd.theta1_dot(k),MatrizTd.theta2_dot(k),theta1_2dot,B)
MatrizTd.set_theta2_2dot(theta2_2dot,k)
proxIterVar = np.add(MatrizTd.variaveis(k),np.multiply(MatrizTd.derivadas(k),h))
# proxIterVar = MatrizTd.variaveis(k)+h*MatrizTd.derivadas(k)
MatrizTd.set_variaveis(proxIterVar,k+1)
def rungeKutta2(Mtd,h,n,A,B):
# Definição das funções que serão utilizadas para calcular os parametros do método RK
def kx(theta1_dot):
return theta1_dot
def lx(theta1,theta2,theta1_dot,theta2_dot):
return calc_theta1_2dot(theta1,theta2,theta1_dot,theta2_dot,A)
def mx(theta2_dot):
return theta2_dot
def nx(theta1,theta2,theta1_dot,theta2_dot,theta1_2dotvar):
return calc_theta2_2dot(theta1,theta2,theta1_dot,theta2_dot,theta1_2dotvar,B)
# Inicio loop que aplicará o algoritmo do método
for k in range(n-1):
# Inicializando variaveis dessa iteração com nomes mais intuitivos para utilização de inputs nas funções
[theta1,theta2,theta1_dot,theta2_dot] = Mtd.variaveis(k)
# Calculo das segundas derivadas que serão utilizadas nas funções dessa iteração
theta1_2dot = calc_theta1_2dot(theta1,theta2,theta1_dot,theta2_dot,A)
theta2_2dot = calc_theta2_2dot(theta1,theta2,theta1_dot,theta2_dot,theta1_2dot,B)
# Armazenamento das segundas derivadas para permitir a plotagem das mesmas no final
Mtd.set_theta1_2dot(theta1_2dot,k)
Mtd.set_theta2_2dot(theta2_2dot,k)
####### Calculo de #1
############## K1
k1 = kx(theta1_dot)
############## L1
l1 = theta1_2dot
############## M1
m1 = mx(theta2_dot)
############## N1
n1 = theta2_2dot
####### Calculo de #2
############## K2
k2 = kx(theta1_dot+h*l1)
############## L2
l2 = lx(theta1+h*k1,theta2+h*m1,theta1_dot+h*l1,theta2_dot+h*n1)
############## M2
m2 = mx(theta2_dot+h*n1)
############## N2
n2 = nx(theta1+h*k1,theta2+h*m1,theta1_dot+h*l1,theta2_dot+h*n1,l2)
############CALCULO PROXIMA ITERAÇÃO
# Vetor que será multiplicado por h e somado nas variaveis
somas = np.array([(k1+k2)/2,(m1+m2)/2,(l1+l2)/2,(n1+n2)/2])
# Variaveis[k+1] = Variaveis[k] + h*(k1+k2)/2
proxIterVar = np.add(Mtd.variaveis(k),np.multiply(somas,h))
Mtd.set_variaveis(proxIterVar,k+1)
def rungeKutta4(Mtd,h,n,A,B):
# Definição das funções que serão utilizadas para calcular os parametros do método RK
def kx(theta1_dot):
return theta1_dot
def lx(theta1,theta2,theta1_dot,theta2_dot):
return calc_theta1_2dot(theta1,theta2,theta1_dot,theta2_dot,A)
def mx(theta2_dot):
return theta2_dot
def nx(theta1,theta2,theta1_dot,theta2_dot,theta1_2dotvar):
return calc_theta2_2dot(theta1,theta2,theta1_dot,theta2_dot,theta1_2dotvar,B)
# Inicio loop que aplicará o algoritmo do método
for k in range(n-1):
# Inicializando variaveis dessa iteração com nomes mais intuitivos para utilização de inputs nas funções
[theta1,theta2,theta1_dot,theta2_dot] = Mtd.variaveis(k)
# Calculo das segundas derivadas que serão utilizadas nas funções dessa iteração
theta1_2dot = calc_theta1_2dot(theta1,theta2,theta1_dot,theta2_dot,A)
theta2_2dot = calc_theta2_2dot(theta1,theta2,theta1_dot,theta2_dot,theta1_2dot,B)
# Armazenamento das segundas derivadas para permitir a plotagem das mesmas no final
Mtd.set_theta1_2dot(theta1_2dot,k)
Mtd.set_theta2_2dot(theta2_2dot,k)
####### Calculo de #1
############## K1
k1 = kx(theta1_dot)
############## L1
l1 = theta1_2dot
############## M1
m1 = mx(theta2_dot)
############## N1
n1 = theta2_2dot
####### Calculo de #2
############## K2
k2 = kx(theta1_dot+(h/2)*l1)
############## L2
l2 = lx(theta1+(h/2)*k1,theta2+(h/2)*m1,theta1_dot+(h/2)*l1,theta2_dot+(h/2)*n1)
############## M2
m2 = mx(theta2_dot+(h/2)*n1)
############## N2
n2 = nx(theta1+(h/2)*k1,theta2+(h/2)*m1,theta1_dot+(h/2)*l1,theta2_dot+(h/2)*n1,l2)
####### Calculo de #3
############## K3
k3 = kx(theta1_dot+(h/2)*l2)
############## L3
l3 = lx(theta1+(h/2)*k2,theta2+(h/2)*m2,theta1_dot+(h/2)*l2,theta2_dot+(h/2)*n2)
############## M3
m3 = mx(theta2_dot+(h/2)*n2)
############## N3
n3 = nx(theta1+(h/2)*k2,theta2+(h/2)*m2,theta1_dot+(h/2)*l2,theta2_dot+(h/2)*n2,l3)
####### Calculo de #4
############## K4
k4 = kx(theta1_dot+h*l3)
############## L4
l4 = lx(theta1+h*k3,theta2+h*m3,theta1_dot+h*l3,theta2_dot+h*n3)
############## M4
m4 = mx(theta2_dot+h*n3)
############## N4
n4 = nx(theta1+h*k3,theta2+h*m3,theta1_dot+h*l3,theta2_dot+h*n3,l4)
############CALCULO PROXIMA ITERAÇÃO
# Vetor que será multiplicado por h e somado nas variaveis
somas = np.array([(k1+2*k2+2*k3+k4)/6,(m1+2*m2+2*m3+m4)/6,(l1+2*l2+2*l3+l4)/6,(n1+2*n2+2*n3+n4)/6])
# Variaveis[k+1] = Variaveis[k] + h*(k1+2*k2+2*k3+k4)/6
proxIterVar = np.add(Mtd.variaveis(k),np.multiply(somas,h))
Mtd.set_variaveis(proxIterVar,k+1)
def criaConstEqMov():
# O intuito dessa função é simplificar as expressões determinadas no enunciado do Exercício Programa
# de maneira a não ter que realizar todas as operações entre as constantes em todo calculo das segundas derivadas
# Assim não realizamos o mesmo calculo de maneira desnecessária
# O cálculo feito aqui é basicamente isso: 3*(2**2)*(X-3) ---> 12x - 36
## Definição das constantes
L1=2
L2=2.5
L2eixo=1.8
m1=450
m2=650
g=9.81
F1=-0.5*m1*g
F2=-0.5*m2*g
miIz=2.7
R=0.3
Vel=80/3.6
## Definição de que variaveis as expressoes estão em função de, para funcionamento da função lambdify da biblioteca sympy
theta1 = symbols('theta1')
theta2 = symbols('theta2')
theta1_dot = symbols('theta1_dot')
theta2_2dot = symbols('theta2_2dot')
theta1_2dotvar = symbols('theta1_2dotvar')
## Escrita das expressões
A0 = (L1**2)*L2*R*(m2*cos(2*theta1-2*theta2)-2*m1-m2)
A1 = (L1**2)*L2*R*m2*sin(2*theta1-2*theta2)
A2 = 2*L1*(L2**2)*R*m2*sin(theta1-theta2)
A3 = -2*L2*miIz*Vel
A4 = -2*L1*miIz*Vel*cos(theta1-theta2)
A5 = -R*L1*(L2eixo*F2*sin(theta1-2*theta2)+2*sin(theta1)*(F1*L2+(L2eixo*F2)/2))
B0 = (L2**2)*R*m2
B1 = -L1*L2*R*m2*cos(theta1-theta2)
B2 = L1*L2*R*m2*sin(theta1-theta2)
B3 = -miIz*Vel
B4 = L2eixo*sin(theta2)*R*F2
# Criação do array e loop que lerá as expressões e criará as simplificações
array = np.array([[A0,A1,A2,A3,A4,A5,B0,B1,B2,B3,B4],[0,0,0,0,0,0,0,0,0,0,0]])
for i in range(11):
# Simplify observa os valores que determinei como variaveis e simplifica as expressões com base nisso
temp = simplify(array[0,i])
# Lambdify torna as expressões simplificadas em funções de python dependentes de theta1 e theta2
array[1,i] = lambdify((theta1,theta2),temp)
############### Retornando 2 vetores, o primeiro com cada uma das expressões de A e o outro com cada expressão de B
return array[1,:6],array[1, 6:]
def main():
## Definição de tamanhos utilizados na animação
L1=2
L2=2.5
L2eixo=1.8
## Definição das condicões iniciais
theta1_i = 0
theta2_i = 0
theta1dot_i = 0.4
theta2dot_i = -0.1
# Definição do intervalo de tempo da simulação
tf = 60
ti = 0
## Aréa de imput do usuário, onde ele pode escolher o método a ser utilizado e o passo
print("Selecione o método que deseja realizar: \n0 - Método de Euler \n1 - RK2 \n2 - RK4")
metodo = int(input("Sua escolha: "))
h = float(input("Defina o tamanho do passo que será utilizado: "))
# Criação das variáveis, funções e atualização da matriz para inicio dos métodos
n = int((tf-ti)/h) # Tamanho dos vetores
A, B = criaConstEqMov()
MatrizTd = MatrizTudo(n)
temp = calc_theta1_2dot(theta1_i,theta2_i,theta1dot_i,theta2dot_i,A)
MatrizTd.cond_iniciais([theta1_i,theta2_i,theta1dot_i,theta2dot_i,temp,calc_theta2_2dot(theta1_i,theta2_i,theta1dot_i,theta2dot_i,temp,B)])
if metodo == 0:
print("Você selecionou método de Euler com passo",h)
eulerMethod(MatrizTd, h, n, A, B)
textoGrafico = 'Euler'
elif metodo == 1:
rungeKutta2(MatrizTd, h, n, A, B)
textoGrafico = 'Euler Modificado/RK2'
elif metodo == 2:
rungeKutta4(MatrizTd, h, n, A, B)
textoGrafico = 'RK4'
############ Inicio Plotagem e Animação
t = np.linspace(ti,tf,n) #vetor tempo
plt.figure(1)
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.45)
subplot(3,2,1)
plt.title(r"${\Theta}_1$ para "+textoGrafico+ " com passo " + str(h))
plt.xlabel('t (s)')
# plt.ylabel('theta1 (rad)')
plt.ylabel(r"${\Theta}_1$[rad]")
plt.plot(t,MatrizTd._matriz[0])
subplot(3,2,2)
plt.title(r"${\Theta}_2$ para "+textoGrafico+ " com passo " + str(h))
plt.xlabel('t (s)')
plt.ylabel(r"${\Theta}_2$[rad]")
plt.plot(t,MatrizTd._matriz[1])
subplot(3,2,3)
plt.title(r"$\dot{\Theta}_1$ para "+textoGrafico+ " com passo " + str(h))
plt.xlabel('t (s)')
plt.ylabel(r"$\dot{\Theta}_1$[rad/s]")
plt.plot(t,MatrizTd._matriz[2])
subplot(3,2,4)
plt.title(r"$\dot{\Theta}_2$ para "+textoGrafico+ " com passo " + str(h))
plt.xlabel('t (s)')
plt.ylabel(r"$\dot{\Theta}_2$[rad/s]")
plt.plot(t,MatrizTd._matriz[3])
subplot(3,2,5)
plt.title(r"$\ddot{\Theta}_1$ para "+textoGrafico+ " com passo " + str(h))
plt.xlabel('t (s)')
plt.ylabel(r"$\ddot{\Theta}_1[rad/s^2]$")
plt.plot(t,MatrizTd._matriz[4])
subplot(3,2,6)
plt.title(r"$\ddot{\Theta}_2$ para "+textoGrafico+ " com passo " + str(h))
plt.xlabel('t (s)')
plt.ylabel(r"$\ddot{\Theta}_2[rad/s^2]$")
plt.plot(t,MatrizTd._matriz[5])
## CALCULO DE DA POSIÇÃO DE CADA PONTO NECESSÁRIO PARA ANIMAÇÃO
x1 = L1*np.sin(MatrizTd._matriz[0])
y1 = -L1*np.cos(MatrizTd._matriz[0])
x1rodaEsquerda = 0.75*np.cos(MatrizTd._matriz[0]) + x1
y1rodaEsquerda = 0.75*np.sin(MatrizTd._matriz[0]) + y1
x1rodaDireita = -0.75*np.cos(MatrizTd._matriz[0]) + x1
y1rodaDireita = -0.75*np.sin(MatrizTd._matriz[0]) + y1
x2 = L2eixo*np.sin(MatrizTd._matriz[1]) + x1
y2 = -L2eixo*np.cos(MatrizTd._matriz[1]) + y1
x2rodaEsquerda = 0.75*np.cos(MatrizTd._matriz[1]) + x2
y2rodaEsquerda = 0.75*np.sin(MatrizTd._matriz[1]) + y2
x2rodaDireita = -0.75*np.cos(MatrizTd._matriz[1]) + x2
y2rodaDireita = -0.75*np.sin(MatrizTd._matriz[1]) + y2
x2eixo = L2*np.sin(MatrizTd._matriz[1]) + x1
y2eixo = -L2*np.cos(MatrizTd._matriz[1]) + y1
fig = plt.figure(2)
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-5, 5), ylim=(-6, 0))
ax.grid()
line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
def init():
line.set_data([], [])
time_text.set_text('')
return line, time_text
def animate(i):
thisx = [0, x1[i],x1rodaDireita[i],x1rodaEsquerda[i],x1[i],
x2[i], x2rodaDireita[i], x2rodaEsquerda[i], x2[i], x2eixo[i]]
thisy = [0, y1[i],y1rodaDireita[i],y1rodaEsquerda[i],y1[i], y2[i],y2rodaDireita[i], y2rodaEsquerda[i], y2[i], y2eixo[i]]
line.set_data(thisx, thisy)
time_text.set_text(time_template % (t[i]))
return line, time_text
ani = animation.FuncAnimation(fig, animate, np.arange(1, len(t)),
interval=5, blit=True, init_func=init,save_count=50)
# ani.save('Ep1.mp4', fps=15)
plt.show()
main()
|
"""Make Gaussian distribution
"""
import numpy as np
def make_gaussian(size, sigma=8, center=None):
""" Make a square gaussian kernel.
Size is the length of a side of the square
sigma is standard deviation.
Idea from this gist: https://gist.github.com/andrewgiessel/4635563
With additions for skewed gaussian
original output: np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / sigma ** 2)
"""
x = np.arange(0, size[0], 1, float)
y = np.arange(0, size[1], 1, float)
y = y[:, np.newaxis]
if center is None:
x0 = size[0] // 2
y0 = size[1] // 2
print("center is not given")
else:
x0 = center[0]
y0 = center[1]
# choose given sigma for the shortest side
# if size[0] < size[1]:
# sigma = max(int(0.1 * size[0]), 1)
# sigma_1 = sigma
# sigma_2 = max((size[1] * sigma) // (size[0] + 1), 1)
# else:
# sigma = max(int(0.1 * size[1]), 1)
# sigma_2 = sigma
# sigma_1 = max((size[0] * sigma) // (size[1] + 1), 1)
# if sigma_1==0:
# sigma_1 = 1
# if sigma_2 == 0:
# sigma_2 = 1
sigma_1 = sigma_2 = sigma
patch = np.exp(
-(((x - x0) ** 2) / sigma_1 ** 2 + ((y - y0) ** 2) / sigma_2 ** 2)
)
return patch
if __name__ == "__main__":
import matplotlib.pyplot as plt
blank = np.zeros([200, 200])
w = 60
gaussian_patch = make_gaussian([w, 100], sigma=8)
blank[0:100, 0:w] = gaussian_patch
plt.figure()
plt.imshow(blank)
plt.show()
|
import random
import sys
X = "X"
O = "O"
computer_calls = []
human_calls = []
stall_count = 0
def computer_call(call_list):
call = random.randrange(1,29)
while call in call_list:
call = random.randrange(1,29)
return call
def legal_move(call,call_list,board,other_player_last_call):
if call in call_list:
return False
return (call + other_player_last_call) in board
def computer_move(board,call_list,other_player_last_call,computer_piece):
call = computer_call(call_list)
for i in range(100):
if legal_move(call,call_list,board,other_player_last_call):
print("Computer calls ",call, "\n")
call_list.append(call)
board[board.index(call+other_player_last_call)] = computer_piece
display_board(board)
return
call = computer_call(call_list)
print("STALL. GAME OVER.")
exit()
def human_call():
call = int(input("Please input a number between 1 and 28: "))
while call not in range(1,29):
call = int(input("Please input a number between 1 and 28: "))
return call
def human_move(board,call_list,other_player_last_call,computer_piece):
call = human_call()
if legal_move(call,call_list,board,other_player_last_call):
call_list.append(call)
board[board.index(call+other_player_last_call)] = computer_piece
display_board(board)
else:
print("Sorry, illegal move.")
def display_instruct ():
"""Display game instructions."""
print (
"""
Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a number from 1-28.
This number will then be added to the previously called number.
If there exists a square with this number that is unmarked your marker will be put there.
Prepare yourself, human. The ultimate battle is about to begin. \n
""")
def pieces():
"""Determine if player or computer goes first."""
go_first = ask_yes_no("Do you require the first move? (y/n): ")
if go_first == "y":
print ("\nThen take the first move. You will need it.")
hum = X
com = O
else:
print ("\nYour bravery will be your undoing... I will go first.")
com = X
hum = O
return com, hum
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def display_board(board):
for i in range(0,4):
for j in range(0,4):
print(board[i*4+j],end="\t")
print()
print("\n")
def make_board():
random_board = []
for i in range(16):
number = random.randrange(2,33)
while number in random_board:
number = random.randrange(2,33)
random_board.append(number)
display_board(random_board)
return random_board
def draw(board):
for entry in board:
if not(entry == X or entry == O):
return False
return True
def winner(board):
# check rows
for i in range(4):
first_square = board[i*4]
four_in_line = True
for j in range(1,4):
if board[i*4+j] != first_square:
four_in_line = False
break
if four_in_line:
return True
# check columns
for j in range(4):
i = 0
first_square = board[i*4+j]
four_in_line = True
for i in range(1,4):
if board[i*4+j] != first_square:
four_in_line = False
break
if four_in_line:
return True
# check leading diagnonal
first_square = board[0]
four_in_line = True
for (i,j) in [(1,1),(2,2),(3,3)]:
if board[i*4+j] != first_square:
four_in_line = False
break
if four_in_line:
return True
# check trailing diagonal
first_square = board[3]
four_in_line = True
for (i,j) in [(1,2),(2,1),(3,0)]:
if board[i*4+j] != first_square:
four_in_line = False
break
if four_in_line:
return True
return False
#main
display_instruct()
computer_piece, human_piece = pieces()
board = make_board()
if computer_piece == O: # Human calls first
human_calls.append(human_call())
current_turn = computer_piece
else:
computer_calls.append(computer_call(computer_calls))
print("Computer calls ",computer_calls[-1], "\n")
current_turn = human_piece
while not (winner(board) or draw(board)):
if (current_turn == computer_piece):
computer_move(board,computer_calls,human_calls[-1],computer_piece)
current_turn = human_piece
else:
human_move(board,human_calls,computer_calls[-1],human_piece)
current_turn = computer_piece
if winner(board):
if current_turn == human_piece:
print("Sorry, I win. Better luck next time.")
else:
print("Congratulations! You won!!!!")
else:
print("DRAW!!")
|
n = -1
am = -1
while n != 0:
n = int(input())
if n % 2 == 0:
am += 1
print(am)
|
previous = -1
current_len = 0
max_len = 0
n = int(input())
while n != 0:
if previous == n:
current_len += 1
else:
previous = n
max_len = max(max_len, current_len)
current_len = 1
n = int(input())
max_len = max(max_len, current_len)
print(max_len)
|
#! /usr/bin/python
from matrix import Matrix
from variable import Variable
def leastsquares(A,b):
ret = "\\begin{align*}\n"
Atrans = A.transpose()
ret += " A^TA &= " + Atrans.toString() + A.toString() + " = " + (Atrans*A).toString() + " \\\\\n"
ret += " A^Tb &= " + Atrans.toString() + b.toString() + " = " + (Atrans*b).toString() + " \\\\\n"
ret += "\\end{align*}\n"
ret += "Then the equation $A^TAx = A^Tb$ becomes $$" + (Atrans*A).toString()
ret += Matrix([ [Variable("x_"+str(i+1))] for i in range(len(Atrans))]).toString()
ret += "=" + (Atrans*b).toString() + "$$\n"
ret += "Then to solve $A^TAx = A^Tb$ as \\begin{align*}\n"
ret += " \hat{x} \n &= \left(A^TA\\right)^{-1}A^Tb \\\\\n"
ret += "\\end{align*}"
return ret
if __name__ == "__main__":
A = []
r = raw_input()
while(r):
A.append(r.split())
r = raw_input()
A = Matrix(A)
b = Matrix( [ [x] for x in raw_input().split() ])
print leastsquares(A,b)
|
'''
Created on May 30, 2014
Illustrative example which shows how duck typing can work.
Each of the classes exhibits the duck-like behavior, while only the Not_A_Duck exhibits other expected behaviors as well.
When the function make_it_quack is executed with either class of object passed into it, they will both execute the quacking method properly.
Note that they will exhibit DIFFERENT behavior when the quacking method is executed.
When the function do_nonduck_things is executed with either class, they do not both execute properly.
The Not_A_Duck executes just fine, but Ducks do not have the expected behavior, so a runtime exception is raised.
@author: MRHardwick
'''
class Duck(object):
def quacking(self):
print "I'm quacking"
class Not_A_Duck(object):
def quacking(self):
print "I'm busy with other non-duck things"
def doing_other_things_too(self):
print "You've found my real purpose"
def make_it_quack(duck):
duck.quacking()
def do_nonduck_things(not_a_duck):
not_a_duck.doing_other_things_too()
if __name__ == '__main__':
a_duck = Duck()
something_else = Not_A_Duck()
make_it_quack(a_duck)
make_it_quack(something_else)
do_nonduck_things(something_else)
do_nonduck_things(a_duck) |
'''
六:json&pickle模块
#1、什么是序列化
序列化指的是把内存的数据类型转换成一个特定的格式的内容
该格式的内容可用于存储或者传输给其他平台使用
内存中的数据类型 ---->序列化 ---->特定的格式(json格式或者pickle格式)
内存中的数据类型 <----序列化 <----特定的格式(json格式或者pickle格式)
#2、为何要序列化
(1)可用于存储===>可以用于存档(内存中的数据以某种形式存入硬盘)
可以是专用格式:pickle只有python语言可以识别
可以用json,但不推荐
(2)传输给其他平台使用===>跨平台数据交互
通用格式,能够被所有语言识别的格式==json
json只是提取了所有语言共有的特点,但语言独有的特点不行
#3、如何使用序列化与反序列化
(1)
json.dumps()
json.loads()
(2)
json.dump()
json.loads()
(3)补充:
json只是提取了所有语言共有的特点,但语言独有的特点不行,
例如python中的集合,不可以序列化
强调:json格式没有单引号格式
#4、猴子补丁
核心思想:对源码中有些地方不满意,用自己的代码来代替源代码中的某一部分功能
可以在程序的启动文件中修改。不想要便可直接注释。注意:不可以直接修改源代码。
#5、pickcle模块
集合可以识别,但是读写文件应该是b模式
七:shelve模块
八: xml模块
九:configparser模块
(遗留:settings的配置文件???)
添加某种特定格式的配置文件
十 :hashlib模块
1、什么是哈希
hash是一类算法,该算法接受传入的内容,经过运算得到的一串 hash
hash值的特点:
(1) 只要传入的内容一样,得到的hash值必然一样=====>要用明文传输密码文件完整性校验
(2)不能由 hash值返解成内容=======》把密码做成 hash值,不应该在网络传输明文密码
(3)只要使用的 hash算法不变,无论校验的内容有多大,得到的hash值长度是固定的
2、hash用途
(1)密文
(2)完整性校验
3、如何用
(1)撞库
(2)加盐
十一:suprocess模块 : 获取到命令执行结果的返回值
子进程
十二:logging模块
import logging
logging.debug("XXX")
logging.info("XXX")
logging.warning("XXX")
logging.error("XXX")
logging.critical("XXX")
'''
# #3、如何使用序列化与反序列化
# #示范一:
# import json
# #json.dumps 转化为json格式
# json_res=json.dumps(True)
# print(json_res,type(json_res))
#
# json_res2=json.dumps([1,'aaa',True,False])
# print((json_res2,type(json_res2)))
#
# #json.loads 反序列化
# cover_json=json.loads(json_res)
# print(cover_json,type(cover_json))
#
# cover_json2=json.loads(json_res2)
# print(cover_json2,type(cover_json2))
#示范二
import json
#1)已json格式存入文件(json是字符串格式,可以使用t模式写入)
# json_res=json.dumps([1,'aaa',True,False])
# with open('text.json',mode='wt',encoding='utf-8') as f:
# f.write(json_res)
#2)将json格式已Py格式读出
# with open('text.json',mode='rt',encoding='utf-8') as f:
# res=f.read()
# print(json.loads(res))
#将序列化的结果写入文件的简单方法,dump可以一步到位
# with open('text.json',mode='wt',encoding='utf-8') as f:
# json.dump([1,'aaa',True,False],f)
#将json格式已Py格式读出的简单办法
# with open('text.json',mode='rt',encoding='utf-8') as f:
# res=json.load(f)
# print(res)
# #json验证:
#import json
# res=json.dumps({1,2,3})
# print(res) #Object of type set is not JSON serializable
#中文验证
# res=json.dumps({'name':'我'})
# print(res,type(res))
# res=json.loads('{"name": "\u6211"}')
# print(res)
'''
#4)猴子补丁例子
ujson 模块 比json 模块要更快
import json
import ujson
def monkey_patch_json():
json.__name__='ujson'
json.dumps=ujson.dumps
json.loads=ujson.loads
monkey_patch_json() #在文件入口处执行
#以下办法不可以,因为名称空间并没有改变
import ujson as json
'''
# #5)pickle模块:写
# import pickle
# res=pickle.dumps({1,2,3,4,5})
# # print(res,type(res))
# with open('text2.json',mode='wb') as f:
# f.write()
# #5)读
# import pickle
# #res=pickle.dumps({1,2,3,4,5})
# # print(res,type(res))
# with open('text2.json',mode='rb') as f:
# res=f.read()
# print(pickle.loads(res))
# import configparser
# config=configparser.ConfigParser()
# config.read('test.ini')
# #1、获取sections
# print(config.sections())
#
# #2、获取某一section下的所有options
# print(config.options('section1'))
#
# #3、获取items(元组)
# print(config.items('section1'))
#
# #4、
# res=config.get('section1','user')
# print(res,type(res))
#
# #5、getint 将 str转化为int类型
# res1=config.getint('section1','age')
# print(res1,type(res1))
#
# #6、getboolean 将 str转化为bool类型
# res2=config.getboolean('section1','is_admin')
# print(res2,type(res2))
'''
3、如何用哈希
'''
# import hashlib
# #m相当于hash工厂
# m=hashlib.md5()
# #原料 bits类型
# m.update('hello'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# #合成
# res=m.hexdigest() #'helloworld'
# print(res)
#1)验证
# m1=hashlib.md5()
# m1.update('he'.encode('utf-8'))
# m1.update('llo'.encode('utf-8'))
# m1.update('world'.encode('utf-8'))
# res1=m1.hexdigest() #'helloworld'
# print(res1)
#2)校验完整性
'''
在文件校验时,一般若文件很大,则不会全部校验
只会选取一部分来进行校验
因此,可以f.read(2000),根据字节数来读取
但是只固定几个字节,可能不够随机
因此可以 使用f.feek() 移动指针位置随机获取字节
'''
'''
hash撞库,破坏者可能通过大量随机密码来破解
模拟撞库
'''
# import hashlib
# #m相当于hash工厂
# m=hashlib.md5()
# #原料 bits类型
# m.update('wy'.encode('utf-8'))
# m.update('453521'.encode('utf-8'))
# #合成
# res=m.hexdigest() #'helloworld'
# print(res)
# cryptograph='fc5e038d38a57032085441e7fe7010b0'
# passwds=[
# 'wy123..',
# 'wy990619',
# 'wy990731',
# 'woaini...',
# 'wy1234',
# '453421',
# 'wy8888',
# 'helloworld',
# ]
# import hashlib
# dic={}
# for p in passwds:
# res=hashlib.md5(p.encode('utf-8'))
# dic[p]=res.hexdigest()
# # print(dic)
# for k,v in dic.items():
# if v==cryptograph:
# print("明文密码为:%s"%k)
# break
# else:
# print("撞库失败")
#提升撞库成本==>密码加盐"加干扰"
# import hashlib
# m=hashlib.sha3_512()
# m.update('hello'.encode('utf-8'))
# m.update('哈哈'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# res=m.hexdigest()
# print(res)
# import subprocess
# obj=subprocess.Popen('ls/root',shell=True,
# stdout=subprocess.PIPE,#正确结果
# stderr=subprocess.PIPE,#错误解决
# )
# print(obj)
# err_res=obj.stderr.read()
# print(err_res) #读出来的是二进制类型,需要解码
# #解码的编码:编码应该用系统的编码,因为运行的是系统程序
# print(err_res.decode("gbk"))
|
'''
1、什么是迭代器
迭代器指的是迭代取值的工具,迭代是一个重复的过程,
每次重复是基于上一次的结果而继续的,单纯的重复不算迭代
2、为何要有迭代器
迭代器是用来循环取值的工具,而涉及到把多个值循环取出来的 类 有:
列表、字符串、元组、字典、集合、打开文件
但是上述的迭代方式只适用于有索引的数据类型:列表、字符串、元组
为了解决基于索引取值的局限性,python提供了一种不依赖索引的取值方式
3、如何用迭代器
可迭代对象:但凡内置有__iter__方法的都称之为可迭代的对象
将可迭代对象转化为迭代器对象
可迭代对象.__iter__()=迭代器对象
此时,对象为迭代器对象,并且添加了__next__的内置方法
迭代器对象:内置有__next__方法并且内置有__iter__方法的对象
迭代器对象.__next__():可以得到迭代器的下一个值
迭代器对象.__iter__():得到迭代器本身,调与不调没区别
在迭代器对象下加上__iter__()方法:
目的是为了使for循环的工作原理统一
'''
# 验证一下迭代器对象.__iter__():得到迭代器本身,调与不调没区别
# d={'a':1,'b':2,'c':3}
# d_iterator=d.__iter__()
# print(d_iterator.__iter__() is d_iterator) #True
'''
4、可迭代对象与迭代器对象是有区别的:
可迭代对象下没有__next__方法
迭代器对象下有
可迭代对象有:字符串、列表、元组、字典、集合、文件对象
迭代器对象;文件对象
在以上可迭代对象中只有文件对象含有__next__方法
原因:迭代器对象比较省内存,因为调用一次__next__进一次内存,
其他可迭代对象都不会有过多内容,而文件可能在一开始使用时就可能包含很多内容,
为了节约内存,一开始就把文件设置成了迭代器对象
'''
# s1=''
# s1.__iter__()
# l=[]
# l.__iter__()
# d={'a':1}
# d.__iter__()
'''
# 调用可迭代对象下的__iter__方法会将其转换为可迭代器对象
# 调用转化为迭代器对象的__next__就是在取值
'''
# d={'a':1,'b':2,'c':3}
# d_iterator=d.__iter__()
# print(d_iterator.__next__()) #a
# print(d_iterator.__next__()) #b
# print(d_iterator.__next__()) #c
# print(d_iterator.__next__()) #会抛出异常 StopIteration
# 取值
# 第一次迭代器取值
# print("开始第一次迭代:")
# while True:
# try:
# print(d_iterator.__next__())
# except StopIteration: # 捕捉异常
# break
# print("开始第二次迭代:")
# 第二次迭代器取值
# 会发现连续迭代时什么都取不出来,因为第一次已经取完了
# 如果想继续取值,只能在转换成迭代对象
# d_iterator=d.__iter__()
# while True:
# try:
# print(d_iterator.__next__())
# except StopIteration: # 捕捉异常
# break
'''
如果使用while来进行可迭代对象的循环,步骤如下所示:
'''
d={'a':1,'b':2,'c':3}
d_iterator=d.__iter__()
while True:
try:
print(d_iterator.__next__())
except StopIteration: # 捕捉异常
break
'''
5、如果使用for来进行可迭代对象的循环,步骤如下所示:
可知for循环帮我们做了工作:
1、将可迭代对象.__iter__() 得到迭代器对象
2、取迭代器对象的__next__()得到返回值,并且赋值给K
3、循环往复步骤2,直到抛出StopIteration异常for循环便结束循环
在迭代器对象中加__iter__方法的目的是为了统一
for K in XXX
无论XXX是可迭代对象还是迭代器对象都取__iter__()
'''
d={'a':1,'b':2,'c':3}
for k in d:
print(k)
'''
6、迭代器优缺点:
优点:
统一:不依赖索引取值
省内存,在调用__next__时,内存中才有值,内存中只能有一个值
缺点:
不可以跟数组一样,按索引取值,每次都需要遍历
迭代器是一次性的,一次取完值后,不能连续取值,不然什么都没有
'''
'''
7、遗留问题:
类似C++中的如果一开始并不知道要存的内容有多大,或者要存无穷多个,应该怎么存?
可利用迭代器的办法,但是目前学到的都python内置的迭代器,无法改变
因此有了下面要学的自定义迭代器----生成器
''' |
# import numpy as np
'''
np 矩阵
'''
'''
属性
'''
# array=np.array([[1,2,3],
# [2,3,4]])
# #属性
# print(array)
# #维度
# print('number of dim:',array.ndim)
# #形状(行,列)
# print('sharp:',array.shape)
# #size 个数
# print('size',array.size)
'''
创建array
'''
import numpy as np
'''一维'''
# a=np.array([2,3,4],dtype=np.int64)
# print(a)
# print(a.dtype)
'''二维'''
# array=np.array([[1,2,3],
# [2,3,4]])
'''全要0的矩阵(行列'''
a=np.zeros((3,4))
print(a)
'''全要1的矩阵(2* 全是2)'''
a2=2*np.ones((3,4))
print(a2)
'''什么都没有的矩阵//随机'''
a3=np.empty((4,5))
print(a3)
'''有序数列或矩阵(前闭后开)'''
a4=np.arange(12,20,2)
print(a4)
'''有序数列或矩阵(前闭后开) 4*4=12'''
a4=np.arange(16).reshape((4,4))
print(a4)
'''生成线段:(从哪,到哪,步长).resharp(n,m) 要求n*m=步长'''
a5=np.linspace(1,10,6).reshape((2,3))
print(a5)
'''arange减/加/乘法'''
a=np.arange(10,30,5)
b=np.array([1,2,3,4])
print('a-b',a-b)
print(a+b)
print(a**2) #(a的平方)
'''三角函数'''
d=100*np.cos(a) #给a求cos值,并乘10
print(d)
''''''
print(a<20)
'''
矩阵乘法
1、逐个相乘
2、矩阵乘法
注意维度
'''
a=np.arange(4).reshape(2,2)
b=np.array([[2,3],
[4,5]])
print(a)
print(b)
print(a*b)
#c c_2方式一样
c=np.dot(a,b)
c_2=a.dot(b)
print(c)
print(c_2)
print("====>")
'''随机'''
a=np.random.random((2,4))
print(a)
print(np.sum(a))
'''
axis表示维度,
0表示列,每一个列的最小值
1表示行,每一个行的最小值
'''
print(np.min(a,axis=0))
print(np.max(a))
'''
索引最大/小位置、平均值、中位数
'''
A=np.arange(0,20).reshape(4,5)
print(A)
print(np.argmax(A))
print(np.argmin(A))
#平均值的不同表示方式
print(np.mean(A))
print(A.mean())
print(np.average(A))
#中位数
print(np.median(A))
#累加返回列表
print(np.cumsum(A))
#累差还是矩阵(会少一列哦~)
print(np.diff(A))
#循环输出每一行
A=np.arange(3,15).reshape((3,4))
print(A)
#循环输出每一行
for row in A:
print(row)
#循环输出每一列(必须要转置)
for column in A.T:
print(column)
# 将矩阵整成一个列表
print(A.flatten())
#循环输出每一项
for item in A.flat:
print(item)
#合并
A=np.array([1,1,1])[:,np.newaxis]
B=np.array([2,2,2])[:,np.newaxis]
#AB上下合并合并
C=np.vstack((A,B))
print(A.shape,C.shape)
print(C)
#AB上下合并合并
C=np.hstack((A,B))
#将A写成[[1],[1],[1]].T的形式
#print(A[np.newaxis,:].shape)
print("====")
#多个合并,并且可以指定维度的个数
print(np.concatenate((A,B,A,B),axis=1))
#分割
A=np.arange(12).reshape((3,4))
print(A)
#均分
print(np.split(A,2,axis=1))
#不等分军阀
print(np.array_split(A,3))
#
# np.vsplit((A,1))
# np.hsplit((A,1))
#深浅copy(一起变,浅copy)(不关联,deep.copy)
b=np.arange(4)
a=b
print(b)
print(a)
print(a is b)
c=b.copy()
print(c)
print(c is b)
'''
pandas 类似于字典的排序
'''
import pandas as pd
s=pd.Series([1,3,6,np.nan,44,1])
#自动 加字典和dtype
print(s)
dates=pd.date_range('20200601',periods=6)
print(dates)
'''
DataFrame转化为了列表形式,np.XX是数据来源,index=按某种方式索引,列名称
默认索引于行数都是0 1 2 ...
'''
df=pd.DataFrame(np.random.randn(6,4),index=dates,columns=['第一列','第2列','第3列','第4列'])
print(df)
#每一列的类型
print(df.dtypes)
#打印单独DataFrame的行名、列名、值、
print(df.columns)
print(df.index)
print(df.values)
#描述 计数、平均值、标准值、最小值、最大值、会忽略不可计算的数
print(df.describe())
#行列翻转
print(df.T)
#根据行列排序 axis=按行或按列,ascending=正序或倒序
dfA=df.sort_index(axis=0,ascending=False)
##根据行值排序(从小到大排序)
dfB=df.sort_values(by='第2列')
print(dfA)
print(dfB)
print("============")
#选择数据
print(df.第一列)
print("============")
print(df['第一列'])
print(df[0:2])
print(df['20200603':'20200604'])
#高级数据选择,1、根据标签选择(类似)
print("===")
print(df.loc['20200602'])
#打印某行某列
print(df.loc['20200603',["第2列",]])
#2、根据位置选择df.iloc[第几行,第几位]
print("my list")
print(df)
print("iloc=======")
print(df.iloc[3])
print("iloc=======")
print(df.iloc[3,0])
#[第几行:到第几行,第几列:第几列]
print(df.iloc[1:3,2:])
print("iloc=======")
#3、条件选择
print(df[df['第一列']>0])
#设置值,可以选出来后直接赋值
#加一个为NaN的序列np.nan
'''
如何处理消失了的数据
1、丢掉缺失的数据dropna()
axis=选择丢掉的是行还是列,
how=选择丢掉的方式,任何一个是空值,还是所有数据都是空值
2、用0来填充
fillna() 用0来填补空缺值
3、检查是否有丢失的数据
isnull() 返回的是布尔值,没有值返回True
np.any() 有任何缺失便返回True
'''
print(df.dropna(axis=0,how='any')) #{'any','all'}
print(df.fillna(value=0))
print(np.any(df.isnull())==True)
'''
导入文件
read_csv
read_pickle
read_json
...
导出文件
to_csv
to_pickle
to_json
...
pd.read_csv(r"文件名.后缀名")
pd.to_csv(r"新文件名.后缀名")
'''
'''
合并多个DataFrame #concatenating
1、同列合并(列名相同),(注意方向 axis 调方向)
concat([需要合并的表格,注意在列表中],axis=确定合并方向,ignore_index=是否忽略原来的索引)
2、行名,列名不同:join['inner','outer']
join='outer'默认类型,全连接,没有的补NaN
Join='inner'只取相同部分
concat([list],join='XXX',ignore_index='',axis='')
'''
# df_1=pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'])
# df_2=pd.DataFrame(np.ones((3,4))*1,columns=['a','b','c','d'])
# df_3=pd.DataFrame(np.ones((3,4))*3,columns=['a','b','c','d'])
#
# res=pd.concat([df_1,df_2,df_3],axis=0,ignore_index=True)
# print(res)
#join['inner','outer']
df_1=pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'],index=['1','2','3'])
df_2=pd.DataFrame(np.ones((3,4))*1,columns=['e','b','c','d'],index=['2','3','4'])
res=pd.concat([df_1,df_2],join='inner',ignore_index=True,axis=0)
print(res)
print("===="
"====="
"=====")
#横向合并,索引没有时补NaN没有 join_axes=[df_1.index](可能已经被弃用了)
res2=pd.concat([df_1,df_2],axis=1)
print(res2)
#append
df_A=pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'])
df_B=pd.DataFrame(np.ones((3,4))*1,columns=['a','b','c','d'])
df_C=pd.DataFrame(np.ones((3,4))*2,columns=['a','b','c','d'])
#默认纵向添加(填一个不用列表,填多个用列表)
res4=df_A.append([df_B,df_C],ignore_index=True)
print(res4)
# 只需要添加一行/一列 Series
df_A=pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'])
s1=pd.Series([1,2,3,4],index=['a','b','c','d'])
res=df_A.append(s1,ignore_index=True)
print(res)
'''
merge
pd.merge(A,B,on=基于哪一个columns进行合并)
连接,默认连接方式how='inner'
how=['inner','outer','left','right']
indicator=True : 显示数据格式
indicator='XXX': 改名字
suffixes=['XXX','XXX'] #添加后缀名
'''
pd.merge(A,B,on=['C','D'])
#pd.merge(left,right,right_index=,left_index=)
|
"""
1、*args **kwargs
2、名称空间与作用域:名称空间的 “嵌套”关系是在函数定义阶段,检测语法的时候确认的
3、函数对象:
可以把函数当做参数传入
可以把函数当做返回值(不要加括号!!!!)
4、函数的嵌套定义:
函数内写函数
5、闭包函数
函数里面的函数变量,是上一层函数里的
最后再外层函数中返回里面的函数
传参的方式:
一、通过参数传递
二、通过闭包函数传递
什么是装饰器:
工具(函数、类)添加额外的功能
为何要用装饰器:再不改变源代码和调用方式的情况下,增加扩展功能
开放封闭原则
开放:指的是对扩展功能是开放的
封闭:指的是对修改源代码是封闭的
如何
"""
'''
要求:添加一个功能:统计运行时间
'''
# import time
#
# def timmer(func):
# # func=原来wapper的内存地址
# def wapper(*args, **kwargs):
# start = time.time()
# res = func(*args, **kwargs) # 目的:将函数返回值写活
# end = time.time()
# print(end - start)
# return res
#
# return wapper # 返回wapper的原因是让他重新变成全局变量调用
#
#
# @timmer # index=outter(index)
# def index(x, y):
# time.sleep(3)
# print(x, y)
# return 123
'''
将参数写活了之后,wapper是一个封装的功能,但是目前只能给index使用
'''
# def wapper(*args, **kwargs):
# start = time.time()
# index(*args, **kwargs)
# end = time.time()
# print(end-start)
#
#
# wapper(111,222)
# index=outter(index) #原来wapper的内存地址
'''
不方便的地方是你每一次写都需要把被装饰的函数写在outter里面,
有个简单的办法:在被装饰的函数前面写上@装饰器名 即可
'''
# res = index(111, 222) # 相当于在调用wapper
#
# print(res)
'''
思考题:
如果一个函数有多个装饰器怎么运行,运行过程是怎样的?
答案:先运行最下方的装饰器
@deco1 #index=deco1(deco2.wrapper的内存地址)
@deco2 #deco2.wrapper的内存地址=deco2(deco3.wrapper的内存地址)
@deco3 #deco3.wrapper的内存地址=deco3(index)
def index():
pass
'''
'''
装饰器作用:
1、调用原函数
2、补充新功能
'''
# 无参装饰器模板
# def outter(func):
# def wapper(*args,**kwargs):
# res=func(*args,**kwargs)
# return res
# return wapper
'''
@语法的作用:
@outter #相当于index=outter(index)
如果我写成@print("hello")
执行步骤:
1、先执行这个函数
2、将函数的转为@后的东西
3、但不一定可以运行
@None
'''
# @print
# def home(a,b,c):
# pass
#
# print(home) # None 因为home没有返回值
'''
装饰器的补充:
print(index.__name__) #可以查看函数的名字,加装饰器后名字是wapper,不加装饰器名字是index
# print(help(index))
print(index.__doc__) #help()可以查看原函数中的注释,查看的是原函数__doc__属性下的注释
为了使wapper()和index()函数更像,需要将属性也替换掉,但是属性过多,每行都写不现实,
因此python提供了简单的办法,可以导入模块来装饰wapper()的属性
from functools import wraps #导入模块
@wraps(func) #在需要 被装饰的 装饰器函数 正上方写(需要传参,参数为需要改变的函数对象)
'''
# import time
# from functools import wraps
#
# def timmer(func):
# # func=原来wapper的内存地址
# @wraps(func)
# def wapper(*args, **kwargs):
# start = time.time()
# res = func(*args, **kwargs) # 目的:将函数返回值写活
# end = time.time()
# print(end - start)
# return res
#
# return wapper # 返回wapper的原因是让他重新变成全局变量调用
#
#
# @timmer # index=outter(index)
# def index(x, y):
# time.sleep(3)
# print(x, y)
# return 123
'''
补充:
由于语法糖@的限制,outter函数只能有一个参数,就是正下方的函数。不能有多个参数 -----相当于这一行 # index=outter(index)
那么我们现在知道了,wapper()中的参数不能改,outter函数中的参数也不能改,那怎么做需要传参的装饰器呢
解决还需要参数的情况:再套一层
'''
# 例如:写一个认证功能的装饰器,账户密码可来自文件,可来自数据库,可来自其他软件
'''
现在的问题是闭包函数内的db_type也需要一个参数
在补充知识是写到,第一层参数不可修改,外一层参数也不可修改,那么只能再通过一次闭包来进行传递了
'''
def auth(db_type):
# db_type=111
def deco(func):
def wapper(*args, **kwargs):
user = input("输入名字:")
pwd = input("输入密码:")
if db_type == 'file':
print("基于文件的输入")
res = func(*args, **kwargs)
return res
elif db_type == 'mysql':
print("基于mysql的输入")
res = func(*args, **kwargs)
return res
elif db_type == 'other':
print("基于mysql的输入")
res = func(*args, **kwargs)
return res
else:
print("不可认证")
return wapper
return deco
'''
如何使用这层闭包:auth(deco)
# deco = auth(db_type='file')
# @deco
@auth(db_type='file')
上面俩行与下面的一行用法相同,先执行@之后的语句,在使用@
注意:没必要闭包四层,因为第三次已经是可以传各种参数了
'''
# deco = auth(db_type='file')
# @deco
@auth(db_type='file')
def index(x, y):
print(x, y)
deco = auth(db_type='mysql')
@auth(db_type='mysql')
def home(x, y):
print(x, y)
home(1, 2)
|
"""
异常:
我们常见的异常由三部分组成:
追踪信息、具体位置、错误类型
我们进行异常处理:是为了捕捉异常信息并放到出错信息记录的日志内
异常处理的两类:
1、语法错误
2、逻辑错误
1)、可预知的错误
2)、不可预知的错误 (重点)
"""
# 2)、不可预知的错误 (重点)
'''
#完整的异常处理语法:
try:
#有可能会抛出异常的代码
子代码1
子代码2
子代码3
子代码4
except 异常类型1 as e:
pass
except 异常类型2 as e:
pass
...
else:
如果被检测的子代码块没有异常发生,则会执行else的子代码
finally:
无论被检测的子代码块有无异常发生,都会执行finally的子代码
'''
'''
可能出现的问题:
1、抛出异常后,该行代码同级别的后续代码不会运行
2、捕捉异常的类型不对,仍然会报错
3、异常不同,但捕捉后的操作相同时,可以合并错误类型
except (IndexError,NameError) as e:
pass
4、万能异常(Exception):就是所有异常都可以捕捉到
5、try不能单独和else连用
6、try可以单独和finally连用
'''
'''
文件处理:with自带异常处理机制
'''
|
# # 注册
# user_info = {}
# with open('login.txt', mode='r', encoding='utf-8') as f:
# for line in f:
# user, pwd = line.strip().split(" ")
# user_info[user] = pwd
# print("所有用户的数据:", user_info)
#
# while True:
# new_name = input("请输入你的名字:")
# if new_name in user_info:
# print("用户名已存在,请重新输入")
# continue
#
# pwd = input("请输入密码:")
# re_pwd = input("请再次输入密码:")
# if pwd == re_pwd:
# # dict.update("{}:{}".format(new_name, pwd))
# with open('login.txt', mode='a', encoding='utf-8') as f1:
# f1.write('\n{} {}'.format(new_name, pwd))
# print("注册成功")
# break
# else:
# print("请重新输入密码")
|
# -*- coding: utf-8 -*-
"""
Planck Law Plotter
"""
import pylab
import scipy.constants
import numpy as np
global U
U=(scipy.constants.h*scipy.constants.c)/scipy.constants.Boltzmann
def Normalize(b):
Bnorm=[]
Min=min(b)
Max=max(b)
for i in range(0,len(b)):
Bi=(b[i]-Min)/(Max-Min)
Bnorm.append(Bi)
return(Bnorm)
def RadianceArray(xvals, U):
B=(2*scipy.constants.Planck*scipy.constants.c*scipy.constants.c)/(xvals*xvals*xvals*xvals*xvals)*1/(np.exp(U/xvals)-1)
return(B)
T=float(input("Enter the temperature of the first blackbody in Kelvin: "))
T2=float(input("Enter the temperature of the second blackbody in Kelvin: "))
T3=float(input("Enter the temperature of the second blackbody in Kelvin: "))
V1=str(int(T))+' K' #for the plot legend text strings
V2=str(int(T2))+' K'
V3=str(int(T3))+' K'
U2=U*1/T #compute constant part of the radiance equation 1
U3=U*1/T2 #compute constant part of the radiance equation
U4=U*1/T3
n=100000
lmin, lmax = 0.000000001,.00001
t=pylab.linspace(lmin, lmax, n)
B=(2*scipy.constants.Planck*scipy.constants.c*scipy.constants.c)/(t*t*t*t*t)*1/(np.exp(U2/t)-1)
B2=(2*scipy.constants.Planck*scipy.constants.c*scipy.constants.c)/(t*t*t*t*t)*1/(np.exp(U3/t)-1)
B3=(2*scipy.constants.Planck*scipy.constants.c*scipy.constants.c)/(t*t*t*t*t)*1/(np.exp(U4/t)-1)
B=RadianceArray(t,U2)
B2=RadianceArray(t,U3)
B3=RadianceArray(t,U4)
Bnorm=Normalize(B)
B2norm=Normalize(B2)
B3norm=Normalize(B3)
pylab.plot(t,Bnorm, label=V1, color='g', linestyle='--')
pylab.plot(t,B2norm, label=V2, color='r', linestyle='-')
pylab.plot(t,B3norm, label=V3, color='b', linestyle='-.')
pylab.title("Normalized Blackbody radiation curves")
pylab.legend()
pylab.xlabel('Wavelength in M')
pylab.ylabel('Surface Radiance in W/(sr*m^2*Hz)')
pylab.show()
|
import random
randNumber = random.randint(1,100)
userGuess = None
guesses = 0
while(userGuess != randNumber):
userGuess = int(input("Enter the number/guess: "))
guesses += 1
if(userGuess == randNumber):
print("You guessed it right!")
elif(userGuess > randNumber):
print("You guessed it wrong, guess smaller number")
else:
print("You guessed it wrong, guess greater number")
print(f"You guessed the number in {guesses} guesses")
with open("hiscore.txt", "r") as f:
highscore = int(f.read())
if(guesses<highscore):
print("You have just broken the high score!")
with open("hiscore.txt", "w") as f:
f.write(str(guesses))
|
import calculations
# Фронтенд программы
def is_number(str):
try:
float(str)
return True
except ValueError:
return False
def convStN(str_data):
str_num = ""
arr_num = []
i = 0
length = len(str_data)
for elem in str_data:
if elem.isdigit() or elem == "." or elem == ",":
if elem == ",":
elem = "."
str_num += elem
elif is_number(str_num):
arr_num.append(float(str_num))
str_num = ""
elif len(arr_num) < 1 and i >= length - 1:
return True
i += 1
if len(arr_num) > 0 and is_number(str_num):
arr_num.append(float(str_num))
if len(arr_num) <= 1:
return False
return arr_num
def clickCalc():
str_data = str_nums.get() # Получаю строку с массивом чисел
arr_data = []
if (str_data != ""):
arr_data = convStN(str_data) # Получаю массив с числами
if arr_data != False and arr_data != True:
data2 = arr_data.copy()
count_dat = len(arr_data)
aver_str.delete(0, END)
aver_str.insert(0, str(calculations.average(arr_data, count_dat)))
disp_str.delete(0, END)
disp_str.insert(0, str(calculations.dispersion(arr_data, count_dat)))
median_str.delete(0, END)
median_str.insert(0, str(calculations.median(arr_data, count_dat)))
mode_str.delete(0, END)
mode_str.insert(0, str(calculations.mode(arr_data)))
global _number
global _len
_number = 0
_len = 0
asym_str.delete(0, END)
asym_str.insert(0, str(calculations.asymmetry(data2, count_dat)))
excess_str.delete(0, END)
excess_str.insert(0, str(calculations.excess(data2, count_dat)))
notif_str.delete(0, END)
notif_str.insert(0, "Готово.")
notif_str.configure({"background": "White"})
elif arr_data == True:
notif_str.delete(0, END)
notif_str.insert(0, "Введены не числа.")
notif_str.configure({"background": "Red"})
return
else:
notif_str.delete(0, END)
notif_str.insert(0, "Нужно ввести не менее 2 чисел.")
notif_str.configure({"background": "Red"})
return
else:
notif_str.delete(0, END)
notif_str.insert(0, "Числа не введены.")
notif_str.configure({"background": "Red"})
from tkinter import *
window = Tk()
window.title("Статистический анализ одномерной случайной величины")
window.iconbitmap('terminator.ico') # иконка на окне
# строка с вводом строки с массивом чисел
lbl = Label(window, text="Введите числа через пробел и нажмите кнопку \"Рассчитать\"", font=("Arial Bold", 14))
lbl.grid(column = 0, row = 0, pady="10", padx="10")
lbl_nums = Label(window, text="Введите массив чисел: ", font=("Arial", 12))
lbl_nums.grid(column = 0, row = 1, pady="10", padx="10")
str_nums = Entry(window, width=100)
str_nums.grid(column = 1, row = 1, pady="10", padx="10")
str_nums.focus()
# строка с выводом оповещений (в том числе об ошибках ввода)
notif = Label(window, text="Оповещение: ", font=("Arial", 12))
notif.grid(column = 0, row = 2, pady="10", padx="10")
notif = Entry(window, width=20)
notif_str = Entry(window, width=100)
notif_str.grid(column = 1, row = 2, pady="10", padx="10")
# строка с выводом среднего арифметического
aver = Label(window, text="Среднее арифметическое: ", font=("Arial", 12))
aver.grid(column = 0, row = 3, pady="10", padx="10")
aver = Entry(window, width=100)
aver_str = Entry(window, width=30)
aver_str.grid(column = 1, row = 3, pady="10", padx="10")
# строка с выводом дисперсии
disp = Label(window, text="Дисперсия: ", font=("Arial", 12))
disp.grid(column = 0, row = 4, pady="10", padx="10")
disp = Entry(window, width=100)
disp_str = Entry(window, width=30)
disp_str.grid(column = 1, row = 4, pady="10", padx="10")
# строка с выводом медианы
medi = Label(window, text="Медиана: ", font=("Arial", 12))
medi.grid(column = 0, row = 5, pady="10", padx="10")
medi = Entry(window, width=100)
median_str = Entry(window, width=30)
median_str.grid(column = 1, row = 5, pady="10", padx="10")
# строка с выводом моды
mod = Label(window, text="Мода: ", font=("Arial", 12))
mod.grid(column = 0, row = 6, pady="10", padx="10")
mod = Entry(window, width=100)
mode_str = Entry(window, width=30)
mode_str.grid(column = 1, row = 6, pady="10", padx="10")
# строка с выводом асимметрии
asym = Label(window, text="Асимметрия: ", font=("Arial", 12))
asym.grid(column = 0, row = 7, pady="10", padx="10")
asym = Entry(window, width=100)
asym_str = Entry(window, width=30)
asym_str.grid(column = 1, row = 7, pady="10", padx="10")
# строка с выводом эксцесса
exc = Label(window, text="Эксцесс: ", font=("Arial", 12))
exc.grid(column = 0, row = 8, pady="10", padx="10")
exc = Entry(window, width=100)
excess_str = Entry(window, width=30)
excess_str.grid(column = 1, row = 8, pady="10", padx="10")
# кнопка для старта расчетов
btn = Button(window, text="Рассчитать", command=clickCalc, font=("Arial", 12), cursor="hand2") # Клик на кнопку и запуск функции
btn.grid(column = 1, row = 9, pady="10")
# запуск программы
window.mainloop()
#str_data = "16.06 15.92 16.01 16.05 15.80 15.97 16.18 16.26 16.22 16.20 16.03 16.31 15.92 16.17 16.07 15.99 16.06 16.07 15.98 16.08 16.09 16.21 16.05 15.87 16.03 16.21 16.23 16.04 15.94 16.03 15.96 16.09 16.24 16.10 15.97 16.16 16.11 16.12 16.14 16.11 16.03 16.03 16.05 16.22 15.97 16.27 16.16 16.32 16.21 16.14 16.23 16.17 16.00 16.13 16.10 15.98 16.12 16.07 16.06 16.11 16.02 15.89 16.29 16.14 15.93 16.17 16.16 15.99 16.15 16.13 16.14 16.05 16.34 16.13 16.13 15.91 16.18 16.06 16.18 16.07 16.09 16.15 16.02 16.08 16.40 16.03 16.16 15.89 16.04 16.15 16.22 16.08 16.09 16.17 16.10 16.11 16.12 16.08 16.13 16.10"
#str_data = "1 1,1 2 3.5 4 5 100" |
import time
timeis = time.localtime()
a = time.strftime('%H''%M', timeis)
#import เวลา
Y = input("do you want parking Y or N")
# ต้องการที่จอดรถไหม
if Y <= Y:
print("start",a)
else :
print("ok")
c2 = input("do you want out parking :")
#ออกและระบุเวลา
total = (int(c2) - int(a))
costPerHour = 20
if total:
hours = round(int(total/ 60))
total2 = round(hours * costPerHour, 2)
print('Your parking for ' + str(hours) + ' hours or ' + str(total) + ' minutes')
print('Total cost is ' + str(total2) + ' baht')
else:
print('Error')
|
def happyBirthdayEmily():
""":arg
When writing a python function we use def- define
"""
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday to you dear Emily!")
print("Happy Birthday to you.")
happyBirthdayEmily()
happyBirthdayEmily()
happyBirthdayEmily()
#Multiple Function defination
def happyBirthdayJane():
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday to you dear Jane!")
print("Happy Birthday to you.")
def happyBirthdayJohn():
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday to you dear John!")
print("Happy Birthday to you.")
happyBirthdayJane()
happyBirthdayJohn()
#Trial
def myFunc1():
print("My name is day Qinyanjui")
def myFunc2():
myFunc1()
print("I love coding")
myFunc2()
#Functs can also call other functions
def happyBirthdayEmily():
print("Happy Birthday Emily.")
def happyBirthdayAndrea():
print("Happy Birthday Andrea")
def Main():
happyBirthdayAndrea()
happyBirthdayEmily()
Main()
def f():
print("In function f")
print("When does this print.")
f()
print("+++"*30)
def f():
print("In function f.")
print("When does this print?")
f()
print("It has already been printed.",end="\n\n")
#TestyourMind
def mySong():
print("Twinkle twinkle little stars")
print("How i wonder how you are!")
print("You fly in the sky....")
mySong()
mySong()
mySong()
print("==="*30)
#Function Parameters
def happyBirthday(person):
""":arg Func- with arguments/parameters"""
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday dear {}".format(person),end=".\n")
print("Happy Birthday to you.")
happyBirthday("Jane")
happyBirthday("John")
#In function parameters you can call the func in another function
def newHappyBirthday(person):
""":arg Func- with arguments/parameters"""
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday dear {}".format(person), end=".\n")
print("Happy Birthday to you.")
def Main():
pass
# while True:
# name=input("Enter the name:")
# newHappyBirthday("Carl")
Main()
def anotherHappyBirthday(person):
""":arg Func- with arguments/parameters"""
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday dear {}".format(person), end=".\n")
print("Happy Birthday to you.")
def Main():
# username=input("Enter the name of the persons birthday:")
anotherHappyBirthday("Jane")
Main()
#Multiple Function Parameters
def sumProblem(x,y):
sum=x+y
sen="The sum of {0} and {1} is {2}".format(x,y,sum)
print(sen)
def Main():
sumProblem(2,3)
sumProblem(1234,5678)
# a=eval(input("Enter an integer:"))
# b=eval(input("Enter another integer:"))
sumProblem(7,6)
Main()
#Returned Function Values
def f(x):
return x*x
print(f(3))
print(f(4))
print(f(4)+f(3))
def sumProblem(x,y):
sum=x+y
return sum
print(sumProblem(5,10))
print(sumProblem(11,12))
def myFunc(name,age,school):
sen="My name is {}, i am {} years old. I school in {} university".format(name,age,school)
return sen
# name=input("Enter your name:")
# age=input("Enter your age:")
# school=input("Enter your school:")
name="John"
age="19"
school="MIT"
print(myFunc(name,age,school))
def lastFirst(firstName,lastName):
separator=" , "
result=lastName+separator+firstName
return result
print(lastFirst("John","Doe"))
print(lastFirst("Jane","Doe"))
def sumProblemString(x,y):
sum=x+y
return 'The sum of {} and {} is {}'.format(x,y,sum)
def main():
print(sumProblemString(2,3))
print(sumProblemString(56,75))
# x=eval(input("Enter the first integer:"))
# y=int(input("Enter the second integer:"))
x=23
y=59
print(sumProblemString(x,y))
main()
def newFunc(interviewer,applicant,time):
return '{} will be interviewed by {} at {}'.format(applicant,interviewer,time)
def Main():
# interviewer=input("Enter the name of the interviewer:")
# applicant=input("Enter the name of the applicant:")
# time=input("Enter the appointment time:")
interviewer="John"
applicant="Day"
time="2.30"
print(newFunc(interviewer,applicant,time))
Main()
#Reminder
def TestYourMight(width,height):
area=width*height
return "The area of a rectangle whose width is {} and height {} is {}".format(width,height,area)
def Main():
print(TestYourMight(20,23))
print(TestYourMight(5,7))
Main()
#Local Variablea
def Main():
x=3
f(x)
def f(x):
print(x)
Main()
#global variables
pi=3.14
def circleArea(radius):
return pi*radius*radius
def circlecumference(radius):
return pi*radius*2
def Main():
print("The area of the circle with radius 5 is",circleArea(5))
print("The circumference with radius 5 is:",circlecumference(5))
Main()
|
import random
print(2<5)
print(3>7)
x=11
print(x>10)
print(2*x<x)
print(type(True))
print(bool(0))
y=bool(0)
print(type(y),y,sep="|")
#Simple if statements
# weight=float(input("How many pounds does your suitcase weight?"))
weight=56
if weight>50:
print("There is a 25$ for luggades that heavy:")
print("Thank you for your business.")
#If-else Statements
# temp=float(input("What is the temperature?"))
temp=25
if temp>70:
print("I think your should wear shorts.")
else:
print('I think you should wear long pants.')
print("Get some exercise outside")
# #More Conditional Expressions
# def CalcWeeklyWages(totalHours,hourlyWage):
# """Return the total weekly wages for a worker working totalHours with a given regular hourlywage, include overtime for hours over 40"""
# if totalHours<=40:
# totalwages=hourlyWage*totalHours
# else:
# overtime=totalHours-40
# totalWages=hourlyWage*40+(1.5*hourlyWage)*overtime
# return totalwages
# def Main():
# # hours=float(input("Enter hours worked"))
# # wage=float(input("Enter dollars paid per hour:"))
# hours=40.0
# wage=2.0
# total=CalcWeeklyWages(hours,wage)
# print(f"Wages for {hours} hours at ${round(wage,2)} per hour are ${round(total,2)}")
# # Main()
# from random import randint
# class headsTail:
# def __init__(self):
# """:arg"""
# def flip(self):
# guess = input("1 or 0:")
# comp=randint(guess)
# guess.capitalize()
# if guess==comp:
# print("Congrats!, You won....")
# else:
# print(f"Ooopps!, You failed... The outcome is {comp}")
# day=headsTail()
# day.flip()
def StudentsGrade():
# marks=eval(input("Enter the students marks:"))
marks=86
if marks>=80 and marks<=100:
print("The student scored an A.")
elif marks>=75:
print("The student scored an A-")
elif marks>=70:
print("The student scored a B+.")
elif marks>=65:
print("The student scored a B.")
elif marks>=54:
print("The student scored a B-.")
elif marks>=49:
print("The student scored a C+.")
elif marks>=44:
print("The student scored a C.")
elif marks>=39:
print("The student scored a D+.")
elif marks>=34:
print("The student scored a D.")
elif marks>=24:
print('The student scored a D-.')
elif marks<=23 and marks>=0:
print("The student failed.")
else:
print("Please check the students score and enter again!!!")
StudentsGrade()
# Nested loops
def PrintAllPositive(numberList):
""":arg """
for num in numberList:
if num>0:
print("Positive numbers",num)
PrintAllPositive([3,-6,8,92,56,12,])
def PrintEvenNumbers(nums):
""":arg"""
for num in nums:
if num%2==0:
print(num)
PrintEvenNumbers([3,5,6,9,8,5,1,7,10,18])
def ChooseEven():
"""
:param num:
:return:
"""
myList=[]
for i in range(3):
num=eval(input("Enter the the numbers:"))
myList.append(num)
newList=[]
for num in myList:
if num%2==0:
newList.append(num)
print(newList)
ChooseEven()
|
import random
from HangmanParts import parts # We need to import HangmanParts.py to be able to print the parts of the body every time we miss a letter
words_spanish = ["lampara", "pantalla", "escritorio"]
words_english = ["picnic", "table", "garden"]
language = input("Which language do you prefer: spanish/english? ")
if language.lower() == "spanish":
picked = random.choice(words_spanish)
else:
picked = random.choice(words_english)
print('The word has', len(picked), 'letters')
correct = ['_'] * len(picked)
incorrect = []
def update():
for i in correct:
print(i, end = ' ') # end = make that the letters will be printed next to each other
print()
update()
parts(len(incorrect))
while True:
print('================')
guess = input("Guess a letter: ")
# Way 1: Here we find out if the chosen letter is correct and in what index
# if guess in picked:
# index = 0
# for i in picked:
# if i == guess:
# correct[index] = guess
# index += 1
# # correct.append(guess)
# # print('Correct letters: ', correct)
# update()
# Way 2: To know if the chosen letter is correct and in what index.
if guess in picked:
for i in range(len(picked)):
index = picked[i]
# print(picked[i])
if index == guess:
correct[i] = picked[i]
# correct.append(guess)
# print('Correct words: ', correct)
update()
else:
if guess not in incorrect:
incorrect.append(guess)
parts(len(incorrect)) # this is to call the fuction
else:
print('You already guess that letter')
print('Incorrect words: ', incorrect)
if len(incorrect) == 4:
print('You lose')
print('I picked', picked)
break
if '_' not in correct:
print('You win')
break
|
from cryptography.fernet import Fernet
def writeKey(keyFilePath : str):
"""
Generates an AES farnet key and save it into a file
Parameters:
keyFilePath: path to key file to write to
Returns:
None
"""
key = Fernet.generate_key()
with open(keyFilePath, "w") as key_file:
key_file.write(key.decode())
def loadKey(keyFilePath : str) -> bytes:
"""
loads an AES farnet key and from a file
Parameters:
keyFilePath: path to key file to write to
Returns:
Key from file as bytes
"""
return open(keyFilePath, "rb").read()
def encrypt(message : bytes, key : bytes):
"""
Encrypts a message
Parameters:
message: the message to encrypt in bytes
key: key to use
"""
fernetKey = Fernet(key)
return fernetKey.encrypt(message)
def decrypt(encryptedMessage : bytes, key : bytes):
"""
Encrypts a message
Parameters:
message: the message to encrypt in bytes
key: key to use
"""
fernetKey = Fernet(key)
return fernetKey.decrypt(encryptedMessage) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.