text
stringlengths 37
1.41M
|
---|
# Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
# В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия.
# Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
from sys import argv
x = argv[1]
y = argv[2]
c = argv[3]
x = int(x)
y = int(y)
c = int(c)
print(f'Размер заработной платы составил: {x * y + c }')
|
from PIL import Image, ImageDraw, ImageFont
import string
import random
def random_letters(cnt):
return ' '.join(random.choice(string.ascii_letters) for x in range(cnt))
def draw(letters):
# Set the size of the image
width = 100
height = 40
# Generate an image
im = Image.new("RGB", (width, height), (255, 255, 255))
dr = ImageDraw.Draw(im)
for i in range(len(letters)):
font = ImageFont.truetype("Futura.ttf", 30)
dr.text((5 + i * 10, 5), letters[i], (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
font)
del dr
# Change the background color
for x in range(width):
for y in range(height):
if im.getpixel((x, y)) == (255, 255, 255):
im.putpixel((x, y), (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# Save the image
im.save('t1.png')
if __name__ == '__main__':
# print(string.ascii_letters)
# print(random.choice(string.ascii_letters))
letters = random_letters(4)
# letters.upper()
print(letters)
draw(letters)
|
"""
第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
北京
程序员
公务员
领导
牛比
牛逼
你娘
你妈
love
sex
jiangge
"""
import os
path = os.listdir(".")
def load_filter_words(path):
words=[]
with open(path, 'r', encoding='utf-8') as content:
words = content.read()
return words
if __name__ == '__main__':
words = load_filter_words('filtered_words.txt')
# print(words)
s = input("输入:")
if s in words:
print("Freedom")
else:
print("Human Rights")
|
def ip_divider():
"""
Divides IP number segments and return separate segments with its lengths.
"""
ip_address = input("Please enter the IP address: ")
ip_address_dot = ip_address + "."
segment = ""
ip_segments = []
print("")
for char in ip_address_dot:
if char != ".":
segment += char
elif char == "." and segment != "":
ip_segments.append(segment)
ip_segments.append(len(segment))
print(f"Segment {segment:3} contains {len(segment)} characters.")
segment = ""
print("")
return ip_segments
ip_divider()
|
list1 = [10, 21, 4, 45, 66, 93]
for number in list1:
if number % 2 == 0:
print(number, end = " ")
|
def insertionSort(lst):
for i in range(1, len(lst)):
curr = lst[i]
j = i - 1
while j >= 0 and curr < lst[j]:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = curr
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print ("% d" % arr[i]) |
class Square():
def __init__(self, s):
self.s1 = s
square_one = Square(5)
square_one_sm = square_one
def object_is(obj1, obj2):
if obj1 is obj2:
return True
else:
return False
print(object_is(square_one, square_one_sm)) |
#!/usr/bin/env python3
from VectorOperations import ScalarMultiplication as scalar
# Suppose A and B are matrices of the n x n, A + B = C is the C[i][j] = A[i][j] + B[i][j]
def Addition(A, B):
row = len(A)
col = row
C = [[0]* row for _ in range(row)]
for i in range(row):
for j in range(col):
C[i][j] = A[i][j] + B[i][j]
return C
# Suppose A and B are matrices of the n x n, A - B = C is the C[i][j] = A[i][j] - B[i][j] s
def Subtraction(A, B):
row = len(A)
col = row
C = [[0]* row for _ in range(row)]
for i in range(row):
for j in range(col):
C[i][j] = A[i][j] - B[i][j]
return C
# T(A) is a new matrix where the columns and rows are swapped
def Transpose(A):
row = len(A)
col = len(A[0])
#creating an empty list
transpose = []
for j in range (col):
rows = []
for i in range (row):
element = A[i][j]
rows.append(element)
transpose.append(rows)
return transpose
#Trace(A) is the sum of the main diagonal of an nxn matrix
def Trace(A):
row = len(A[0])
trace = 0.0
for i in range(row):
trace += A[i][i]
return trace
def Scalar(A, alpha):
row = len(A)
col = len(A[0])
for i in range(row):
for j in range(col):
A[i][j] *= alpha
# A is the matrix, and x is the vector. given n x m matrix, n X 1 vector, find the product
def VectorMatrixMultiplication(A, x):
row = len(A)
col = len(A[0])
product = [0]*row
for j in range(col):
rows = []
for i in range(row):
rows.append(A[i][j])
scalar(rows, x[j])
for i in range(row):
product[i] += rows[i]
return product
# A = m x n, B = n x p, c = m x p
def MatrixMultiplication(A,B):
row = len(A)
col = len(B[0])
m = len(A[0])
C = [[0] * row for i in range(col)]
for i in range(row):
for j in range(col):
for k in range(m):
C[i][j] += A[i][k] * B[k][j]
return C
#given a matrix, reduce the rows
A = [[1,2,3],[5,7,11],[13,17,19]]
B = [[1,2,3],[4,5,6],[7,8,9]]
C = MatrixMultiplication(A,B)
|
#!/usr/bin/env python3
import cmath
# find the roots of a function in the form of aX^2 + bX + c = 0
# findRoots takes three parametes.
def findRoots(a,b,c):
sqrt1 = (b**2) - (4*a*c)
denom = 2*a
negB = -b
solutionList = []
sol1 = (negB - cmath.sqrt(sqrt1))/denom
sol2 = (negB + cmath.sqrt(sqrt1))/denom
#solutionList[0] contains the negative value, and solutionList[1] contains the pos
#value
solutionList.append(sol1)
solutionList.append(sol2)
print(solutionList)
return solutionList
findRoots(1,5,6) |
from collections import namedtuple,OrderedDict
Person = namedtuple('Person','id Name LastName age')
a_person = Person(id=14253083,Name='Edgar',LastName='Ocampo',age=32)
print(a_person) # I can acces them by index []
# Next example with OrderedDict :: Order the dict in falling way
d = {'banana' : 3, 'apple' : 4, 'pear' : 1, 'orange' : 2}
new_d = OrderedDict(sorted(d.items()))
print(new_d)
for key in new_d:
print(key,new_d[key])
# If I Wanna iter in reverse in upward way i have to do this.
for key in reversed(new_d):
print(key,new_d[key]) |
def find_location(board):
x = 0
y = 0
for i in range(len(board)):
for ii in range(len(board)):
if board[i][ii] == 1:
x = ii
y = i
return x, y
def posible_moves(x, y, board_size):
posible_moves_array = []
if y > 0:
posible_moves_array.append("(N)orth")
if x < (board_size-1):
posible_moves_array.append("(E)ast")
if y < (board_size-1):
posible_moves_array.append("(S)outh")
if x > 0:
posible_moves_array.append("(W)est")
#removing where there are walls
if x == 1 and y == 0:
posible_moves_array.remove("(S)outh")
if x == 2 and y == 1:
posible_moves_array.remove("(W)est")
if x == 1 and y == 1:
posible_moves_array.remove("(N)orth")
posible_moves_array.remove("(E)ast")
if x == 0 and y == 2:
posible_moves_array.remove("(E)ast")
if x == 1 and y == 2:
posible_moves_array.remove("(W)est")
posible_moves_array.remove("(E)ast")
if x == 2 and y == 2:
posible_moves_array.remove("(W)est")
return posible_moves_array
def move_player(posible_moves_arry, x, y, board):
choose_move = ""
keepgoing = True
while keepgoing:
print("You can travel:", end = " ")
for i in range(len(posible_moves_arry)):
if (i + 1) == len(posible_moves_array):
print(posible_moves_arry[i], end=".")
else:
print(posible_moves_arry[i], end=" or ")
print("")
choose_move = str(input("Direction: "))
for i in range(len(posible_moves_arry)):
if choose_move == "n" or choose_move == "N":
if posible_moves_arry[i] == "(N)orth":
keepgoing = False
break
if choose_move == "s" or choose_move == "S":
if posible_moves_arry[i] == "(S)outh":
keepgoing = False
break
if choose_move == "e" or choose_move == "E":
if posible_moves_arry[i] == "(E)ast":
keepgoing = False
break
if choose_move == "w" or choose_move == "W":
if posible_moves_arry[i] == "(W)est":
keepgoing = False
break
if keepgoing:
print("Not a valid direction!")
change_y = 0
change_x = 0
if choose_move == "n" or choose_move == "N":
change_y = -1
if choose_move == "s" or choose_move == "S":
change_y = 1
if choose_move == "e" or choose_move == "E":
change_x = 1
if choose_move == "w" or choose_move == "W":
change_x = -1
board[y][x] = 0
board[(y + change_y)][(x + change_x)] = 1
return board
board_size = 3
board = [[0 for x in range(board_size)] for y in range(board_size)]
board[2][0] = 1
not_winner = True
while not_winner:
x_loc, y_loc = find_location(board)
posible_moves_array = posible_moves(x_loc, y_loc, board_size)
board = move_player(posible_moves_array, x_loc, y_loc, board)
x_loc, y_loc = find_location(board)
if x_loc == 2 and y_loc == 2:
print("Victory!")
not_winner = False
|
# Print out a string depending on if food is a value in bakery_stock print out a string that states how many items are left.
# This code picks a random food item:
from random import choice
food = choice(["cheese pizza", "quiche","morning bun","gummy bear","tea cake"])
bakery_stock = {
"almond croissant" : 12,
"toffee cookie": 3,
"morning bun": 1,
"chocolate chunk cookie": 9,
"tea cake": 25
}
if food in bakery_stock:
print(f"There is {bakery_stock[food]} of {food} left")
else:
print(f"{food}? We don't make that") |
import random
random_number = random.randint(1,10) # numbers 1 - 10
# handle user guesses
# if they guess correct, tell them they won
# otherwise tell them if they are too high or too low
# Let player play again if they want!
while True:
player = int(input("Guess a number between 1 and 10: "))
if player > 10 or player < 1:
print("Ugh... That's out of range, read instructions please...")
elif player > random_number:
print("Too high, try again :)")
elif player < random_number:
print("Too low, try again :)")
else:
print("Alright, you guesssed it! You won!")
play_again = input("Do you want to play again? (y/n) ")
if play_again == "y":
random_number = random.randint(1,10)
else:
print("It was fun, thanks!")
break
|
from cs50 import get_string, get_int
import re
options = [1, 2, 3, 4, 5, 6, 7, 8]
i = None
while i not in options:
i = get_int("Height: ")
spaces = i - 1
for a in range(i):
hashes = a + 1
for b in range(spaces):
print(" ", end="")
for c in range(hashes):
print("#", end="")
print(" ", end="")
for c in range(hashes):
print("#", end="")
print()
spaces -= 1
|
#!/bin/python
import math
DIGITS=int(input("How many digitsyou want :"))
print "%.*f" %(DIGITS,math.pi)
|
'''
Calcule a potência de x elevado a n pot(x, n). Ex.: pot(2, 3) = 8.
'''
def pot(a, b):
if b == 1:
return a
if b > 1:
return a * pot(a, b - 1)
print(pot(2,3))
|
import sys
# =============================== Task 1 ===============================
print('=' * 30, ' Task 1 ', '=' * 30)
# Run-app from terminal: python Homework_4.py 8 12.50 100
def validate_args(arguments):
if len(arguments) != 4:
print('Error, expecting 3 parameters:\n'
'Hours, Hourly rate, Bonus')
sys.exit()
def calc_wage(work_hours=int, per_hour=float, extra_bonus=float) -> float:
wage = (int(work_hours) * float(per_hour)) + float(extra_bonus)
print(f'Your wage is: {wage}')
if __name__ == '__main__':
validate_args(sys.argv)
try:
hours = sys.argv[1]
hourly_pay = sys.argv[2]
bonus = sys.argv[3]
calc_wage(hours, hourly_pay, bonus)
except (IndexError, ValueError):
print('Invalid input, please try again')
# =============================== Task 2 ===============================
print('=' * 30, ' Task 2 ', '=' * 30)
result = []
rand_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
for i in range(1, len(rand_list)):
if rand_list[i] > rand_list[i - 1]:
result.append(rand_list[i])
print(result)
# OR Lambda exp. [_ - means no matter what var name]🤓
print([rand_list[_] for _ in range(1, len(rand_list)) if rand_list[_] > rand_list[_ - 1]])
# =============================== Task 3 ===============================
print('=' * 30, ' Task 3 ', '=' * 30)
print([el for el in range(20, 240) if el % 20 == 0 or el % 21 == 0])
# =============================== Task 4 ===============================
print('=' * 30, ' Task 4 ', '=' * 30)
# rand_gen_list = [random.randint(1, 100) for el in range(1, 11)]
rand_gen_list = [2, 2, 2, 7, 23, 1, 44, 3, 2, 10, 7, 4, 11]
# Remove all duplicates
print([val for val in rand_gen_list if rand_gen_list.count(val)])
# Remove all appears at least once
print([element for element in rand_gen_list if rand_gen_list.count(element) == 1])
print(list(dict.fromkeys(rand_gen_list)))
# =============================== Task 5 ===============================
from functools import reduce
print('=' * 30, ' Task 5 ', '=' * 30)
def add_two_num(a, b):
return a * b
my_list = ([el for el in range(100, 1001) if el % 2 == 0])
print(reduce(add_two_num, my_list))
# =============================== Task 6 ===============================
import sys
# To run this file run in terminal: python Homework_4.py <any number>
print('=' * 30, ' Task 6 ', '=' * 30)
from itertools import cycle, count
def count_my_list_el(a):
for el in count(a):
if el >= a + limit:
print('\n')
break
else:
print(el, ', ', end='')
def circle_my_list(a):
counter = 0
for el in cycle(a):
counter += 1
print(el, ', ', end='')
if count == limit:
print(f' printed {counter} times')
break
if __name__ == '__main__':
limit = 10
starting_no = int(sys.argv[1])
my_list = [el for el in range(starting_no, starting_no + 6)]
circle_my_list(my_list)
count_my_list_el(starting_no)
# =============================== Task 7 ===============================
print('=' * 30, ' Task 7 ', '=' * 30)
factorial_list = []
number = 4
def print_factorial(num):
result = 0
if num == 1:
result = 1
else:
temp_val = yield from print_factorial(num - 1)
result = num * temp_val
yield result
return result
for i in print_factorial(number):
factorial_list.append(i)
print(f'Factorial of {number}! is: ', end='')
print(*factorial_list[:-1], sep=' * ', end='')
print(f' = {factorial_list[-1]}')
|
import sqlite3
from db import db
# ovaj UserModel je API! (nije rest)
# sastoji se od 2 API endpoint methods find_by_username i by_id
class UserModel(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50))
password = db.Column(db.String(50))
TABLE_NAME = 'users'
def __init__(self, username, password):
self.username = username
self.password = password
# ovaj "something" ce biti stvoren i moze se koristiti
# u modelu ali nema nikakvu poveznicu sa bazom podataka
# jer nije definiran iznad kao db column - sqlalchemy
# stvara konekciju izmedu pythona i baze podataka
self.something = "hi"
def save_to_db(self):
db.session.add(self)
db.session.commit()
@classmethod
def find_by_username(cls, username):
# connection = sqlite3.connect('data.db')
# cursor = connection.cursor()
#
# query = "SELECT * FROM {table} WHERE username=?".format(table=cls.TABLE_NAME)
# result = cursor.execute(query, (username,))
# row = result.fetchone()
# if row:
# user = cls(*row)
# else:
# user = None
#
# connection.close()
# return user
return cls.query.filter_by(username=username).first()
@classmethod
def find_by_id(cls, _id):
# connection = sqlite3.connect('data.db')
# cursor = connection.cursor()
#
# query = "SELECT * FROM {table} WHERE id=?".format(table=cls.TABLE_NAME)
# result = cursor.execute(query, (_id,))
# row = result.fetchone()
# if row:
# user = cls(*row)
# else:
# user = None
#
# connection.close()
# return user
return cls.query.filter_by(id=_id).first()
|
import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
create_table = "CREATE TABLE IF NOT EXISTS users" \
"(id INTEGER PRIMARY KEY, username text, password text, email text)"
# for auto increment use INTEGER, otherwise int is enough
cursor.execute(create_table)
create_table = "CREATE TABLE IF NOT EXISTS meals" \
"(name text, price text)"
# for auto increment use INTEGER, otherwise int is enough
cursor.execute(create_table)
connection.commit()
connection.close()
|
class Node:
def __init__(self, v):
self.value = v
self.prev = None
self.next = None
class OrderedList:
def __init__(self, asc):
self.head = None
self.tail = None
self.__ascending = asc
def compare(self, v1, v2):
if v1 < v2:
return -1
elif v1 == v2:
return 0
else:
return +1
def add(self, value):
if self.head is None:
self.head = Node(value)
self.tail = self.head
else:
if self.__ascending == True:
currNode = self.head
prevNode = None
cont = True
while cont == True and currNode is not None:
x = self.compare(value, currNode.value)
if x == 1:
currNode, prevNode = currNode.next, currNode
else:
cont = False
if currNode is None:
self.tail = Node(value)
self.tail.prev, prevNode.next = prevNode, self.tail
else:
if currNode is self.head:
currNode.prev = Node(value)
currNode.prev.next, self.head = self.head, currNode.prev
else:
currNode.prev = Node(value)
prevNode.next = currNode.prev
currNode.prev.prev, currNode.prev.next = prevNode, currNode
else:
currNode = self.tail
prevNode = None
cont = True
while cont == True and currNode is not None:
x = self.compare(value, currNode.value)
if x != -1:
currNode, prevNode = currNode.prev, currNode
else:
cont = False
if currNode is None:
self.head = Node(value)
self.head.next, prevNode.prev = prevNode, self.head
else:
if currNode is self.tail:
currNode.next = Node(value)
currNode.next.prev, self.tail = self.tail, currNode.next
else:
currNode.next = Node(value)
prevNode.prev = currNode.next
currNode.next.next, currNode.next.prev = prevNode, currNode
def find(self, val):
if self.len() == 0:
return None
else:
if self.__ascending == True:
currNode = self.head
while currNode is not None:
x = self.compare(currNode.value, val)
if x == 1:
return None
elif x == 0:
return currNode
else:
currNode = currNode.next
if self.__ascending == False:
currNode = self.tail
while currNode is not None:
x = self.compare(currNode.value, val)
if x == 1:
return None
elif x == 0:
return currNode
else:
currNode = currNode.prev
if currNode == None:
return None
def delete(self, val):
currNode = self.head
prevNode = None
if self.head is None:
return None
else:
if self.head.value == val:
if self.len() == 1:
self.head = None
self.tail = None
return
else:
currNode = self.head.next
self.head = currNode
currNode.prev = None
return
while currNode is not None:
if currNode.value == val:
prevNode.next = currNode.next
if currNode is self.tail:
self.tail = prevNode
else:
currNode.next.prev = prevNode
return
else:
prevNode = currNode
currNode = currNode.next
def clean(self, asc):
self.head = None
self.tail = None
self.__ascending = asc
def len(self):
currNode = self.head
count = 0
while currNode is not None:
currNode = currNode.next
count += 1
return count
def get_all(self):
r = []
node = self.head
while node != None:
r.append(node)
node = node.next
return r
class OrderedStringList(OrderedList):
def __init__(self, asc):
super(OrderedStringList, self).__init__(asc)
def compare(self, v1, v2):
test_string1 = v1.strip()
test_string2 = v2.strip()
if v1 < v2:
return -1
elif v1 == v2:
return 0
else:
return +1
|
#Made of merge and sort. Merge only merges two SORTED lists
#Break a list of length n into n 1 length lists (inherently sorted) and then merge them 2 at a time
#Has a space of 0(n) complexity, time to break is O(logn) time to put back is O(n) therefore total time complexity is O(nlogn). Most efficient you can make a sorting algorithm
def merge(list1, list2):
combined = []
i = 0
j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
combined.append(list1[i])
i += 1
else:
combined.append(list2[j])
j += 1
if i == len(list1):
combined += list2[j:]
else:
combined += list1[i:]
return combined
def merge_sort(my_list):
if len(my_list) == 1:
return my_list
mid_index = len(my_list)//2
left = merge_sort(my_list[:mid_index])
right = merge_sort(my_list[mid_index:])
return merge(left, right)
l1 = [7, 5, 3 ,1, 8, 6, 4, 2]
print(merge_sort(l1))
|
#Bubble sort compares values and switches them if the value later on is lower
def bubble_sort(list_):
for i in range(len(list_) - 1, 0, -1):
for j in range(i):
if list_[j] > list_[j + 1]:
list_[j], list_[j + 1] = list_[j + 1], list_[j]
return list_
ex_list = [5, 4, 7, 0, 1, 2, 3, 6]
print(bubble_sort(ex_list)) |
# coding:utf-8
import os
import numpy as np
import matplotlib.pyplot as plt
class lr_classifier(object):
"""
使用梯度上升算法 LR 分类器
"""
@staticmethod
def sigmoid(x):
"""
:param x: sigmoid function
:return:
"""
return 1.0 / (1 + np.exp(-x))
def gradient_ascent(self, data, labels, max_iter=1000):
"""
:param data: 数据特征矩阵 M, N numpy matrix
:param labels: 数据集对应的类型向量 N,1
:param max_iter:
:return:
"""
data = np.matrix(data) # (100, 3)
label = np.matrix(labels).reshape(-1, 1) # (100, 1)
m, n = data.shape
w = np.ones((n, 1)) # [1, 1, 1] (100, 3) x (3, 1) -> (100, 1)
alpha = 0.001
ws = []
for i in range(max_iter):
error = label - self.sigmoid(data * w) # (100, 1) 所有数据更新
w += alpha * data.T * error # (3, 100) x (100, 1) -> W (3, 1)
ws.append(w.reshape(-1, 1).tolist()[0])
self.w = w # (3,1)
return w, np.array(ws)
def classify(self, data, w=None):
"""
测试
:param data:
:param w:
:return:
"""
if w is None:
w = self.w
data = np.matrix(data)
prob = self.sigmoid((data * w).tolist()[0][0])
return round(prob)
def load_data(filename):
data_set, labels = [], []
with open(filename, 'r') as f:
for line in f:
split_line = [float(i) for i in line.strip().split('\t')]
data, label = [1.0] + split_line[:-1], split_line[-1]
# print([1.0] + split_line[:-1]) 第一列:全为1
data_set.append(data)
labels.append(label)
data_set = np.matrix(data_set)
labels = np.matrix(labels)
return data_set, labels
# #### 有问题
def snap_shot(w, data_set, labels, picture_name):
"""
绘制类型分割线图
"""
if not os.path.exists('./snap_shots'):
os.mkdir('./snap_shots')
fig = plt.figure()
ax = fig.add_subplot()
pts = {}
# for data, label in zip(data_set.tolist(), labels.tolist()):
# pts.setdefault(label, []).append(data)
for j in range(len(labels)):
pts.setdefault(labels.tolist()[0][j], []).append(data_set[j].tolist())
for label, data in pts.items():
# data = np.array(data)
plt.scatter(data[0][0][1], data[0][0][2], label=label, alpha=0.5)
# 分割线绘制
def get_y(x, w):
w0, w1, w2 = w
return (-w0 - w1 * x) / w2
x = [-4.0, 3.0]
print(w)
y = [get_y(i, w) for i in x]
plt.plot(x, y, linewidth=2)
picture_name = './snap_shots/{}'.format(picture_name)
fig.savefig(picture_name)
plt.close(fig)
if __name__ == '__main__':
data_set, labels = load_data('testSet.txt')
# print(data_set.shape, labels.shape) 100x3 1x100
clf = lr_classifier()
w, ws = clf.gradient_ascent(data_set, labels, max_iter=5000) # (3, 1) (5000, 1)
m, n = ws.shape
'''
for i in range(300):
if i % 30 == 0:
print('{}.png saved'.format(i))
snap_shot(ws[i].tolist(), data_set, labels, '{}.png'.format(i))
fig = plt.figure()
for i in range(n):
label = 'w{}'.format(i)
ax = fig.add_subplot(n, 1, i + 1)
ax.plot(ws[:, i], label=label)
ax.legend()
fig.savefig('w_tra.png')
'''
|
# Assignment: Names
# Write the following function.
# Part I
# Given the following list:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
# Copy
# Create a program that outputs:
# Michael Jordan
# John Rosales
# Mark Guillen
# KB Tonel
# Copy
# Part II
# Now, given the following dictionary:
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
# Copy
# Create a program that prints the following format (including number of characters in each combined name):
# Students
# 1 - MICHAEL JORDAN - 13
# 2 - JOHN ROSALES - 11
# 3 - MARK GUILLEN - 11
# 4 - KB TONEL - 7
# Instructors
# 1 - MICHAEL CHOI - 11
# 2 - MARTIN PURYEAR - 13
# Copy
# Note: The majority of data we will manipulate as web developers will be hashed in a dictionary using key-value pairs. Repeat this assignment a few times to really get the hang of unpacking dictionaries, as it's a very common requirement of any web application.
def myList(var):
for x in var:
print x["first_name"], x["last_name"]
myList(students)
def myList2(var):
for x in var:
count = 0
print x
for y in var[x]:
count = count + 1
first_name = y["first_name"].upper()
last_name = y["last_name"].upper()
char = len(first_name) + len(last_name)
print "{} - {} {} - {}".format(count, first_name, last_name, char)
myList2(users)
|
class Animal:
def __init__(self, esperanzaVida, nombre):
self._esperanzaVida = esperanzaVida
self._nombre = nombre
class Invertebrados (Animal):
def __init__(self, habitat, esperanzaVida, nombre):
self.habitat = habitat
Animal(esperanzaVida, nombre)
class Vertebrados (Animal):
def __init__(self, cantidadHuesos, esperanzaVida, nombre):
self._cantidadHuesos = cantidadHuesos
Animal(esperanzaVida, nombre)
class Mamiferos (Vertebrados):
def __init__(self, tipoPelaje, cantidadHuesos, esperanzaVida, nombre):
self._tipoPelaje = tipoPelaje
Vertebrados(cantidadHuesos, esperanzaVida, nombre)
class Aves (Vertebrados):
def __init__(self, tipoPlumas):
self._tipoPlumas = tipoPlumas
Vertebrados(cantidadHuesos, esperanzaVida, nombre)
class Reptiles (Vertebrados):
def __init__(self, tipoEscamas):
self._tipoEscamas = tipoEscamas;
Vertebrados(cantidadHuesos, esperanzaVida, nombre) |
class PlaylistIterator:
"""Iterator for class Playlist"""
def __init__(self, playlist):
self._songs = playlist.songs
self._index = 0
def __next__(self):
if self._index < len(self._songs):
song_obj = self._songs[self._index]
self._index += 1
return song_obj
raise StopIteration
|
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
from xgboost import XGBClassifier
from sklearn.metrics import roc_auc_score
from category_encoders import OrdinalEncoder
class Baseline:
"creating minimum standards"
def __init__(self, data, target, feat, col):
pass
def train_test(df, target, feat):
"""
THIS FUNCTION DOES NOT DO TIME SERIES SPLITS
This is a function to split your dataframe into you training, validation, test,
and cross validations dataframes. This function returns 8 values
so have 8 var names ready to capture all values outputted by the funcntion.
Example (Using Titanic data set as example filler target/features):
X_train, y_train, X_val, y_val, X_test, y_test, X_test_CV, y_test_CV =
train_test(df, "survived", ["age", "fare", "class"])
This inputs of the function are as follows:
df = the dataframe to be split (cleaned or dirty)
target = Your target (y)
feat = Your features being used passed in as a list or a object pointing to a
list
This function will also display a labled list of the shape of each new
dataframe that was created (8 dataframes in total) for quick fact checking
"""
df = pd.DataFrame(data=df)
df = df.copy()
training, testing = train_test_split(df, random_state=42)
train, val = train_test_split(training, random_state=42)
y = target
features = feat
X_train = train[features]
y_train = train[target]
X_val = val[features]
y_val = val[target]
X_test = testing[features]
y_test = testing[target]
X_test_CV = df[features]
y_test_CV = df[target]
print(f"Original Data Frame Shape: {df.shape}")
print()
print(f"Target: {y}")
print(f"Features: {features}")
print()
print(f"X Training Shape: {X_train.shape}")
print(f"y Training Shape: {y_train.shape}")
print()
print(f"X Validation Shape: {X_val.shape}")
print(f"y Validation Shape: {y_val.shape}")
print()
print(f"X Testing Shape: {X_test.shape}")
print(f"y Testing Shape: {y_test.shape}")
print()
print(f"X Cross Validation Testing Shape: {X_test_CV.shape}")
print(f"y Cross Validation Testing Shape: {y_test_CV.shape}")
return (X_train,
y_train,
X_val,
y_val,
X_test,
y_test,
X_test_CV,
y_test_CV)
def date(df, col):
"""
This is a function for turning a date column that includes month, day, and year
into 5 separate columns that includes: Pandas date time, year, month, day, season.
Seasons identified as: {3,4,5:spring, 6,7,8:summer, 9,10,11:autumn, 12,1,2:winter}
"""
df = df.copy()
season = {1: 'winter',
2: 'winter',
3: 'spring',
4: 'spring',
5: 'spring',
6: 'summer',
7: 'summer',
8: 'summer',
9: 'autumn',
10: 'autumn',
11: 'autumn',
12: 'winter'}
df = pd.DataFrame(data=df)
df['pd_date_time'] = pd.to_datetime(df[col])
df['day'] = df['pd_date_time'].dt.day
df['month'] = df['pd_date_time'].dt.month
df['year'] = df['pd_date_time'].dt.year
df['season'] = df['month'].map(season)
return df
def xgb_reg(X_train, y_train, X_test, y_test):
"""
Simple pipeline Baseline model for using XGB Regressor including a
ordinal encoder, standard scaler, simple imputer. This function returns
Mean baseline, R^2, and RMSE. If R^2 is negative this means mean
baseline is a more effective model
"""
s1 = pd.Series(y_train)
s2 = pd.Series(y_test)
s3 = s1.append(s2)
mean = np.mean(s3)
model = make_pipeline(
OrdinalEncoder(),
StandardScaler(),
SimpleImputer(strategy='median'),
XGBRegressor(
n_estimators=100,
n_jobs=-1,
max_depth=10
)
)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
r2 = r2_score(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print(f'Mean baseline of target = {mean}')
print(f'Gradient Boosting R^2 = {r2}')
print(f'Gradient Boosting RMSE = {rmse}')
return
def xgb_class(X_train, y_train, X_test, y_test):
"""
Baseline XGB Classifier that prints out ROC score for Train and Test
sets provided.
"""
class_index = 1
# processor = make_pipeline(
# ce.ordinal.OrdinalEncoder(),
# SimpleImputer(strategy='median')
# )
# X_train_processed = processor.fit_transform(X_train)
# X_test_processed = processor.transform(X_test)
encoder = OrdinalEncoder()
imputer = SimpleImputer()
X_train_encoded = encoder.fit(X_train)
X_train_encoded = encoder.transform(X_train)
X_train_imputed = imputer.fit_transform(X_train_encoded)
X_test_encoded = encoder.fit(X_test)
X_test_encoded = encoder.transform(X_test)
X_test_imputed = imputer.fit_transform(X_test_encoded)
model = XGBClassifier(
n_estimators=100,
n_jobs=-1,
max_depth=10
)
model.fit(X_train_imputed, y_train, eval_metric='auc')
# Getting the predicted probabilities
y_pred = model.predict(X_test_processed)
y_pred_proba_train = model.predict_proba(X_train_imputed)[:, class_index]
y_pred_proba_test = model.predict_proba(X_test_imputed)[:, class_index]
train_roc = roc_auc_score(y_train, y_pred_proba_train)
test_roc = roc_auc_score(y_test, y_pred_proba_test)
# Making a new Series for mean baseline print
s1 = pd.Series(y_train)
s2 = pd.Series(y_test)
s3 = s1.append(s2)
print('Mean Baseline of Target')
print(s3.value_counts(normalize=True))
print()
print(f'Train ROC AUC for class: {train_roc} \n')
print(f'Test ROC AUC for class: {test_roc}')
return
|
import numpy as np
from quaternion import *
from rotation_matrix import *
class Transform(object):
"""
Homogeneous transform object
:Example:
T = Transform(np.zeros(3), Quaternion())
>>> quaternions = [Quaternion(q/np.linalg.norm(q)) for q in np.random.rand(5,4)]
>>> positions = [p for p in np.random.rand(100,3)]
>>> transform_list = [Transform(position, orientation) for position, orientation in zip(positions, quaternions)]
>>> inverted_list = [transform.i @ transform for transform in transform_list]
>>> all([np.allclose(transform.position, np.zeros(3)) and np.allclose(transform.orientation.q, Quaternion().q) for transform in inverted_list])
True
"""
def __init__(self, position=None, orientation=None):
if position is None:
self._position = np.zeros(3)
else:
self._position = position[:3]
if orientation is None:
self._orientation = Quaternion()
else:
self._orientation = Quaternion(orientation)
def __repr__(self):
return "Position: " + self._position.__str__() + " "+ self.orientation.__repr__()
def __matmul__(self, other):
orientation = self.orientation * other.orientation
# Hamilton quaternion product
position = ((self.orientation * Quaternion([0, *other.position]) * self.orientation.i).q
+ np.array([0, *self.position]))[1:]
return Transform(position, orientation)
@property
def i(self):
position = -((self.orientation.i * Quaternion([0, *self.position]) * self.orientation).q[1:])
orientation = self.orientation.i
return Transform(position, orientation)
@property
def position(self):
return self._position
@property
def orientation(self):
return self._orientation
|
from threading import Thread
i = 0
def someThreadFunction1():
global i
while i<1000000:
i+=1
print ("first\n")
def someThreadFunction2():
global i
while i<1000000:
i+=1
print ("second\n")
def main():
someThread1 = Thread(target = someThreadFunction1, args = (),)
someThread1.start()
someThread2 = Thread(target = someThreadFunction2, args = (),)
someThread2.start()
someThread1.join()
someThread2.join()
print("ferdig!\n")
main()
|
__author__ = 'Pato'
class Program:
def __init__(self, a_name):
self.instructions = []
self.program_name = a_name
self.program_size = 0
self.instructions.append('EOF')
def run(self):
for i in self.instructions:
i.execute()
def get_instructions(self):
return self.instructions
def add_instruction(self, instruction):
self.instructions.insert(self.program_size, instruction)
self.program_size += 1
def get_program_size(self):
return self.program_size
def get_program_name(self):
return self.program_name
|
# Prompt: Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional data structures?
def is_unique(val : str) -> bool:
copy = val
for i in val:
copy = copy[1:]
if i in copy:
return False
return True
assert(is_unique("aaaa") == False), f"Input: 'aaaa' should be False"
assert(is_unique("bbaa") == False), f"Input: 'abab' should be False"
assert(is_unique("abab") == False), f"Input: 'abab' should be False"
assert(is_unique("") == True), f"Input: '' should be False"
assert(is_unique("abcd") == False), f"Input: 'abcd' should be False"
|
# Prompt: Given an image represented by an NxN matrix, where each pixel is 4 bytes,
# write a method to rotate the image 90 degrees. Can you do this in place?
def rotate(img : [[]]) -> [[]]:
layers = int((len(img)/2)+0.5)
offset = 0
for i in range(0, layers):
for j in range(0, len(img)-1-(offset*2)):
item1 = img[i][j+offset]
item2 = img[j+offset][len(img)-1-offset]
item3 = img[len(img)-1-offset][len(img)-1-j-offset]
item4 = img[len(img)-1-j-offset][i]
img[i][j+offset] = item4
img[j+offset][len(img)-1-offset] = item1
img[len(img)-1-offset][len(img)-1-j-offset] = item2
img[len(img)-1-j-offset][i] = item3
offset += 1
return img
test = [["a", "b", "c", "d"],
["e", "f", "g", "h"],
["i", "j", "k", "l"],
["m", "n", "o", "p"]]
expected = [["m", "i", "e", "a"],
["n", "j", "f", "b"],
["o", "k", "g", "c"],
["p", "l", "h", "d"]]
test2 = [["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]]
expected2 = [["g", "d", "a"],
["h", "e", "b"],
["i", "f", "c"]]
test3 = [["a", "b"],
["c", "d"]]
expected3 = [["c", "a"],
["d", "b"]]
assert(rotate(test) == expected)
assert(rotate(test2) == expected2)
assert(rotate(test3) == expected3)
assert(rotate([[]]) == [[]])
|
# Prompt: Given a string, write a function to check if it is a permutation of a palindrome.
# A palindrome is a word or phrase that is the same forwards and backwards.
# A permutation is a rearrangement of letters.
# The palindrome does not need to be limted to just dictionary words
# Ex:
# Input: Tact Coa
# Output: True
# Brute force: Generalize all permutations until that permutation is a palindrome
# Better: Sort the string and try to create two ends of a palindrome
# Runtime improvement => O(n!n) => O(2n + log(n))
def is_palindrome(val:str) -> bool:
val = sorted(val.lower().replace(' ','')) # O(log(n))
odds = 0
counts = {}
for i in val:
counts[i] = val.count(i) # O(n)
for i in counts.values(): # O(n)
if i%2 != 0:
odds += 1
if len(val) %2 == 0 and odds != 0:
return False
elif len(val) %2 != 0 and odds != 1:
return False
return True
assert(is_palindrome("ab") == False)
assert(is_palindrome("bbbbac") == False)
assert(is_palindrome("a") == True)
assert(is_palindrome("Tact Coa") == True)
assert(is_palindrome("") == True)
assert(is_palindrome("aaaa") == True)
assert(is_palindrome("moonoom") == True)
assert(is_palindrome("baaab") == True)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 6 17:15:02 2020
@author: Yusef Quinlan
"""
from tkinter import*
from tkinter import ttk
import os
import PyPDF2
from gtts import gTTS
#Make a main window
Main = Tk()
Main.title("ConvertPDFtoMp3")
#C:\Users\User\Downloads so I can see my directory name for testing.
"""
Saves and converts a chosen pdf file from a start point chosen by
the user to an end point chosen by the user (i.e could be pages 6-18 of a pdf)
this is so that users can skip contents pages or just take chapters. Saves
pdf as mp3 file in the same directory it is in, rather the directory that this
file is run from.
"""
def save(FileAbsPath,Start,End):
pdfOpen = open(FileAbsPath, 'rb')
pdfRead = PyPDF2.PdfFileReader(pdfOpen)
text = ""
for i in range(int(Start.get()) -1,int(End.get()) ):
text += pdfRead.getPage(i).extractText()
Audio_file = gTTS(text=text, lang='en')
Audio_file.save(FileAbsPath.replace(".pdf",".mp3"))
"""
This makes a new window pop-up when the 'convert' button is pressed in the
second window. And allows the third window generated to convert a selected
pdf file given the start and end page
"""
def convertBtn(Dir1,Listb):
FileAbsPath = os.path.join(Dir1,Listb.get(Listb.curselection()))
Name = Listb.get(Listb.curselection())
Main3 = Tk()
Main3.title("Choose conversion options for " + FileAbsPath)
Label(Main3, text=" Conversion process for " + str(Name)).grid(row=0,column=0)
Label(Main3, text=" ").grid(row=1,column=0)
Label(Main3, text=" Below enter the number of the page you wish to start converting from").grid(row=2,column=0)
Entry(Main3, width=80).grid(row=3,column=0)
Label(Main3, text="").grid(row=4,column=0)
Label(Main3, text="Below enter the number of the page you wish to end the conversion at").grid(row=5,column=0)
Entry(Main3,width=80).grid(row=6,column=0)
Start = Main3.grid_slaves(row=3,column=0)[0]
End = Main3.grid_slaves(row=6,column=0)[0]
Button(Main3,text="Convert",command=lambda z=FileAbsPath,y=Start,x=End: save(z,y,x)).grid(row=7,column=0)
"""
Opens a second window when users click the directory button with a valid
directory as an argument in the entry widget of the main window, second
window lists all the pdf files in that directory and allows users to
select pdfs to be converted (one at a time) in another window by the user.
"""
def getdir():
# File not found error to be resolved or try-catched.
Dir1 = Main.grid_slaves(row=1,column=0)[0].get()
print(Dir1)
Main2 = Tk()
Main2.title("Select pdfs in directory: " + Dir1)
F1 = Frame(Main2)
scroller = Scrollbar(F1)
Listb = Listbox(F1)
scroller.pack(side=RIGHT, fill=Y)
Listb.pack(side=LEFT, fill=Y)
Listb.config(width=0)
scroller['command'] = Listb.yview
Listb['yscrollcommand'] = scroller.set
for file in os.listdir(Dir1):
if (file.endswith(".pdf")) :
Listb.insert(END, file)
F1.pack(side=TOP)
F2 = Frame(F1)
Btn = Button(F2, text="Select",command=lambda z=Dir1,x = Listb: convertBtn(z,x))
Btn.pack()
F2.pack(side=TOP)
Main2.mainloop()
"""
Widgets in the main window.
"""
dirpromt = "Enter the directory path that contains pdfs you wish to convert"
dirbuttontxt = "Opens a window that allows conversion of all pdfs in a stated directory"
Label(Main, text=dirpromt).grid(row=0,column=0)
Entry(Main,width=140).grid(row=1,column=0)
Button(Main,text=dirbuttontxt,bg='blue',command=getdir).grid(row=2,column=0)
Main.mainloop() |
num=int(input("Whos factorial do u want?"))
def recur(num):
if num==1:
return num
else:
return num*recur(num-1)
print("The factorial is", recur(num)) |
def shortNOT(val):
return (~(val & 65535) & 65535)
def shortLSHIFT(val, shift):
return ((val & 65535) << shift) & 65535
def shortRSHIFT(val, shift):
return ((val & 65535) >> shift) & 65535
def shortAND(val1, val2):
return (val1 & 65535) & (val2 & 65535)
def shortOR(val1, val2):
return (val1 & 65535) | (val2 & 65535)
def findVal(lines, wires, wire):
# If the wire was already calculated, just return that
if wire in wires:
return wires[wire]
# If it's a digit, just return that
if wire.isdigit():
return int(wire)
# Go through every line to find the gate that
# contains the wire we're looking for. Then,
# recursively find the value for each wire on
# that gate.
for line in lines:
words = line.split()
# Simple assignment
if words[1] == '->':
if words[2] != wire:
continue
wires[wire] = findVal(lines, wires, words[0])
return wires[wire]
elif words[0] == 'NOT':
if words[3] != wire:
continue
wires[wire] = shortNOT(findVal(lines, wires, words[1]))
return wires[wire]
else:
if words[4] != wire:
continue
lhs = findVal(lines, wires, words[0])
rhs = findVal(lines, wires, words[2])
if words[1] == 'AND':
wires[wire] = shortAND(lhs, rhs)
elif words[1] == 'OR':
wires[wire] = shortOR(lhs, rhs)
elif words[1] == 'LSHIFT':
wires[wire] = shortLSHIFT(lhs, rhs)
elif words[1] == 'RSHIFT':
wires[wire] = shortRSHIFT(lhs, rhs)
return wires[wire]
# If we get here, we're boned :)
return None
wires = {}
with open('input.txt') as f:
lines = f.readlines()
tmp = findVal(lines, wires, 'a')
print wires['a']
# Note: Answer to Input A is 956
# Answer to Input B is 40149
# All that's different for B is we added an extra line
|
"""
App for nonlinear_vector_field.py
TODO:
Need to implement moving the plot view and zooming out
with the mouse. Initial attempts at this implementation
are found in the commented out parts of code.
Setup different ways to plot trajectories, such
as plotting multiple trajectories.
"""
import tkinter as tk
from nonlinear_vector_field import NonLinearVectorField2D
from matplotlib.backends import backend_tkagg
class App(NonLinearVectorField2D):
"""
"""
def __init__(self) -> None:
"""
This is the constructor.
"""
# Initialize the parent class
NonLinearVectorField2D.__init__(self)
# Primary Tkinter GUI
self.window = tk.Tk()
self.window.title("Linear Vector Field in 2D")
self.window.configure()
# Canvas
# A short example of how to integrate a Matplotlib animation into a
# Tkinter GUI is given here:
# https://stackoverflow.com/a/21198403
# [Answer by HYRY: https://stackoverflow.com/users/772649/hyry]
# Link to question: https://stackoverflow.com/q/21197728
# [Question by user3208454:
# https://stackoverflow.com/users/3208454/user3208454]
self.canvas = backend_tkagg.FigureCanvasTkAgg(
self.figure,
master=self.window
)
maxrowspan = 18
self.canvas.get_tk_widget().grid(
row=0, column=0, rowspan=maxrowspan, columnspan=3)
self._canvas_height = self.canvas.get_tk_widget().winfo_height()
self.canvas.get_tk_widget().bind("<B1-Motion>", self.mouse_listener)
# Right click menu
self.menu = tk.Menu(self.window, tearoff=0)
self.menu.add_command(label="Use Forward-Euler",
command=lambda *args:
self.particle.set_method(
"Forward-Euler"))
self.menu.add_command(label="Use Runge-Kutta",
command=lambda *args:
self.particle.set_method(
"Runge-Kutta"))
self.window.bind("<ButtonRelease-3>", self.popup_menu)
# Thanks to stackoverflow user rudivonstaden for
# giving a way to get the colour of the tkinter widgets:
# https://stackoverflow.com/questions/11340765/
# default-window-colour-tkinter-and-hex-colour-codes
#
# https://stackoverflow.com/q/11340765
# [Question by user user2063:
# https://stackoverflow.com/users/982297/user2063]
#
# https://stackoverflow.com/a/11342481
# [Answer by user rudivonstaden:
# https://stackoverflow.com/users/1453643/rudivonstaden]
#
colour = self.window.cget('bg')
if colour == 'SystemButtonFace':
colour = "#F0F0F0"
# Thanks to stackoverflow user user1764386 for
# giving a way to change the background colour of a plot.
#
# https://stackoverflow.com/q/14088687
# [Question by user user1764386:
# https://stackoverflow.com/users/1764386/user1764386]
#
self.figure.patch.set_facecolor(colour)
self._zoom = False
self._mouse_action = 2
# self.mouse_dropdown_dict = {"Move Plot Around": 1,
# "Plot Trajectories": 2}
# self.mouse_dropdown_string = tk.StringVar(self.window)
# self.mouse_dropdown_string.set("Set Mouse...")
# self.mouse_dropdown = tk.OptionMenu(
# self.window,
# self.mouse_dropdown_string,
# *tuple(key for key in self.mouse_dropdown_dict),
# command=self.set_mouse_action
# )
# self.mouse_dropdown.grid(
# row=0, column=3, padx=(10, 10), pady=(0, 0)
# )
# self.canvas.get_tk_widget().bind_all("<MouseWheel>", self.zoom)
# self.canvas.get_tk_widget().bind_all("<Button-4>", self.zoom)
# self.canvas.get_tk_widget().bind_all("<Button-5>", self.zoom)
self.preset_dropdown_dict = {
"Linear": ["a*x - b*y + k1", "c*x + d*y + k2"],
"Pendulum 1": ["y", "5*a*sin(k*x/2)"],
"Pendulum 2": ["y", "5*a*sin(k*x/2)-b*y"],
# "Rescaled Lotka–Volterra": ["a*(x+10)/2 - b*(x+10)*(y+10)/2",
# "d*(x+10)*(y+10)/4 - e*(y+10)/2"]
"Lotka–Volterra": ["10*a*x/2 - 3*b*x*y/2",
"6*d*x*y/4 - 10*e*y/2"]
}
self.preset_dropdown_string = tk.StringVar(self.window)
self.preset_dropdown_string.set("Choose Preset Vector Field")
self.preset_dropdown = tk.OptionMenu(
self.window,
self.preset_dropdown_string,
*tuple(key for key in self.preset_dropdown_dict),
command=self.set_preset_dropdown
)
self.preset_dropdown.grid(
row=1, column=3, padx=(10, 10), pady=(0, 0))
# Enter vx
self.entervxlabel = tk.Label(self.window,
text="Enter f(x, y)")
self.entervxlabel.grid(
row=2,
column=3,
columnspan=2,
sticky=tk.W + tk.E + tk.S,
padx=(10, 10)
)
self.enter_vx = tk.Entry(self.window)
self.enter_vx.bind("<Return>", self.update_function_by_entry)
self.enter_vx.grid(
row=3,
column=3,
columnspan=2,
sticky=tk.W + tk.E + tk.N + tk.S,
padx=(10, 10)
)
self.enter_vx_button = tk.Button(self.window,
text="OK",
command=self.update_function_by_entry)
self.enter_vx_button.grid(
row=4,
column=3,
columnspan=2,
sticky=tk.W + tk.E + tk.N,
padx=(10, 10)
)
# Enter vy
self.entervylabel = tk.Label(self.window,
text="Enter g(x, y)")
self.entervylabel.grid(
row=5,
column=3,
columnspan=2,
sticky=tk.W + tk.E + tk.S,
padx=(10, 10)
)
self.enter_vy = tk.Entry(self.window)
self.enter_vy.bind("<Return>", self.update_function_by_entry)
self.enter_vy.grid(
row=6,
column=3,
columnspan=2,
sticky=tk.W + tk.E + tk.N + tk.S,
padx=(10, 10)
)
self.enter_vy_button = tk.Button(self.window,
text="OK",
command=self.update_function_by_entry)
self.enter_vy_button.grid(
row=7,
column=3,
columnspan=2,
sticky=tk.W + tk.E + tk.N,
padx=(10, 10)
)
# Sliders
self.sliderslist = []
self.sliderslist_symbols = []
self.simulation_speed_slider = None
self.quit_button = None
self.set_sliders()
self.set_preset_dropdown("Linear")
self.preset_dropdown_string.set("Choose Preset Vector Field")
def set_preset_dropdown(self, *event: tk.Event) -> None:
"""
Set the dropdown of the functions.
"""
event = event[0]
args_vx, args_vy = self.preset_dropdown_dict[event]
self._update_function(args_vx, args_vy)
if event == "Lotka–Volterra":
if any([self.bounds[i] != [0.0, 10.0, 0.0, 10.0][i]
for i in range(len(self.bounds))]):
self.set_bounds([0.0, 10.0, 0.0, 10.0])
else:
if any([self.bounds[i] != [-10.0, 10.0, -10.0, 10.0][i]
for i in range(len(self.bounds))]):
self.set_bounds([-10.0, 10.0, -10.0, 10.0])
# def set_mouse_action(self, *event: tk.Event) -> None:
# """
# Set the mouse action.
# """
# event = event[0]
# self._mouse_action = self.mouse_dropdown_dict[event]
def slider_update(self, *event: tk.Event) -> None:
"""
Update the functions given input from the slider.
"""
self.particle.remove_line()
vx_params = self._vx.get_default_values()
vy_params = self._vy.get_default_values()
for i in range(len(self.sliderslist)):
symbol = self.sliderslist_symbols[i]
if symbol in vx_params:
vx_params[symbol] = self.sliderslist[i].get()
if symbol in vy_params:
vy_params[symbol] = self.sliderslist[i].get()
# print(self.sliderslist_symbols)
# print("vx params: ", vx_params)
# print("vy params: ", vy_params, "\n")
self.vxparams = []
for key in self._vx.symbols:
if key in vx_params:
self.vxparams.append(vx_params[key])
self.vyparams = []
for key in self._vy.symbols:
if key in vy_params:
self.vyparams.append(vy_params[key])
# vx_parameter_set = {s for s in self._vx.get_default_values()}
# vy_parameter_set = {s for s in self._vy.get_default_values()}
# self.vxparams = [vx_params[s] for s in vx_parameter_set]
# self.vyparams = [vy_params[s] for s in vy_parameter_set]
self.plot_vector_field(change_title=False)
# self._clear_plot_after_zoom_or_move()
def mouse_listener(self, event: tk.Event) -> None:
"""
Listen to mouse input on the canvas and then call further
functions in order to handle this.
"""
if self._mouse_action == 2:
ax = self.figure.get_axes()[0]
xlim = ax.get_xlim()
ylim = ax.get_ylim()
pixel_xlim = [ax.bbox.xmin, ax.bbox.xmax]
pixel_ylim = [ax.bbox.ymin, ax.bbox.ymax]
height = self.canvas.get_tk_widget().winfo_height()
mx = (xlim[1] - xlim[0])/(pixel_xlim[1] - pixel_xlim[0])
my = (ylim[1] - ylim[0])/(pixel_ylim[1] - pixel_ylim[0])
x = (event.x - pixel_xlim[0])*mx + xlim[0]
y = (height - event.y - pixel_ylim[0])*my + ylim[0]
self.set_interactive_line(x, y)
# elif self._mouse_action == 1:
# ax = self.figure.get_axes()[0]
# xlim = ax.get_xlim()
# ylim = ax.get_ylim()
def _update_function(self, args_vx: str, args_vy: str) -> None:
"""
Helper function for update_function_by_entry and
update_function_by_preset.
"""
self.set_vx(args_vx)
self.set_vy(args_vy)
# self.f = Functionx(str_args)
# ones = ([1 for i in range(len(self.f.symbols) - 1)])
# self.y = self.f(self.x, *ones)
self.plot_vector_field()
# self.text.set_text("f(x) = $%s$" % (self.f.latex_repr))
self.set_sliders()
# self.lim_update()
# self.set_title()
def update_function_by_entry(self, *event: tk.Event) -> None:
"""
Update the function.
"""
args_vx = self.enter_vx.get()
args_vy = self.enter_vy.get()
if args_vx.strip() == "":
args_vx = "zero(x, y)"
if args_vy.strip() == "":
args_vy = "zero(x, y)"
self.preset_dropdown_string.set("Choose Preset Vector Field")
self._update_function(args_vx, args_vy)
def set_sliders(self) -> None:
"""
Create and set sliders.
"""
rnge = 10.0
for slider in self.sliderslist:
slider.destroy()
self.destroy_widgets_after_sliders()
self.sliderslist = []
self.sliderslist_symbols = []
vx_defaults = self._vx.get_default_values()
vy_defaults = self._vy.get_default_values()
parameters = set(self._vx.parameters + self._vy.parameters)
for i, symbol in enumerate(parameters):
self.sliderslist_symbols.append(symbol)
self.sliderslist.append(tk.Scale(self.window,
label="change "
+ str(symbol) + ":",
from_=-rnge, to=rnge,
resolution=0.01,
orient=tk.HORIZONTAL,
length=200,
command=self.slider_update))
self.sliderslist[i].grid(row=i + 8, column=3,
padx=(10, 10), pady=(0, 0))
if symbol in self._vx.parameters:
self.sliderslist[i].set(vx_defaults[symbol])
if symbol in self._vy.parameters:
self.sliderslist[i].set(vy_defaults[symbol])
self.set_widgets_after_sliders(len(parameters) + 8)
def set_widgets_after_sliders(self, index: int) -> None:
"""
Set the widgets after the each of the parameter sliders.
"""
slider = tk.Scale(self.window,
label="Set simulation speed: ",
from_=0, to=20, resolution=1,
length=200,
orient=tk.HORIZONTAL,
command=self.set_simulation_speed)
slider.set(1)
slider.grid(row=index, column=3,
padx=(10, 10), pady=(0, 0))
self.simulation_speed_slider = slider
self.quit_button = tk.Button(
self.window, text='QUIT', command=self.quit)
self.quit_button.grid(row=index+1, column=3, padx=(10, 10),
pady=(0, 0))
def destroy_widgets_after_sliders(self) -> None:
"""
Destroy the widgets after each of the parameter sliders.
"""
if self.simulation_speed_slider is not None:
self.simulation_speed_slider.destroy()
if self.quit_button is not None:
self.quit_button.destroy()
def popup_menu(self, event: tk.Event) -> None:
"""
popup menu upon right click.
"""
self.menu.tk_popup(event.x_root, event.y_root, 0)
# def zoom(self, event: tk.Event) -> None:
# """
# Zoom in and out of the plot.
# """
# if event.delta == -120 or event.num == 5:
# x_scale_factor, y_scale_factor = 1.1, 1.1
# elif event.delta == 120 or event.num == 4:
# x_scale_factor, y_scale_factor = 0.9, 0.9
# ax = self.figure.get_axes()[0]
# xlim = ax.get_xlim()
# ylim = ax.get_ylim()
# dx = xlim[1] - xlim[0]
# dy = ylim[1] - ylim[0]
# xc = (xlim[1] + xlim[0])/2
# yc = (ylim[1] + ylim[0])/2
# xlim = (xc - x_scale_factor*dx/2.0, xc + x_scale_factor*dx/2.0)
# ylim = (yc - y_scale_factor*dy/2.0, yc + y_scale_factor*dy/2.0)
# # self.plot_vector_field()
# # self.set_sliders()
# self.set_bounds([xlim[0], xlim[1], ylim[0], ylim[1]])
# # self.plot_vector_field()
# self._zoom = True
# # self.set_bounds([xlim[0], xlim[1], ylim[0], ylim[1]])
# def _clear_plot_after_zoom_or_move(self) -> None:
# """
# Clear the plot after a zoom or a move.
# """
# if self._zoom:
# self.plot_vector_field()
# self._zoom = False
def quit(self, *event: tk.Event) -> None:
"""
Quit the application.
"""
self.window.quit()
self.window.destroy()
if __name__ == "__main__":
app = App()
app.animation_loop()
tk.mainloop()
|
def main():
n = int(input())
binary = str(bin(n)).replace("0b", "").split("0")
biggest = 0
for i in binary:
if len(i) > biggest:
biggest = len(i)
print(biggest)
if __name__ == '__main__':
main() |
if __name__ == '__main__':
s = input()
alnum = False
alpha = False
digit = False
lower = False
upper = False
for i in s:
if i.isalnum() == True:
alnum = True
if i.isalpha() == True:
alpha = True
if i.isdigit() == True:
digit = True
if i.islower() == True:
lower = True
if i.isupper() == True:
upper = True
print(alnum)
print(alpha)
print(digit)
print(lower)
print(upper) |
list=[]
l2=[]
m=[]
l3=[]
def Remove(l2):
final_list = []
for num in l2:
if num not in final_list:
final_list.append(num)
return final_list
n=int(input())
for i in range(0,n):
l=[]
list.append(l)
for i in range(0,n):
for j in range(0,2):
a=input()
list[i].append(a)
for i in list:
l2.append(i[1])
l2.sort()
k=Remove(l2)[1]
for i in list:
for j in i:
m.append(j)
for i in m:
if(i==k):
l3.append(m)
m=i
l3.sort()
for i in l3:
print(i)
|
def addJob(jobName,jobType,jobExp,jobGoden):
file_data = ""
num = 0
with open("Storage/Job.csv", "r") as f:
for line in f:
line_list = line.strip("\n").split(",")
if line_list[0] != "任务编号":
num = int(line_list[0])
file_data += line
with open("Storage/Job.csv","w") as f:
new_list = []
new_list.append(str(num+1))
new_list.append(jobName)
new_list.append(jobType)
new_list.append(str(jobExp))
new_list.append(str(jobGoden))
new_list.append("0")
new_line = ",".join(new_list) + "\n"
file_data += new_line
f.write(file_data)
print("任务增加完成!")
print("任务编号:" + str(num+1) + " 任务名称:《" + jobName + "》")
def addWorkJob(jobName,jobType,jobExp,jobGoden):
file_data = ""
num = 0
with open("Storage/WorkJob.csv", "r") as f:
for line in f:
line_list = line.strip("\n").split(",")
if line_list[0] != "任务编号":
num = int(line_list[0])
file_data += line
with open("Storage/WorkJob.csv","w") as f:
new_list = []
new_list.append(str(num+1))
new_list.append(jobName)
new_list.append(jobType)
new_list.append(str(jobExp))
new_list.append(str(jobGoden))
new_list.append("0")
new_line = ",".join(new_list) + "\n"
file_data += new_line
f.write(file_data)
print("工作任务增加完成!")
print("工作任务编号:" + str(num+1) + " 任务名称:《" + jobName + "》")
if __name__ == '__main__':
#添加个人任务
jobName = "加入图形化界面第一版"
jobType = "基础任务"
jobExp = 100
jobGoden = 100
addJob(jobName, jobType, jobExp, jobGoden)
#添加工作
workJobName = "检查一下昨天合并到qa分支的换签自动化执行状态"
workJobType = "普通任务"
workJobExp = 0
workJobGoden = 5
#addWorkJob(workJobName, workJobType, workJobExp, workJobGoden)
|
# author: Qiyi Shan
# date: 3.3.2017
from Homework.newsplit import new_split_iter
def priority(operator):
if operator in '+-':
return 1
elif operator in '*/':
return 2
elif operator == '**':
return 3
elif operator == '(':
return 4
elif operator == ')':
return 0
elif operator == '=':
return -1
else:
raise ValueError("%s not supported by priority function" % operator)
def to_postfix(expr_iter):
# make sure the type of parameter is Iterator
if type(expr_iter) == str:
expr_iter = list(new_split_iter(expr_iter))
operator_list = []
for item in expr_iter:
if item.isnumeric() or item[1:].isnumeric() and item[0] == '-' or item.isalpha():
yield item
else:
if item == ';':
while len(operator_list) != 0:
yield operator_list.pop()
elif item == ')':
while operator_list[-1] != '(':
yield operator_list.pop()
operator_list.pop() # remove "("
else:
if item != '**' and item != '=' and item != '(':
while len(operator_list) > 0 and operator_list[-1] != '(' and priority(
operator_list[-1]) >= priority(
item):
yield operator_list.pop()
operator_list.append(item)
if __name__ == "__main__":
print(list(to_postfix(new_split_iter("x = 1 + (y = 4)"))))
|
from Homework.infix2 import eval_infix
from Homework.newsplit import new_split_iter
from random import randint
operators = ["+", "-", "*", "/"]
# operators = ["+", "-", "*", "/", "**"]
def rand_num():
return str(randint(1, 6)) if randint(1, 2) == 1 else str(randint(-6, -1))
def rand_space():
return " " * randint(0, 1)
def rand_operator():
return operators[randint(0, len(operators) - 1)]
def genexpr(_len):
s = ""
curent_len = 0
while curent_len < _len - 1:
s += (rand_num() if randint(0, 5) != 0 else "(" + rand_space() + genexpr(
2) + rand_space() + ")") + rand_space() + rand_operator() + rand_space()
curent_len += 1
s += rand_num()
return s
def test(_expr):
try:
if eval_infix(_expr) == eval(_expr):
print('Correct')
else:
print(list(new_split_iter(_expr)))
print('Wrong ', str(_expr), '=', eval_infix(_expr), 'should be', eval(_expr))
except ValueError:
print('!!get value error', list(new_split_iter(_expr)))
except ZeroDivisionError:
print('zero division error')
for i in range(20):
expr = genexpr(3)
test(expr)
|
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['figure.figsize'] = (15, 5)
pd.set_option('display.width', 5000)
pd.set_option('display.max_columns', 60)
df = pd.read_csv('./data/311-service-requests.csv')
# we select the first five rows to see how the file looks like
print(df[:5])
# To get the noise complaints, we need to find the rows where the Complain Type column is "Noise-Street/Sidewalk"
noise_complaints = df[df['Complaint Type'] == "Noise - Street/Sidewalk"]
print(noise_complaints)
# print only the first three rows
print(noise_complaints[:3])
print(df['Complaint Type'] == "Noise - Street/Sidewalk")
is_noise = df['Complaint Type'] == "Noise - Street/Sidewalk"
in_brooklyn = df['Borough'] == "BROOKLYN"
# You can also combine more than one condition with the & operator like this:
print(df[is_noise & in_brooklyn][:5])
# Which borough has the most noise complaints?
noise_complaints = df[is_noise]
print(noise_complaints['Borough'].value_counts())
# But what if we wanted to divide by the total number of complaints,
noise_complaint_counts = noise_complaints['Borough'].value_counts()
complaint_counts = df['Borough'].value_counts()
print(noise_complaint_counts / complaint_counts)
# plot
(noise_complaint_counts / complaint_counts.astype(float)).plot(kind='bar')
plt.show()
|
# Grace Kelly 11-02-2018
# Source: https://docs.python.org/3/tutorial/controlflow.html#if-statements
x = int(input("Please enter an integer: "))
if x < 0: # if statement if x is less than zero
x = 0 # x is equal to zero, one = sign is defining character
print('Negative changed to zero') # output if x is less than zero
elif x == 0: # two equal sign is testing character, test else if above not true test if x is equal to zero
print('Zero')
elif x == 1: # test else if x is equal to one if abpove statements are not true
print('Single')
else: # or else print
print('More')
print("The final value of x is:", x)
|
#Grace Kelly
#https://projecteuler.net/problem=1
#list all the natural numbers below 10
#that are multiples of 3 or 5, we get 3, 5, 6 and 9.
#The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
x = 1
for i in range(1000): # all natural numbers below 1000
if i % 3 == 0 or i % 5 == 0: # is is divisable by 3 or 5
x += i # x = x + i
print (x)
|
isim=input("İsminizi giriniz->")
print(isim)
sayı1=float(input("İlk sayıyı giriniz->"))
sayı2=float(input("İlk sayıyı giriniz->"))
print(sayı1)
print(sayı2)
topla=sayı1+sayı2
print(topla)
print(type(topla))
dönüşüm=int(topla)#float cinsi verilen sayıyı inte cevirdik.
print(type(dönüşüm))
|
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:return 0
len_list = len(nums)
i = 0
for j in range(1,len(nums)):
if nums[i] != nums[j]:
nums[i+1] = nums[j]
i += 1
return i+1
x = Solution()
print(x.removeDuplicates([1,1,2])) |
import math
import numpy
class Solver:
def __init__(self):
self.foundSolution = False
def canPlaceNumber(self, sudokuGrid, row, column, number):
for r in range(9):
if(sudokuGrid[r][column] == number):
return False
for c in range(9):
if(sudokuGrid[row][c] == number):
return False
sqrt = int(math.sqrt(len(sudokuGrid[0])))
beginningRow = row - row % sqrt
beginningColumn = column - column % sqrt
for i in range(beginningRow, beginningRow+3):
for n in range(beginningColumn, beginningColumn+3):
if(sudokuGrid[i][n] == number):
return False
return True
def getSolutions(self, sudokuGrid):
def solveUsingBacktracking(sudokuGrid):
nonlocal solutions
temp = numpy.zeros((9,9), int)
for row in range(9):
for column in range(9):
temp[row][column] = sudokuGrid[row][column]
for row in range(9):
for column in range(9):
if sudokuGrid[row][column] == 0:
for i in range(1,10):
if self.canPlaceNumber(sudokuGrid, row, column, i):
sudokuGrid[row][column] = i
temp[row][column] = i
solveUsingBacktracking(sudokuGrid)
sudokuGrid[row][column] = 0
temp[row][column] = 0
return
if row == 8 and column == 8 and sudokuGrid[row][column] != 0:
solutions.append(temp)
solutions = []
solveUsingBacktracking(sudokuGrid)
# This part checks if the user put in the right numbers
""" counter = 0
incorrectlyPlacedNumbers = 0
for solution in solutions:
print("solution: ", solution)
for x in range(9):
for row in range(9):
if counter >= 81:
counter = 0
if inputBoxes[counter].givenNumber == False:
if inputBoxes[counter].text == '':
inputBoxes[counter].markWrong(True)
incorrectlyPlacedNumbers += 1
else:
if int(inputBoxes[counter].text) == sudokuGrid[x][row]:
inputBoxes[counter].markWrong(False)
else:
inputBoxes[counter].markWrong(True)
incorrectlyPlacedNumbers += 1
counter += 1
Tk().wm_withdraw()
# displays both the messages
if incorrectlyPlacedNumbers == 0:
self.foundSolution = True
if self.foundSolution == True:
messagebox.showinfo('', 'Correct! (if there are squares marked red, they indicate that there are other possible solutions)')
self.foundSolution = False """
return solutions |
#12)“Mă iubeşte un pic, mult, cu pasiune, la nebunie, de loc, un pic,…”. Rupând petalele unei margarete cu x petale, el (ea) mă
#iubeşte …. Exemplu: Date de intrare: x=10 Date de ieşire: … de loc.
a=int(input("nr de petale: "))
b="Ma iubeste un pic"
f="Ma iubeste mult"
c="Ma iubeste cu pasiune"
d="Ma iubeste la nebunie"
e="Ma iubeste de loc"
if a>0:
if (a-(a//6)*6)==0:
print(b)
elif (a-(a//6)*6)==1:
print(f)
elif (a-(a//6)*6)==2:
print(c)
elif (a-(a//6)*6)==3:
print(d)
elif (a-(a//6)*6)==4:
print(e)
else:
print("Error")
|
#10)La ferma de găini Copanul este democraţie. Fiecare găină primeşte exact acelaşi număr de boabe de porumb. Cele care nu pot
#fi împărţite vor fi primite de curcanul Clapon. Să se spună cine a primit mai multe boabe şi cu cât. În caz de egalitate, se va
#afişa numărul de boabe primite şi cuvântul "egalitate". Datele se vor citi în următoarea ordine: numărul de găini, iar dupa aceea
#numărul de boabe de porumb. Exemplu: Date de intrare 100 4050 Date de ieşire: Curcanul mai mult cu 10 boabe.
a=int(input("Nr de gaini:"))
b=int(input("Numarul de boabe de porumb:"))
if (b%(a+1)==0):
print("egalitate")
elif(b%(a+1)!=0):
print("curcanul a primit cu ", (b%(a+1)), "boabe mai mult") |
def calcVolmSfera(radio):
return 4 / 3 * 3.14 * radio ** 3
r = float(input('Set the radio of sfera: '))
result = calcVolmSfera(r)
print(result)
|
#!/usr/local/bin/python3
# Usage: cat a column of numbers into the program
import sys
from statistics import mean, median, stdev
data = [float(i.strip('\n')) for i in sys.stdin]
print('''Count: {0}
Mean: {1:.2f}
Low: {2}
High: {3}
Median: {4}
Stdev: {5:.2f}'''.format(len(data),
mean(data),
min(data),
max(data),
median(data),
stdev(data)))
|
import numpy as np
from Encriptator import *
from diccionario import Diccionario
#Prueba array de numpy
'''
x = np.array([[0,0,0],[0,0,0],[0,0,0]])
print(x)
'''
#Prueba metodo cargarMensaje(mensaje)
'''
texto = 'TexTo De pRuEba'
mensaje = Mensaje(texto)
print(mensaje)
encriptado = Encriptador().cargarMensaje(mensaje)
print(encriptado)
'''
#prueba de matriz
'''
##Matriz con inversa
###Pasando una lista de python
arr = [[1,2,1],[0,-1,3],[2,1,0]]
matriz1 = Matriz(arr)
print(matriz1)
###Pasando un array de numpy
arrnp = np.array(arr)
matriz2 = Matriz(arrnp)
print(matriz2)
###Ambos funcionan :D
##Matriz sin inversa, debe sacar error
arr2 = [[0,0,0],[0,0,0],[0,0,0]]
matriz3 = Matriz(arr2)
print(matriz3)
##funciona
##Iniciar con matriz inversa y cambiar a matriz inversible, debe sacar error
matriz4 = Matriz(arr)
print(matriz4)
matriz4.setMatriz(arr2)
##funciona
'''
#prueba de vectores
'''
x1x2x3 = [1,1,1]
x1x2x3b = [2,3,3]
vector1 = Vector(x1x2x3)
print(vector1)
vector1.setVector(x1x2x3b)
print(vector1)
##funciona
'''
'''
texto = 'texto de prueba'
mensaje = Mensaje(texto)
traductor = Diccionario()
texto2 = list(texto)
traducido = []
for i in texto2:
traducido.append(traductor.traducir(i))
print(traducido)
print(mensaje)
encriptacion = Encriptador()
desencriptacion = Desencriptar()
arr = [[1,2,1],[0,-1,3],[2,1,0]]
print(encriptacion.encriptar(mensaje,arr))
print(mensaje)
print(desencriptacion.desencriptar(mensaje,arr))
print(mensaje)
'''
'''
x = 20.999999999999996
print(round(x,0))
'''
a = [0,0,0,0]
while len(a)%3 != 0:
a.append(0)
print(a) |
# -*- coding: utf-8 -*-
"""
Spyder Editor
Dongyu Zhu
[email protected] term project- A interesting penalty shootout game
"""
from random import choice
score = [0, 0]
rest = [5, 5]
direction = ['left', 'center', 'right']
def kick():
print ('==== You Kick! ====')
print ('Choose one side to shoot:')
print ('left, center, right')
you = input()
print ('You kicked ' + you)
com = choice(direction)
print ('Computer saved ' + com)
if you != com:
print ('Goal!')
score[0] += 1
else:
print ('Oops...')
print ('Score: %d(you) - %d(com)\n' % (score[0], score[1]))
if rest[0] > 0:
rest[0] -= 1
if score[0] < score[1] and score[0] + rest[0] < score[1]:
return True
if score[1] < score[0] and score[1] + rest[1] < score[0]:
return True
print ('==== You Save! ====')
print ('Choose one side to save:')
print ('left, center, right')
you = input()
print ('You saved ' + you)
com = choice(direction)
print ('Computer kicked ' + com)
if you == com:
print ('Saved!')
else:
print ('Oops...')
score[1] += 1
print ('Score: %d(you) - %d(com)\n' % (score[0], score[1]))
if rest[1] > 0:
rest[1] -= 1
if score[0] < score[1] and score[0] + rest[0] < score[1]:
return True
if score[1] < score[0] and score[1] + rest[1] < score[0]:
return True
return False
i = 0
end = False
while(i < 5 and not end):
print ('==== Round %d ====' % (i+1))
end = kick()
i += 1
while(score[0] == score[1]):
print ('==== Round %d ====' % (i+1))
kick()
i += 1
if score[0] > score[1]:
print ('You Win!')
else:
print ('You Lose.')
|
#!/usr/bin/python
class Node:
def __init__( self, value, id, parent_id, position ):
self.id = id
self.parent_id = parent_id
self.value = value
self.position = position # Relative to parent: L - Left, R - Right
self.left = None
self.right = None
def print_node( self ):
return '[' + str(self) + ',' + self.id + ',' + self.parent_id + ',' + self.value + ',' + self.position + ',' + str( self.left ) + ',' + str( self.right ) + ']'
|
name=input("YOUR FULL NAME: ")
for letter in name:
if letter==" ":
break
print (letter)
|
'''
Johnny Dollard
Programming 1
Pygame Lab
'''
import pygame
import sys
from math import pi
pygame.init()
screen = pygame.display.set_mode((640,480))
white = (255,255,255)
screen.fill(white)
yellow = (255,255,0)
orange = (255,69,0)
green = (0, 255, 0)
blue=(0, 0, 255)
red = (255, 0 , 0)
eye1=(180,70,100,70)
eye2=(330,70,100,70)
nose=((300,150),(325,200),(275,200))
mouthArc=((170,150),(250,200))
# draw a smiley face
# draw eyes
pygame.draw.ellipse(screen, green,eye1,3)
pygame.draw.ellipse(screen, green,eye2,3)
# draw a nose
pygame.draw.polygon(screen, red, nose, 5)
# draw a mouth
pygame.draw.arc(screen, orange, mouthArc, pi, 2*pi+0.05, 3)
pygame.draw.line(screen, orange,(170,250),(419,250), 3)
#Do fun extra stuff
pygame.draw.circle(screen, blue, (300, 200), 200, 5)
# update the screen
pygame.display.update()
while (True):
for event in pygame.event.get() :
if ( event.type == pygame.QUIT ):
pygame.quit();
sys.exit();
|
'''
Assignment Number 1
Due Date: 8/29/16
Name: Johnny Dollard
'''
num=int(input("Numerator: "))
den=int(input("Denominator: "))
ans=num/den
print(num,"/",den,"=",ans)
|
def merge_sort(arr, beg, end):
if beg < end:
mid = (beg + end) // 2
merge_sort(arr, beg, mid)
merge_sort(arr, mid + 1, end)
merge(arr, beg, mid + 1, end)
return
def merge(arr, start1, start2, end):
l1 = [i for i in arr[start1:start2]]
l2 = [j for j in arr[start2 : end + 1]]
i = 0
j = 0
curr = start1
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
arr[curr] = l1[i]
i += 1
else:
arr[curr] = l2[j]
j += 1
curr += 1
while i < len(l1):
arr[curr] = l1[i]
curr += 1
i += 1
while j < len(l2):
arr[curr] = l2[j]
curr += 1
j += 1
return
if __name__ == "__main__":
l3 = [2, 8, 7, 1, 3, 5, 6, 4]
print(l3)
merge_sort(l3, 0, 7)
print(l3)
|
people = {
"Alice":{
"phone": 1234,
"addr": "Rockland 23"
},
"Bob":{
"phone": 2344,
"addr": "Kim str 24"
}
}
labels = {
"phone": "phone number",
"addr": "address"
}
name = input("Input the name: \n")
request = input ("Phone number(p) or address(a)?\n")
if request == "p":
key = "phone"
if request == "a":
key = "addr"
if name in people:
print("{}'s {} is {}.".format(name,labels[key],people[name][key]))
|
def celsius_to_farenheit(stopnie):
return (stopnie * 1.8) + 32
def farenheit_to_celsius(stopnie):
return (stopnie - 32) / 1.8
for x in range(-20, 40, 5):
print('Temperatura {celcius}C to {farenheit}F'.format(celcius=x,
farenheit=celsius_to_farenheit(x)))
|
from typing import Union, Sequence
def stairway_path(stairway: Sequence[Union[float, int]]) -> Union[float, int]:
"""
Calculate min cost of getting to the top of stairway if agent can go on next or through one step.
:param stairway: list of ints, where each int is a cost of appropriate step
:return: minimal cost of getting to the top
"""
if len(stairway) == 0:
return None
min_list = []
for i in range(len(stairway)):
if i != 0 and i != 1:
option = stairway[i] + min(min_list[i - 2], min_list[i - 1])
min_list.append(option)
else:
min_list.append(stairway[i])
return min_list[-1]
|
x = 1
while( x < 4):
print("it true")
x=x+1
|
inputs=eval(input("enter the year you were born"))
cal=2019-inputs
if inputs==2016 or inputs==2020:
print("your year was a leap year")
print(cal)
else:
print("your are not a leap year born")
print(cal) |
def even():
for i in range(12,20):
if(i%2==0):
print(i)
even() |
def get_age():
age=input("enter your age")
print("your name is :")
print(age)
def get_name():
name=input("enter your name")
print("your name")
print(name)
def both():
get_age()
get_name()
|
import numpy as np
import pandas as pd
from bokeh.plotting import figure, output_notebook, show
def bokeh_hist(arr, do_log=True, title="A Histogram"):
'''
Always spend 10 mins googling how to bokeh a histogram.
Lets have a quick one!
Inputs:
arr (iterable)
Outputs:
bokeh figure object
'''
bottom = 1e-1 * do_log
hist, edges = np.histogram(arr, bins=50)
p = figure(
title=title,
y_axis_type='log'
)
p.y_range.start = 0.1 * do_log
p.quad(
top=hist, bottom=bottom, left=edges[:-1], right=edges[1:],
fill_color="navy", line_color="white", alpha=0.5
)
return p
|
s=raw_input()
res=""
for i in range(0,len(s)):
if(i==0):
res+=s[i].upper()
elif(s[i-1]==" "):
res += s[i].upper()
# continue
else:
res+=s[i]
print (res) |
# 有偏估计和无偏估计
from playStats.descriptive_stats import mean,variance
import random
import matplotlib.pyplot as plt
def variance_bias(data):
"""方差"""
n = len(data)
mean_value = mean(data)
# 最后除以n或是n-1,有讲究
return sum((e - mean_value) ** 2 for e in data) / n
def sample(num_of_samples,sample_sz,var):
data = []
# data = [random.uniform(0.0,1.0) for _ in range(sample_sz)]
for _ in range(num_of_samples):
data.append(var([random.uniform(0.0,1.0) for _ in range(sample_sz)]))
return data
if __name__ == "__main__":
data1 = sample(1000,40,variance_bias)
plt.hist(data1,rwidth=0.8)
E = mean(data1)
plt.axvline(x=E,c="black")
plt.axvline(x=1/12,c="red") # 均匀分布的方差 = (max - min)**2 / 12
print("bias :",E, 1/12)
plt.show()
data2 = sample(1000,40,variance)
plt.hist(data2,rwidth=0.8)
E = mean(data2)
plt.axvline(x=E,c="black")
plt.axvline(x=1/12,c="red") # 均匀分布的方差 = (max - min)**2 / 12
print("unbias :",E, 1/12)
plt.show() |
import hashlib
import random
from random import randint
chars = '0123456789abcdefghijklmnopqrstuvwxyz' # all possible characters
msg = 'Me gusta el helado'
def random_string(): # generate a random string of random length up to 50
randomLength = randint(1, 50)
randomString = ''.join(random.choice(chars) for i in range(randomLength))
return randomString
def hash_input(user_input): # hashing function, encoding, and subscripting
hashed_input = hashlib.sha256(user_input.encode())
hashed_input = hashed_input.hexdigest() # hashing function that encodes into printable as well as subscripting
hashed_input = hashed_input[:6] # this is 24 bits
return hashed_input
def brute_one_way(message):
hashed_message = hashlib.sha256(message.encode()) # first hashing the given input string
hashed_message = hashed_message.hexdigest()[:6]
print('Message is :', msg)
print('The hashed input reduced to 24 bits is: ', hashed_message) # printing that string and its hash value
done = False
loops = 0
while (done == False): # finding a random generated string that hashes to the same hash value as the given input
loops = loops + 1
randString = random_string()
randHashedString = hash_input(randString)
if (randHashedString == hashed_message): # if so, print
print('Brute forcing one-way property completed:')
print('Found a match!', randString, ' also hashes to ', randHashedString)
print('# of iterations: ', loops)
return None
def brute_collision(): # brute collision here uses 2 randomly generated strings and compares their hash values
done = False
loops = 0
while (done == False):
loops = loops + 1
randomFirst = random_string()
randomSecond = random_string()
randomFirstHashed = hash_input(randomFirst)
randomSecondHashed = hash_input(randomSecond)
if (randomFirstHashed == randomSecondHashed and randomFirst != randomSecond):
print('Brute forcing collision-free property completed:')
print('Found a match!')
print('# of iterations: ', loops)
print(randomFirst, 'and ', randomSecond, ' both hash to ', randomFirstHashed, '!')
return None
brute_one_way(msg)
brute_collision()
|
"""
Custom class to define data structure for a Black Jack hand.
"""
import constants as cn
from num_to_card_converter import convert, value
class Hand(object):
"""
Class containing all relevant methods for a BlackJack Hand.
"""
def __init__(self, deal_size, deck):
"""
Constructor for Hand.
Input: initial deal size, deck being used
"""
self.deal_size = deal_size
self.deck = deck
self.hand_sum = 0
self.hand = self.deal()
def __str__(self):
"""
To String method for Hand Class.
Output: String representation of Hand Class.
"""
return cn.DISPLAY_HAND_MESSAGE + \
[convert(card) + '\n' for card in self.hand] + \
cn.DISPLAY_HAND_SUM + self.hand_sum + '\n'
def _calculate_sum_of_cards(self):
"""
Internal method for calculating the sum of cards in a deck.
Assigns new sum of hand to instance variable hand_sum.
"""
self.hand_sum += value(self.hand[-1])
def _check_choice(self, ace_val):
"""
Internal method for checking if user input is valid for assigning
value of ace to 1 or 11.
Input: user input (string)
Output: valid response (int)
"""
if ace_val == str(cn.ACE_ONE):
return cn.ACE_ONE
elif ace_val == str(cn.ACE_ELEVEN):
return cn.ACE_ELEVEN
return self._check_choice(input(cn.INVALID_ACE_VAL))
def handle_ace(self):
"""
Internal method for handling case an ace is drawn. Prompt user to
select a value for ace, either 1 or 11. By default, the system values
an ace as 11, so if the user specifies 1, then 10 is subtracted from
the hand sum.
"""
if value(self.hand[-1]) == cn.ACE_ELEVEN:
ace_val = input(cn.VALUE_OF_ACE)
ace_val = self._check_choice(ace_val)
if ace_val == cn.ACE_ONE:
self.hand_sum -= cn.TEN_NUM
def hit(self):
"""
Public-facing hit method. Pops card from deck and adds it to hand.
"""
self.hand.append(self.deck.pop())
self._calculate_sum_of_cards()
def deal(self):
"""
Public-facing deal method. Pops initial two cards from deck and adds
them to hand. Calculates initial sum of cards in hand.
Output: hand
"""
self.hand = []
[self.hand.append(self.deck.pop()) for card in
range(cn.INITIAL_DEAL_SIZE)]
for val in self.hand:
self.hand_sum += value(val)
return self.hand
|
# simple Perceptron:
# one input layer and one output layer
# using one hidden layer
# feed-forward and back-propagation steps
from sklearn import datasets
from matplotlib import pyplot as plt
import numpy as np
np.random.seed(0)
feature_set, labels = datasets.make_moons(100, noise=0.10)
plt.figure(figsize=(10,7))
plt.scatter(feature_set[:,0], feature_set[:,1], c=labels, cmap=plt.cm.winter)
labels = labels.reshape(100, 1)
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_der(x):
return sigmoid(x) *(1-sigmoid (x))
wh = np.random.rand(len(feature_set[0]),4)
wo = np.random.rand(4, 1)
lr = 0.5
for epoch in range(200000):
# feedforward
zh = np.dot(feature_set, wh)
ah = sigmoid(zh)
zo = np.dot(ah, wo)
ao = sigmoid(zo)
# Phase1 =======================
error_out = ((1 / 2) * (np.power((ao - labels), 2)))
print(error_out.sum())
dcost_dao = ao - labels
dao_dzo = sigmoid_der(zo)
dzo_dwo = ah
dcost_wo = np.dot(dzo_dwo.T, dcost_dao * dao_dzo)
# Phase 2 =======================
# dcost_w1 = dcost_dah * dah_dzh * dzh_dw1
# dcost_dah = dcost_dzo * dzo_dah
dcost_dzo = dcost_dao * dao_dzo
dzo_dah = wo
dcost_dah = np.dot(dcost_dzo , dzo_dah.T)
dah_dzh = sigmoid_der(zh)
dzh_dwh = feature_set
dcost_wh = np.dot(dzh_dwh.T, dah_dzh * dcost_dah)
# Update Weights ================
wh -= lr * dcost_wh
wo -= lr * dcost_wo |
def outer_func(msg):
message = msg
def inner_func():
print(message)
return inner_func
hi_func = outer_func('Hi')
hello_func = outer_func('Hello')
hi_func()
hello_func()
print ([n**2 for n in range(10) if n%2])
lst = [-1, 1, -2, 20, -30, 10]
lsta = [x[1] for x in sorted([(abs(x),x) for x in lst])]
print lsta
#print(sort(lst, key=abs))
print "a".endswith("") |
print "Some Math here"
print "8%4: ", 8 % 4
print "8/4: ", 8 / 4
print "8*4: ", 8*4
print "8+4: ", 8+4
print "8-4: ", 8-4
print "56/13: ", 56/13
print "Notice that the last answer is in whole numbers. That is, the result is automatically floored. We need to use floating point numbers (i.e. with decimal points) to get these answers in floating point representation."
print "Let us see"
print "56.0/13.0: ", 56.0/13.0
print "Hooray!"
print "What is integer division or floor division?"
print "// is used for floor division which works in floats too."
print "56.0//13.0: ", 56.0//13.0
print "In all python version floor division remains same but normal division is different. Python 2.x versions will make 2/3 = 0 while 3.x versions will give the result as 0.6666."
print "If you want Py 2.x to behave like 3.x, just perform a from __future__ import division (with double underscores and spaces between from and import) and should occur at the beginning of the file like I have done in the next file named FromFutureImport.py"
|
def apple():
print "I AM APPLES!"
# this is just a variable
tangerine = "Living reflection of a dream"
def addition():
x = int(raw_input("Please enter the first number to be added: "))
y = int(raw_input("Please enter the second number to be added: "))
#return x+y
z = x+y
return z
|
#lyrics = "Hey you"
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
#print lyrics # Doesn't print hey you..?
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around tha family",
"With pockets full of shells"])
new_song = ["You see her when you fall asleep", "But never to touch and never to keep"]
create_new_song_object = Song(new_song)
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
create_new_song_object.sing_me_a_song()
|
# Three ways to call things
# dict style
mystuff = {"apples": "Here are apples!"}
print mystuff['apples']
# module style
'''
In some module mystuff:
def apple():
print "I AM APPLES!"
# this is just a variable
tangerine = "Living reflection of a dream"
'''
#import the file
#mystuff.apples()
#print mystuff.tangerine
# class style
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I AM CLASSY APPLES!"
thing = MyStuff()
thing.apple()
print thing.tangerine
|
# 1238765 = 1+2+3+8+7+6+5 = x
n = int(input("Enter the number: "))
sum = 0
while n!=0:
digit = n % 10
sum += digit
n = n // 10
print(sum) |
a = 4
b = 5
temp = 0
print("before :")
print(a)
print(b)
temp = a
a = b
b = temp
print("After: ")
print(a)
print(b)
|
from hashTable import HashTable
import unittest
class HashTableTest(unittest.TestCase):
def test_init(self):
ht = HashTable(4)
assert len(ht.buckets) == 4
assert ht.length() == 0
def test_length(self):
ht = HashTable()
assert ht.length() == 0
ht.set('I', 1)
assert ht.length() == 1
ht.set('V', 5)
assert ht.length() == 2
ht.set('X', 10)
assert ht.length() == 3
def test_set_and_get(self):
ht = HashTable()
ht.set('I', 1)
ht.set('V', 5)
ht.set('X', 10)
assert ht.get('I') == 1
assert ht.get('V') == 5
assert ht.get('X') == 10
assert ht.length() == 3
with self.assertRaises(KeyError):
ht.get('A') # Key does not exist
def test_delete(self):
ht = HashTable()
ht.set('I', 1)
ht.set('V', 5)
ht.set('X', 10)
assert ht.length() == 3
ht.delete('I')
ht.delete('X')
assert ht.length() == 1
with self.assertRaises(KeyError):
ht.delete('X') # Key no longer exists
with self.assertRaises(KeyError):
ht.delete('A') # Key does not exist
if __name__ == '__main__':
unittest.main()
|
weight = input("What is your weight? ")
height = input("What is your height? ")
BMI = 703*(int(weight)/int(height)**2)
print("Your BMI is "+ str(BMI) + ".")
if ((BMI) <= 18):
print ("You are underweight.")
elif(((BMI) > 18) and ((BMI) < 26)):
print ("Your weight is normal.")
else:
print ("You are overwight.") |
print("-----------------------------\n"
"------Assignment part 2------\n"
"-----------------------------\n")
print("===You have 3 tries===\n"
"------Be careful------")
print("Iftiaj Alom")
print("1001956795")
import sys
count = 0
while count <3: #count number of tries
option = input("Enter an Arithmethic Operation: ")
print(option)
#check for invalid Operations
if "++" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "--" in option and "+" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "--" in option and "*" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "--" in option and "/" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "**" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "//" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "+*" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "+/" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "-/" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "*/" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "-+" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "/*" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "a" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "b" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "ab" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "k" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "z" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "x" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "c" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "v" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "s" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "d" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "f" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "h" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "j" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "q" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "w" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "e" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "r" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "t" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "y" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "u" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "i" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "o" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "p" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "l" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "n" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
elif "m" in option:
print("Invalid Arithmethic Operation. Please try again.")
count += 1
continue
else:
break
if count == 3:
print(" Your 3 tries are over. The program Terminated.")
sys.exit()
else:
pass
option= option.replace(" ", "") # remove spaces
w=option.split('+') # indentify a and b regardless their position
x= option.split('-')
y=option.split('*')
z=option.split('/')
if "+" in option: #check for + Operation
a = int(w[0])
b = int(w[1])
result = a + b
print("The result is = " + str(result))
elif "*" in option: #check for * Operation
a = int(y[0])
b = int(y[1])
result = a * b
print("The result is = " + str(result))
elif "/" in option: #check for / Operation
a= int(z[0])
b= int(z[1])
result = a / b
result =round(result,3)
print("The result is = " + str(result))
elif "--" in option and len(x)==3: #check for - sign and a is positve
a= int(x[0])
b= int(x[2])
result = a -- b
print("The result is = ", result)
elif "-" in option and len(x) == 3: #check for - sign and a is negative
a = int(x[1])
b = int(x[2])
result = a + b
result = result * (-1)
print("The result is = ", result)
elif "-" in option and len(x)==2: #check for - sign and a is positve
a= int(x[0])
b= int(x[1])
result = a - b
print("The result is = ", result)
elif "-" in option and len(x) == 4:
a = int(x[1])
b = int(x[3])
result = -a -- b
print("The result is = ", result)
else:
count = 3 |
if x == 3:
print("Hey!")
elif x > 5:
if x < 20:
print("Haha")
else:
print("Wow")
else:
print("No!")
|
from abc import ABC
from typing import Any
class Operator(ABC):
"""
Abstract class for operators, you can create custome operators using it.
"""
pointers = []
"""A list of chars that point to the operator
"""
members = []
"""Members which operation gose over them
"""
require_member = 0
"""Least require member for the operation
"""
name = ''
about = ''
def __init__(self) -> None:
if not self.pointers:
raise ValueError('pointers required!')
if self.require_member < 1:
raise ValueError('require_member Should be more that 0')
def calculate(self) -> Any:
"""Main func to calculate the result
"""
pass
def add_members(self, members = []):
"""Add members to attribute (Not important if field is public)"""
self.members = members
def check_members(self):
"""Members should be valid!
"""
if self.members.__len__() < self.require_member:
raise TypeError(f"Need at least {self.require_member} members")
for x in self.members:
if not (isinstance(x, int) or isinstance(x, float)):
raise TypeError("Only int and float!")
return True
def set_members(self, index, text):
""" The fun that find member on text using operator index
Retuns the starting and ending index of whole operation
"""
member1 = eval(text[index - 1])
member2 = eval(text[index + 1])
self.add_members([member1, member2])
return index - 1, index + 1
def __str__(self) -> str:
return f'Operator {self.name} ( {self.about} )'
class GroupingOperator(Operator):
def __init__(self) -> None:
super().__init__()
|
def addition(a,b):
if type(a) and type(b) == (str): #or type(a) and type(b) == (int) or type(a) and type(b) == (int):
print (a+b)
else:
print "error"
addition(str(3),5)
#addition(0,4)
|
# 创建一个列表,其中包含数字1~1000000,再使用min()和max()核实该列表确实是从1开始,到1000000结束的。
# 另外,对这个列表调用函数sum(),看看Python将一百万个数字相加需要多长时间
numbers = list(range(1, 1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers)) |
class User1():
def __init__(self,first_name,last_name,*info):
self.first_name=first_name
self.last_name=last_name
self.info=info
def describe_user(self):
print(self.last_name+" "+self.first_name+" has these info:")
for i in self.info:
print(i)
def greet_user(self):
print("Hi,"+self.last_name+" "+self.first_name)
|
# 6-9 喜欢的地方:
# 创建一个名为favorite_places的字典。
# 在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。
# 为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。
# 遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_place = {
'Tom': ['London', 'Liverpool'],
'Jerry': ['NewYork','Liverpool'],
'David':['London','NewYork']
}
for key, value in favorite_place.items():
print(key + '\'s favorite place are:')
for place in value:
print(place)
print('\n') |
# 如果你可以邀请任何人一起共进晚餐(无论是在世的还是故去的),你会邀请哪些人?
# 请创建一个列表,其中包含至少3个你想邀请的人;然后,使用这个列表打印消息,邀请这些人来与你共进晚餐。
dinner_friend = ['bai', 'ye', 'xie', 'zhu']
print("Hi,"+dinner_friend[0]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[1]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[2]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[3]+",I want to have a dinner with you")
# 修改嘉宾名单:你刚得知有位嘉宾无法赴约,因此需要另外邀请一位嘉宾。
# ·以完成练习3-4时编写的程序为基础,在程序末尾添加一条print语句,指出哪位嘉宾无法赴约。
# ·修改嘉宾名单,将无法赴约的嘉宾的姓名替换为新邀请的嘉宾的姓名。
# ·再次打印一系列消息,向名单中的每位嘉宾发出邀请。
print("\n\nI am zhu,i am sorry for that i have no time")
dinner_friend[3] = "zhang"
print("Hi,"+dinner_friend[0]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[1]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[2]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[3]+",I want to have a dinner with you")
#完成练习3-4~练习3-7时编写的程序之一中,使用len()打印一条消息,指出你邀请了多少位嘉宾来与你共进晚餐。
print(len(dinner_friend))
# 你刚找到了一个更大的餐桌,可容纳更多的嘉宾。请想想你还想邀请哪三位嘉宾。
# ·以完成练习3-4或练习3-5时编写的程序为基础,在程序末尾添加一条print语句,指出你找到了一个更大的餐桌。
# ·使用insert()将一位新嘉宾添加到名单开头。
# ·使用insert()将另一位新嘉宾添加到名单中间。
# ·使用append()将最后一位新嘉宾添加到名单末尾。
# ·打印一系列消息,向名单中的每位嘉宾发出邀请
print("\n\nI found a bigger dinner rom")
dinner_friend.insert(0, "li")
dinner_friend.insert(3, "huang")
dinner_friend.append("huang")
print("Hi,"+dinner_friend[0]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[1]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[2]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[3]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[4]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[5]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[6]+",I want to have a dinner with you")
# 缩减名单:你刚得知新购买的餐桌无法及时送达,因此只能邀请两位嘉宾。
# ·以完成练习3-6时编写的程序为基础,在程序末尾添加一行代码,打印一条你只能邀请两位嘉宾共进晚餐的消息。
# ·使用pop()不断地删除名单中的嘉宾,直到只有两位嘉宾为止。每次从名单中弹出一位嘉宾时,都打印一条消息,让该嘉宾知悉你很抱歉,无法邀请他来共进晚餐。
# ·对于余下的两位嘉宾中的每一位,都打印一条消息,指出他依然在受邀人之列。
# ·使用del将最后两位嘉宾从名单中删除,让名单变成空的。打印该名单,核实程序结束时名单确实是空的。
print("I am sorry for that I have remove")
removed = dinner_friend.pop()
print(removed, ",i am so sorry")
removed = dinner_friend.pop()
print(removed, ",i am so sorry")
removed = dinner_friend.pop()
print(removed, ",i am so sorry")
removed = dinner_friend.pop()
print(removed, ",i am so sorry")
removed = dinner_friend.pop()
print(removed, ",i am so sorry")
print(dinner_friend[0])
print(dinner_friend[1])
del dinner_friend[0]
del dinner_friend[0]
print(dinner_friend)
|
# 8-12 三明治:
# 编写一个函数,它接受顾客要在三明治中添加的一系列食材。
# 这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。
# 调用这个函数三次,每次都提供不同数量的实参。
def addtopping(*toppings):
print('You add topping fllow these:')
for topping in toppings:
print(topping)
addtopping('mushrooms','ham')
addtopping('egg') |
# 通过给函数range()指定第三个参数来创建一个列表,其中包含1~20的奇数;再使用一个for循环将这些数字都打印出来
for value in range(1, 20, 2):
print(value)
|
# 编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果都打印出来
# 对于下面列出的各种测试,至少编写一个结果为True和False的测试。
# ·检查两个字符串相等和不等。
# ·使用函数lower()的测试。
# ·检查两个数字相等、不等、大于、小于、大于等于和小于等于。
# ·使用关键字and和or的测试。·测试特定的值是否包含在列表中。
# ·测试特定的值是否未包含在列表中。
car1 = 'audi'
car2 = 'toyota'
car3 = 'audi'
car4 = 'Audi'
print('Is car1==car2,I guess False')
print(car1 == car2)
print("\nIs car1==car3,I guess True")
print(car1 == car3)
#下列省略猜测输出语句,仅注释并输出结果
#True
print(car1 == car4.lower())
#False
print(2 == 3)
#True
print(2 < 3)
#False
print(2 >= 3)
#True
print(2 <= 3)
#False
print(car1 == car2 and car1 == car3)
#True
print(car1 == car2 or car1 == car3)
#False
cars = ['audi', 'toyota', 'bmw']
print('suzuki' in cars)
#True
print('suzuki' not in cars) |
#6-2 喜欢的数字:使用一个字典来存储一些人喜欢的数字。
# 请想出5个人的名字,并将这些名字用作字典中的键;
# 想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。
# 打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
favorite_number = {'Li': 16, 'zhang': 1, 'wang': 2, 'zhu': 3, 'bai': 4}
print('Li,is ' + str(favorite_number['Li']) + ' your favorite_number')
print('zhang,is ' + str(favorite_number['zhang']) + ' your favorite_number')
print('wang,is ' + str(favorite_number['wang']) + ' your favorite_number')
print('zhu,is ' + str(favorite_number['zhu'])+ ' your favorite_number')
print('bai,is ' + str(favorite_number['bai']) + ' your favorite_number') |
# 10-9 沉默的猫和狗:
# 修改你在练习10-8中编写的except代码块,让程序在文件不存在时一言不发。
try:
with open('cats.txt') as file_object:
print(file_object.read())
except FileNotFoundError:
pass
try:
with open('../dogs.txt') as file_object:
print(file_object.read())
except FileNotFoundError:
pass
|
# 继续使用练习3-1中的列表,但不打印每个朋友的姓名,而为每人打印一条消息。每条消息都包含相同的问候语,但抬头为相应朋友的姓名
names = ["bai", "zhu", "ye", "zhang"]
print("Hello,my good friend "+names[0])
print("Hello,my good friend "+names[1])
print("Hello,my good friend "+names[2])
print("Hello,my good friend "+names[3])
|
# 9-5 尝试登录次数:
# 在为完成练习9-3而编写的User类中,添加一个名为login_attempts的属性。
# 编写一个名为increment_login_attempts()的方法,它将属性login_attempts的值加1。
# 再编写一个名为reset_login_attempts()的方法,它将属性login_attempts的值重置为0。
# 根据User类创建一个实例,再调用方法increment_login_attempts()多次。
# 打印属性login_attempts的值,确认它被正确地递增;
# 然后,调用方法reset_login_attempts(),并再次打印属性login_attempts的值,确认它被重置为0。
class User():
def __init__(self,first_name,last_name,*info):
self.first_name=first_name
self.last_name=last_name
self.info=info
self.login_attempts=0
def describe_user(self):
print(self.last_name+" "+self.first_name+" has these info:")
for i in self.info:
print(i)
def greet_user(self):
print("Hi,"+self.last_name+" "+self.first_name)
def increment_login_attempts(self):
self.login_attempts+=1
def reset_login_attempts(self):
self.login_attempts=0
user=User("Vardy","Jim")
for i in range(1,9):
user.increment_login_attempts()
print(user.login_attempts)
user.reset_login_attempts()
print(user.login_attempts) |
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
class Stack():
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None
def size(self):
return len(self.stack)
def earliest_ancestor(ancestors, starting_node):
ancestor_data = {}
# organizing data into graph
for parentChild in ancestors:
parent = parentChild[0]
child = parentChild[1]
# if parent has more than one child
if parent in ancestor_data.keys():
ancestor_data[parent].append(child)
else:
ancestor_data[parent] = [child]
# store possible paths in array
paths = []
# longest path (dfs) for earliest ancestor, starts at the root node and explores as far as possible along each branch before backtracking
s = Stack()
s.push([starting_node])
visited = []
# checking that current vertex is not == to destination vertex
while s.size() > 0:
path = s.pop()
current = path[-1]
if current not in visited:
visited.append(current)
parents_current = []
# looking for parents we append
for parent in ancestor_data:
if current in ancestor_data[parent]:
parents_current.append(parent)
# if no parents that's the end of the path
if len(parents_current) == 0:
# store into paths
paths.append(path)
else:
# if parents add to stack
for parent in parents_current:
new_path = list(path)
new_path.append(parent)
s.push(new_path)
# dfs for all possible paths so now sort to longest one
paths = sorted(paths)
longest_path = paths[0]
earliest = longest_path[-1]
if earliest == starting_node:
return -1
else:
return earliest
testing = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]
print(earliest_ancestor(testing, 9)) |
#AMM Tail Animator - amm_ta
#Purpose: To give characters without tail animations tail animations
import struct
import math
import os
def bsk_type():
#Let's the user select bin type
print("Main BSK (Large in size with AMMs) or Special BSK (Small in size w/o AMMs)?(M/S):")
b_type = input("")
if b_type == "M" or b_type == "m":
main()
elif b_type == "S" or b_type == "s":
special()
else:
print("Please type 'M' or 'S'!")
bsk_type()
def main():
# opens BSK
print("BSK name (with extension):")
x = input("")
x = x.replace("\"", "")
f = open(x, "r+b")
print("Which tail animation would you like to use?")
print("SSJ4, Cell, Frieza, Cooler?(S/C/F/CO)")
tail_type = input("")
tail_type = tail_type.lower()
if tail_type == "s" or tail_type == "ssj4":
# Copying files needed
bin_copy = f.read()
amm = open("Files\Tail_SSJ4.bin", "r+b")
amm_copy = amm.read()
# Setting up temp bins
tn1 = "Files\z.bin" # Will hold edited bin
temp1 = open(tn1, "w+b")
temp1.write(bin_copy)
temp1.close()
temp1 = open(tn1, "r+b")
tn2 = "Files\z2.bin" # Will hold tail AMM
temp2 = open(tn2, "w+b")
temp2.write(amm_copy)
temp2.close()
temp2 = open(tn2, "r+b")
# Changes the size of the 3rd AMM in the AMB of the MAIN BSK bin
temp1.seek(84)
temp1.write(b'\x50\xF1\x02\x00')
# Goes to 3rd AMM
temp1.seek(80)
offset = temp1.read(4)
print("bytes: " + str(offset))
offset = offset.hex()
print("hex(LE): " + str(offset))
offset = int(offset, 16)
print("dec: " + str(offset))
offset = struct.pack('<L', offset)
print("bytes(BE): " + str(offset))
offset = offset.hex()
print("hex(BE): " + str(offset))
offset = int(offset, 16)
print("dec: " + str(offset))
print("")
# Paste over old AMM with new AMM
temp1.seek(offset)
t_copy = temp2.read()
temp1.write(t_copy)
# Deletes extra bytes at the bottom of the bin
temp1.seek(84)
offset2 = temp1.read(4)
print("bytes: " + str(offset2))
offset2 = offset2.hex()
print("hex(LE): " + str(offset2))
offset2 = int(offset2, 16)
print("dec: " + str(offset2))
offset2 = struct.pack('<L', offset2)
print("bytes(BE): " + str(offset2))
offset2 = offset2.hex()
print("hex(BE): " + str(offset))
offset2 = int(offset2, 16) + offset
print("dec: " + str(offset2))
print("")
# Paste over old AMM with new AMM
temp1.seek(0)
t_copy = temp1.read(offset2)
tn3 = "Files\z3.bin"
temp3 = open(tn3, "w+b")
temp3.write(t_copy)
if tail_type == "c" or tail_type == "cell":
# Copying files needed
bin_copy = f.read()
amm = open("Files\Tail_Cell.bin", "r+b")
amm_copy = amm.read()
# Setting up temp bins
tn1 = "Files\z.bin" # Will hold edited bin
temp1 = open(tn1, "w+b")
temp1.write(bin_copy)
temp1.close()
temp1 = open(tn1, "r+b")
tn2 = "Files\z2.bin" # Will hold tail AMM
temp2 = open(tn2, "w+b")
temp2.write(amm_copy)
temp2.close()
temp2 = open(tn2, "r+b")
# Changes the size of the 3rd AMM in the AMB of the MAIN BSK bin
temp1.seek(84)
temp1.write(b'\xE4\xF2\x02\x00')
# Goes to 3rd AMM
temp1.seek(80)
offset = temp1.read(4)
print("bytes: " + str(offset))
offset = offset.hex()
print("hex(LE): " + str(offset))
offset = int(offset, 16)
print("dec: " + str(offset))
offset = struct.pack('<L', offset)
print("bytes(BE): " + str(offset))
offset = offset.hex()
print("hex(BE): " + str(offset))
offset = int(offset, 16)
print("dec: " + str(offset))
print("")
# Paste over old AMM with new AMM
temp1.seek(offset)
t_copy = temp2.read()
temp1.write(t_copy)
# Deletes extra bytes at the bottom of the bin
temp1.seek(84)
offset2 = temp1.read(4)
print("bytes: " + str(offset2))
offset2 = offset2.hex()
print("hex(LE): " + str(offset2))
offset2 = int(offset2, 16)
print("dec: " + str(offset2))
offset2 = struct.pack('<L', offset2)
print("bytes(BE): " + str(offset2))
offset2 = offset2.hex()
print("hex(BE): " + str(offset))
offset2 = int(offset2, 16)+offset
print("dec: " + str(offset2))
print("")
# Paste over old AMM with new AMM
temp1.seek(0)
t_copy = temp1.read(offset2)
tn3 = "Files\z3.bin"
temp3 = open(tn3, "w+b")
temp3.write(t_copy)
if tail_type == "f" or tail_type == "frieza":
# Copying files needed
bin_copy = f.read()
amm = open("Files\Tail_Frieza.bin", "r+b")
amm_copy = amm.read()
# Setting up temp bins
tn1 = "Files\z.bin" # Will hold edited bin
temp1 = open(tn1, "w+b")
temp1.write(bin_copy)
temp1.close()
temp1 = open(tn1, "r+b")
tn2 = "Files\z2.bin" # Will hold tail AMM
temp2 = open(tn2, "w+b")
temp2.write(amm_copy)
temp2.close()
temp2 = open(tn2, "r+b")
# Changes the size of the 3rd AMM in the AMB of the MAIN BSK bin
temp1.seek(84)
temp1.write(b'\x88\xF8\x02\x00')
# Goes to 3rd AMM
temp1.seek(80)
offset = temp1.read(4)
print("bytes: " + str(offset))
offset = offset.hex()
print("hex(LE): " + str(offset))
offset = int(offset, 16)
print("dec: " + str(offset))
offset = struct.pack('<L', offset)
print("bytes(BE): " + str(offset))
offset = offset.hex()
print("hex(BE): " + str(offset))
offset = int(offset, 16)
print("dec: " + str(offset))
print("")
# Paste over old AMM with new AMM
temp1.seek(offset)
t_copy = temp2.read()
temp1.write(t_copy)
# Deletes extra bytes at the bottom of the bin
temp1.seek(84)
offset2 = temp1.read(4)
print("bytes: " + str(offset2))
offset2 = offset2.hex()
print("hex(LE): " + str(offset2))
offset2 = int(offset2, 16)
print("dec: " + str(offset2))
offset2 = struct.pack('<L', offset2)
print("bytes(BE): " + str(offset2))
offset2 = offset2.hex()
print("hex(BE): " + str(offset))
offset2 = int(offset2, 16)+offset
print("dec: " + str(offset2))
print("")
# Paste over old AMM with new AMM
temp1.seek(0)
t_copy = temp1.read(offset2)
tn3 = "Files\z3.bin"
temp3 = open(tn3, "w+b")
temp3.write(t_copy)
if tail_type == "co" or tail_type == "cooler":
# Copying files needed
bin_copy = f.read()
amm = open("Files\Tail_Cooler.bin", "r+b")
amm_copy = amm.read()
# Setting up temp bins
tn1 = "Files\z.bin" # Will hold edited bin
temp1 = open(tn1, "w+b")
temp1.write(bin_copy)
temp1.close()
temp1 = open(tn1, "r+b")
tn2 = "Files\z2.bin" # Will hold tail AMM
temp2 = open(tn2, "w+b")
temp2.write(amm_copy)
temp2.close()
temp2 = open(tn2, "r+b")
# Changes the size of the 3rd AMM in the AMB of the MAIN BSK bin
temp1.seek(84)
temp1.write(b'\x20\xA0\x02\x00')
# Goes to 3rd AMM
temp1.seek(80)
offset = temp1.read(4)
print("bytes: " + str(offset))
offset = offset.hex()
print("hex(LE): " + str(offset))
offset = int(offset, 16)
print("dec: " + str(offset))
offset = struct.pack('<L', offset)
print("bytes(BE): " + str(offset))
offset = offset.hex()
print("hex(BE): " + str(offset))
offset = int(offset, 16)
print("dec: " + str(offset))
print("")
# Paste over old AMM with new AMM
temp1.seek(offset)
t_copy = temp2.read()
temp1.write(t_copy)
# Deletes extra bytes at the bottom of the bin
temp1.seek(84)
offset2 = temp1.read(4)
print("bytes: " + str(offset2))
offset2 = offset2.hex()
print("hex(LE): " + str(offset2))
offset2 = int(offset2, 16)
print("dec: " + str(offset2))
offset2 = struct.pack('<L', offset2)
print("bytes(BE): " + str(offset2))
offset2 = offset2.hex()
print("hex(BE): " + str(offset))
offset2 = int(offset2, 16)+offset
print("dec: " + str(offset2))
print("")
# Paste over old AMM with new AMM
temp1.seek(0)
t_copy = temp1.read(offset2)
tn3 = "Files\z3.bin"
temp3 = open(tn3, "w+b")
temp3.write(t_copy)
# replacing old bytes with new ones
temp3.close()
temp3 = open(tn3, "r+b")
t_copy = temp3.read()
old_b = b'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'
new_b = b'\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF'
t_copy = t_copy.replace(old_b, new_b)
temp3.close
temp3 = open(tn3, "r+b")
temp3.write(t_copy)
# Saves it to your file
temp3.close()
temp3 = open(tn3, "r+b")
t_copy = temp3.read(offset2)
f.close()
temp1.close()
temp2.close()
temp3.close()
os.remove(x)
f = open(x, "w+b")
f.write(t_copy)
f.close()
print("")
print("Completed!")
# deletes temp files
tn1 = "Files\z.bin"
temp1 = open(tn1, "r+b")
temp1.close()
tn2 = "Files\z2.bin"
temp2 = open(tn2, "r+b")
temp2.close()
tn3 = "Files\z3.bin"
temp3 = open(tn3, "r+b")
temp3.close()
os.remove(tn1)
os.remove(tn2)
os.remove(tn3)
def special():
# opens BSK
print("BSK name (with extension):")
x = input("")
f = open(x, "r+b")
chunk = f.read()
# replacing old bytes with new ones
old_b = b'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'
new_b = b'\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF'
chunk = chunk.replace(old_b, new_b)
f.close
f = open(x, "r+b")
f.seek(0)
f.write(chunk)
print("Completed!")
#closes bin
f.close()
def again():
yn = input("Load another? (Y/N)")
if yn == "Y" or yn == "y" or yn == "Yes" or yn == "yes":
bsk_type()
again()
else:
print("Tail AMM replacer by: Nexus-sama")
print("Follow me on Twitter @NexusTheModder")
kill = input("press enter to close")
bsk_type()
again()
exit()
|
import re
import os
# text file to open
file=os.path.join("raw_data","paragraph_1.txt")
# Open txt file
with open(file,'r',encoding="UTF-8") as text:
print(text)
# assigning as an object of text.read class
lines=text.read()
# Counting Words
words=lines.split()
no_of_words=len(words)
# Counting no of periods for sentence count
no_of_sent=lines.count('.')
# Average Letter Count
lettercount=0
for word in words:
lettercount+=len(word)
av_letter_count=lettercount/no_of_words
# Average Sentence Length
av_sent_len=no_of_words/no_of_sent
# printing paragraph analysis
print(f'Paragraph Analysis')
print("-"*40)
print(f"Approximate Word Count: {no_of_words}")
print(f'Approximate Sentence Count: {no_of_sent}')
print(f'Average Letter Count: {av_letter_count}')
print(f'Average Sentence Length: {av_sent_len}') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.