text
stringlengths 37
1.41M
|
---|
words =[]
with open('filtered_words.txt','r+',encoding='utf8') as f:
for i in f.readlines():
if i[-1]=='\n':
i = i[:-1]
words.append(i)
input_key = input('请输入词')
if input_key in words:
print('Freedom')
else:
print('Human Rights') |
# /usr/local/bin/python
# encoding definition
"""coding=utf-8"""
# import packages
from colorama import Fore, Back, Style
# area function definition
def getArea(userLength, userHeight):
return userLength * userHeight
# perimeter function definition
def getPerimeter(userLength, userHeight):
return (userLength + userHeight) * 2
# draw function definition
def draw(userLength, userHeight):
tbRow = '--' * userLength
# bCol = tbRow[ :2]
bCol = '| '
mRow = ' ' * (userLength - 2)
# eCol = tbRow[-2: ]
eCol = ' |'
i = 0
h = userHeight - 2
if userLength == userHeight:
print(Back.GREEN + tbRow + Back.RESET)
while i < h:
print(Back.GREEN + bCol + Back.RESET + mRow + Back.GREEN + eCol + Back.RESET)
i += 1
print(Back.GREEN + tbRow + Back.RESET)
else:
print(Back.CYAN + tbRow + Back.RESET)
while i < h:
print(Back.CYAN + bCol + Back.RESET + mRow + Back.CYAN + eCol + Back.RESET)
i += 1
print(Back.CYAN + tbRow + Back.RESET)
return ''
# input loop
while True:
# script description
print(Fore.RED + '\n===============================================' + Fore.YELLOW + 'v1.5.170311' + Fore.RESET)
print(Fore.CYAN + 'This Python2/Python3 script will draw and calculate the\narea and perimeter of a rectangle and them will draw and\ncalculate the area and perimeter of a square using the\nfollowing inputs...' + Style.DIM + Fore.WHITE + '\n(For exit, enter 0 in any of the inputs.)' + Fore.RESET + Style.RESET_ALL)
print(Fore.BLUE + '----------------------------------------------------------' + Fore.RESET)
# user input prompt and evaluation
try:
userLength = int(input(Fore.YELLOW + 'Enter a LENGTH value for the Rectangle: ' + Fore.RESET))
userHeight = int(input(Fore.YELLOW + 'Enter a HEIGHT value for the Rectangle: ' + Fore.RESET))
except Exception:
print('\n' + Back.RED + ' *** INPUT ERROR *** ' + Back.RESET + '\n' + Back.RED + ' Input value of Length and Height should be a Number. ' + Back.RESET)
continue
print(Fore.RED + '==========================================================\n' + Fore.RESET)
# user input evaluation
if userLength == 0 or userHeight == 0:
print(Back.MAGENTA + '-----------------' + Back.RESET)
print(Back.MAGENTA + '|' + Back.RESET + Style.BRIGHT + ' Good Bye!!! ' + Style.RESET_ALL + Back.MAGENTA + '|' + Back.RESET)
print(Back.MAGENTA + '-----------------' + Back.RESET + '\n')
break
elif userLength < 3 or userHeight < 3:
print(Back.RED + ' *** INPUT ERROR *** ' + Back.RESET + '\n' + Back.RED + ' Input value of Length and Height should not be less than 3 units. ' + Back.RESET)
else:
# rectangle outputs
draw(userLength, userHeight)
print('\n' + Style.BRIGHT + Fore.YELLOW + 'Rectangle total area is ' + Fore.WHITE + str(getArea(userLength, userHeight)) + Fore.RESET + Fore.YELLOW + ' sq. units.')
print('Rectangle perimeter length is ' + Fore.WHITE + str(getPerimeter(userLength, userHeight)) + Fore.RESET + Fore.YELLOW + ' units.\n' + Style.RESET_ALL)
# determine square sides length
sqrSide = int(getPerimeter(userLength, userHeight) / 4)
# square outputs
draw(sqrSide, sqrSide)
print('\n' + Style.BRIGHT + Fore.YELLOW + 'Square total area is ' + Fore.WHITE + str(getArea(sqrSide, sqrSide)) + Fore.RESET + Fore.YELLOW + ' sq. units.')
print('Square perimeter length is ' + Fore.WHITE + str(getPerimeter(sqrSide, sqrSide)) + Fore.RESET + Fore.YELLOW + ' units.\n' + Style.RESET_ALL)
break
|
import tkinter
import os
import urllib.request
mainWindow = None
packer = []
#An option class which contains a box which text can be put in and the label to describe the box
class Option:
def __init__(self, label, box):
self.label = label
self.box = box
#Sets the window in which the labels, buttons, etc. are created in
def setMainWindow(panel):
mainWindow = panel
#Adds a thingy to the packer, such as: labels, entries, and buttons
def addToPacker(o):
packer.append(o)
#Creates and returns a label
def createLabel(txt):
label = tkinter.Label(mainWindow, text=txt)
addToPacker(label)
return label
#Creates a label with a specific font and returns a label
def createLabelWithFont(fnt, txt):
label = tkinter.Label(mainWindow, text=txt, font=fnt)
addToPacker(label)
return label
#Creates and returns a button
def createButton(txt, cmd):
button = tkinter.Button(mainWindow, text=txt, command=cmd)
addToPacker(button)
return button
#Creates and returns an entry
def createBox():
box = tkinter.Entry(mainWindow)
addToPacker(box)
return box
#Creates and returns an option; check the class for more info
def createOption(txt):
return Option(createLabel(txt), createBox());
#Packs all of the different things placed in the packer in the order that they were put in the packer
def packAll():
for box in packer:
box.pack() |
# -*- coding: utf-8 -*-
import sqlite3
def insert_data(values):
with sqlite3.connect("database.db") as db:
cursor = db.cursor()
sql = "INSERT INTO Product (Name, Price) VALUES (?,?)"
cursor.execute(sql,values)
db.commit()
if __name__ == "__main__":
product = ("Americano", 1.50)
insert_data(product) |
#Create an empty set
s = set()
#Add elements to the set
s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3)
#print out the set
print(s)
#Remove element in a set
s.remove(2)
#Print after deleting an element
print(s)
#Print how many elements are there in a set
print(f"The set has {len(s)} elements") |
import sympy as sym
import matplotlib.pyplot as plt
a=[]
b=[]
c=[]
i=-20
def f(x):
return x**2-5*x-6
for i in range (-20,21):
x=i
f1 = 2*x - 5
tol = x
y = x - (f(x)/f1)
count = 0
#print(i)
while(abs(tol)>10**(-5)):
y = x - (f(x)/f1)
#print(y)
tol = y - x
x=y
count+=1
#print("y:",y)
if(abs(y) > 10**2):
print("y is too big for i=",i)
break
if(count == 100):
print('no output or input',i)
break
#else:
# i = i + 1
#print("y:",y)
#print("i:",i)
print("for i is ", i, " The Root is ", y , "Total iteration",count)
a.append(i)
b.append(y)
c.append(count)
plt.plot(a,b)
plt.show()
plt.plot(a,c)
plt.show()
|
f = open("./3-input.txt", "r")
lines = f.readlines()
wire_1 = lines[0].split(",")
wire_2 = lines[1].split(",")
# wire_1 = "R8,U5,L5,D3".split(",")
# wire_2 = "U7,R6,D4,L4".split(",")
def manhattan_distance(x, y):
return sum(abs(a-b) for a, b in zip(x, y))
path = {}
last_coordinate = [0, 0]
steps_offset = 0
for command in wire_1:
c = command[0]
steps = int(command[1:])
for step in range(1, steps + 1):
if c == "R":
last_coordinate = [last_coordinate[0] + 1, last_coordinate[1]]
elif c == "L":
last_coordinate = [last_coordinate[0] - 1, last_coordinate[1]]
elif c == "U":
last_coordinate = [last_coordinate[0], last_coordinate[1] + 1]
else:
last_coordinate = [last_coordinate[0], last_coordinate[1] - 1]
# print(last_coordinate, c)
path[str(last_coordinate)] = step + steps_offset
steps_offset += steps
min_steps = 10000000
last_coordinate = [0, 0]
steps_offset = 0
intersection_dist = 1000000
for command in wire_2:
c = command[0]
steps = int(command[1:])
for step in range(1, steps + 1):
if c == "R":
last_coordinate = [last_coordinate[0] + 1, last_coordinate[1]]
elif c == "L":
last_coordinate = [last_coordinate[0] - 1, last_coordinate[1]]
elif c == "U":
last_coordinate = [last_coordinate[0], last_coordinate[1] + 1]
else:
last_coordinate = [last_coordinate[0], last_coordinate[1] - 1]
# print(last_coordinate, c)
if str(last_coordinate) in path:
intersection_dist = min(
intersection_dist, manhattan_distance([0, 0], last_coordinate))
steps_till_now = steps_offset + step
min_steps = min(min_steps, steps_till_now +
path[str(last_coordinate)])
steps_offset += steps
print(intersection_dist)
print(min_steps)
|
name = "Asen Chekov"
hi = "Hello, there!"
# function definition
def backwards(string):
return string[::-1]
# string slicing
# [start:stop:step]
print(name[::-1] + " " + hi)
print(backwards(name))
print(backwards(hi))
print(hi*3)
print(bool("False"))
# for loop
for number in range(-10,10):
print(number) |
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for extra credit, type it in anyway
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
# add
# 1.
# age = 35
# 2.
# 74 - 4500 = -4426
#
# weight * divide = 4500
# weight = 180
# divide=25
#
# 3. 35 + (-4426) = -4391
#
#
#
print "That becomes: ", what, "Can you do it by hand?"
# -4391
# I got it correct without checking, first time! :D - Austin @ 12:21PM Monday April 4 2016
# Exercise 21:
# Functions Can Return Something
# The purpose of this exercise is to demonstrate how functions in python return values with given arguments. |
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# We could do these two on one line, how?
# in_file = open(from_file)
indata = open(from_file).read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print" Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done."
out_file.close()
# We may comment this out (or remove it) as we have changed line 10 to optimize script per study drill.
# in_file.close()
# Exercise 17: More Files
# Found at: learnpythonthehardway.org/book/ex17.html
# Notes:
# len() is a function (len = length) that returns the length of a passed in string as a number (character count, essentially, which corrolates to bytes. one character = 1 byte
# Because I changed the indata variable to include "open(from_file)" and then call the run method, it's unnecessary to close the txt file at the end, because it was never assigned an actual memory space as the file itself. |
age = int(raw_input("How old are you? "))
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print "So, you're %i years old, %s tall and %s heavy." % (
age, height, weight)
# study drills: look up pydoc, what is it?
# pydoc is a way to look at documentation for python as well as documentation for a specific python file.
# You can also access it for particular built in functions/methods/etc.
# Typing this into terminal: pydoc raw_input
# This produces documentation help on what that command, in this case, raw_input, does.
# Remember to press Q to quit while using pydoc in the terminal.
# From common student questions:
# The input() function has security problems and should be avoided if possible. It also converts input as if it were python code rather than alphanumerical input.
# pydoc help on modules:
# open
#open(...)
# open(name[, mode[, buffering]]) -> file object
#
# Open a file using the file() type, returns a file object. This is the
# preferred way to open a file. See file.__doc__ for further information.
# file
# class file(object)
# | file(name[, mode[, buffering]]) -> file object
# |
# | Open a file. The mode can be 'r', 'w' or 'a' for reading (default),
# | writing or appending. The file will be created if it doesn't exist
# | when opened for writing or appending; it will be truncated when
# | opened for writing. Add a 'b' to the mode for binary files.
# | Add a '+' to the mode to allow simultaneous reading and writing.
# | If the buffering argument is given, 0 means unbuffered, 1 means line
# | buffered, and larger numbers specify the buffer size. The preferred way
# | to open a file is with the builtin open() function.
# | Add a 'U' to mode to open the file for input with universal newline
# | support. Any line ending in the input file will be seen as a '\n'
# | in Python. Also, a file so opened gains the attribute 'newlines';
# | the value for this attribute is one of None (no newline read yet),
# | '\r', '\n', '\r\n' or a tuple containing all the newline types seen.
# |
# | 'U' cannot be combined with 'w' or '+' mode.
# - This was all I bothered to grab, there is methods defined
# further using 'pydoc file'-
# os
# NAME
#os - OS routines for NT or Posix depending on what system we're on.
#FILE
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py
#MODULE DOCS
# http://docs.python.org/library/os
#DESCRIPTION
# This exports:
# - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
# - os.path is one of the modules posixpath, or ntpath
# - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'
# - os.curdir is a string representing the current directory ('.' or ':')
# - os.pardir is a string representing the parent directory ('..' or '::')
# - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
# - os.extsep is the extension separator ('.' or '/')
# - os.altsep is the alternate pathname separator (None or '/')
# - os.pathsep is the component separator used in $PATH etc
# - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
#
|
import argparse
import nltk
import os
class Parse:
"""A parser that processes sentences acccording to the rules of a specified grammar."""
def parse(self, grammarFilePath, sentenceFilePath):
"""Parses the sentences found in sentenceFilePath using the grammar found in grammarFilePath."""
# Load the grammar using NLTK:
grammarFilePath = os.path.abspath(grammarFilePath)
rules = nltk.data.load(grammarFilePath, 'text')
grammar = nltk.CFG.fromstring(rules)
# Load the parser using NLTK:
parser = nltk.parse.EarleyChartParser(grammar)
# Iterate over each of the sentences in the sentences file,
# writing the number of parses for each sentence:
sentenceFile = open(sentenceFilePath, "r")
lines = sentenceFile.readlines()
totalNoOfParses = 0
for line in lines:
noOfParses = 0
tokens = nltk.word_tokenize(line)
print(line, end="")
for interpretation in parser.parse(tokens):
print(interpretation)
noOfParses = noOfParses + 1
print('Number of parses:', noOfParses)
print()
totalNoOfParses = totalNoOfParses + noOfParses
print('Average parses per sentence:', totalNoOfParses / len(lines))
sentenceFile.close()
def main():
"""Calls parse with the parameters passed on the command line."""
parser = argparse.ArgumentParser(description='Parses the specified sentences using the specified grammar.')
parser.add_argument('grammarFile', type=str, help='the name of the file containing the grammar.')
parser.add_argument('sentenceFile', type=str, help='the name of the file containing the sentences.')
ns = parser.parse_args()
# Input Validation:
parse = Parse()
parse.parse(ns.grammarFile, ns.sentenceFile)
if __name__ == "__main__":
main()
|
from MyCNN import *
import data_loader
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
# mean and std of cifar10 in 3 channels
cifar10_mean = (0.49, 0.48, 0.45)
cifar10_std = (0.25, 0.24, 0.26)
# define transform operations of train dataset
train_transform = transforms.Compose([
# data augmentation
transforms.Pad(4),
transforms.RandomHorizontalFlip(),
transforms.RandomCrop(32),
transforms.ToTensor(),
transforms.Normalize(cifar10_mean, cifar10_std)
])
test_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(cifar10_mean, cifar10_std)
])
# torchvision.datasets provide CIFAR-10 dataset for classification
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True, transform=train_transform, download=True)
test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False, transform=test_transform)
# Data loader: provides single- or multi-process iterators over the dataset.
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=100, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=100, shuffle=True)
def fit(model, num_epochs, optimizer, device):
"""
train and evaluate an classifier num_epochs times.\\
We use optimizer and cross entropy loss to train the model. \\
Args: \\
model: CNN network\\
num_epochs: the number of training epochs\\
optimizer: optimize the loss function
"""
# loss and optimizer
loss_func = nn.CrossEntropyLoss()
model.to(device)
loss_func.to(device)
# log train loss and test accuracy
losses = []
accs = []
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch + 1, num_epochs))
# train step
loss = train(model, train_loader, loss_func, optimizer, device)
losses.append(loss)
# evaluate step
accuracy = evaluate(model, test_loader, device)
accs.append(accuracy)
# show curve
show_curve(losses, "train loss")
show_curve(accs, "test accuracy")
# hyper parameters
num_epochs = 10
lr = 0.01
image_size = 32
num_classes = 10
# declare and define an objet of MyCNN
mycnn = MyCNN(image_size, num_classes)
print(mycnn)
# Device configuration, cpu, cuda:0/1/2/3 available
device = torch.device('cuda:2')
print(device)
optimizer = torch.optim.Adam(mycnn.parameters(), lr=lr)
# start training on cifar10 dataset
fit(mycnn, num_epochs, optimizer, device)
|
# coding=utf-8
class MoneyBox:
def __init__(self, capacity):
# конструктор с аргументом – вместимость копилки
self.capacity = capacity
self.current_v = 0
def can_add(self, v):
# True, если можно добавить v монет, False иначе
return self.current_v + v <= self.capacity
def add(self, v):
# положить v монет в копилку
if self.can_add(v):
self.current_v += v
b = MoneyBox(3)
print(b.can_add(1))
print(b.can_add(3))
print(b.can_add(4))
b.add(2)
print(b.can_add(1))
print(b.can_add(3))
|
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
if(n<3):
return n;
a=1;
b=2;
for i in range(n-2):
a,b=b,a+b;
return b;
s=Solution();
print s.climbStairs(3);
print s.climbStairs(4);
print s.climbStairs(5);
|
import COMMON
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if(head==None):
return None;
result=head;
p1=head;
while(True):
# from start to p1 ,it's a sorted List
p2=p1.next;
if(p2==None):
break;
if(p2.val>=p1.val):
p1=p2;
continue;
# insert p2 to the old list
p1.next=p2.next;
if(p2.val<result.val):
p2.next=result;
result=p2;
else:
pointer=result;
while(pointer.next.val<p2.val):
pointer=pointer.next;
p2.next=pointer.next;
pointer.next=p2;
return result;
s=Solution();
COMMON.print_list(s.insertionSortList(COMMON.build_list([1,5,2,4,3])));
|
class Solution:
# @return a boolean
def isValid(self, s):
array=[];
for c in s:
if(c=="(" or c=="{" or c=="["):
array.append(c);
elif (array==[]):
return False;
else:
first=array.pop();
if(first=="(" and c==")"):
continue;
if(first=="{" and c=="}"):
continue;
if(first=="[" and c=="]"):
continue;
return False;
if(array==[]):
return True;
return False;
s=Solution();
print s.isValid("()[]{}");
print s.isValid("([)]");
|
class Solution:
# if we have a array like
# 4 5 6 7 3 9 8 2 1
# we need to swap 3 and 8,
# then reverse the 9 3 2 1
def find_next(self,prev):
n=len(prev);
result=prev[:];
pos=n-2;
while(pos>=0):
if(prev[pos]>prev[pos+1]):
pos-=1;
else:
# pos now point to the first place to swap
second=n-1;
while(prev[second]<prev[pos]):
second-=1;
result[pos]=prev[second];
result[second]=prev[pos];
end=n-1;
pos+=1;
while(pos<end):
result[pos],result[end]=result[end],result[pos];
end-=1;
pos+=1;
return result;
# this is the last one;
return [];
# @param num, a list of integer
# @return a list of lists of integers
def permute(self, num):
current=num[:];
current.sort();
result=[];
while(current!=[]):
result+=[current];
current=self.find_next(current);
return result;
s=Solution();
print s.permute([1,2,3]);
|
from tkinter import *
import tkinter.messagebox
# person class variable used to store information on all person objects
class Person:
def __init__(self):
self.f_name = "fname"
self.l_name = "lname"
self.age = 0
self.gender = "male"
self.ethnicity = "black"
self.weight = 0.0
self.temperature_cel = 0
self.temperature_for = 0
self.total_points = 0
global person
person = Person()
class RegistrationWindow:
def __init__(self, registration_window):
# declaration of variables for the registration window
self.fn_lbl = Label(registration_window, text="First Name")
self.f_name_entry = Entry(registration_window, bd=3)
self.ln_lbl = Label(registration_window, text="Last Name")
self.l_name_entry = Entry(registration_window, bd=3)
self.w_lbl = Label(registration_window, text="Weight")
self.weight_entry = Entry(registration_window, bd=3)
self.a_lbl = Label(registration_window, text="Age")
self.age_entry = Entry(registration_window, bd=3)
self.g_lbl = Label(registration_window, text="Gender")
self.gender_entry = Entry(registration_window, bd=3)
self.e_lbl = Label(registration_window, text="Ethnicity")
# drop down menu variable creation
self.tkvar = StringVar(registration_window) # created tk_variable
self.e_choices = {'Black', 'White', 'Asian', 'Chinese', 'Japanese'} # choices for dropdown menu
self.tkvar.set('Black') # default option for dd_menu
self.ethnicity_dd_menu = OptionMenu(registration_window, self.tkvar, *self.e_choices)
self.t_lbl = Label(registration_window, text="Temperature(celcius)")
self.temperature_entry = Entry(registration_window, bd=3)
self.register_btn = Button(registration_window, text="Finish", command=self.add_person)
# place butttons in window to be created on keypress in main menu
self.fn_lbl.pack()
self.f_name_entry.pack()
self.ln_lbl.pack()
self.l_name_entry.pack()
self.w_lbl.pack()
self.weight_entry.pack()
self.a_lbl.pack()
self.age_entry.pack()
self.g_lbl.pack()
self.gender_entry.pack()
self.e_lbl.pack()
self.ethnicity_dd_menu.pack()
self.t_lbl.pack()
self.temperature_entry.pack()
self.register_btn.pack()
def write_to_file(self): # called at the end of the add_person method
outputFile = open("patients.txt", "a+") # Open a file for appending
# Write record to file
person_record = person.f_name + "\t" + person.l_name + "\t" + str(person.weight) + "\t" + \
str(person.age) + "\t" + person.gender + "\t" + person.ethnicity + "\t" + \
str(person.temperature_cel) + "\t" + str(person.temperature_for) + "\t" +\
str(person.total_points)
outputFile.write("%s" % person_record)
outputFile.close() # Close the file
tkinter.messagebox.showinfo("Data written")
def add_person(self): # saves all data entered to the global person variable
try:
person.f_name = self.f_name_entry.get()
person.l_name = self.l_name_entry.get()
string_weight = self.weight_entry.get()
person.weight = float(string_weight)
string_age = self.age_entry.get()
person.age = int(string_age)
person.gender = self.gender_entry.get()
person.ethnicity = self.tkvar.get()
string_temp_c = self.temperature_entry.get()
person.temperature_cel = float(string_temp_c)
# test entered values and assign points
print(" ")
print("**************JahMedicare****************")
# points acoording to weight
if person.weight > 200:
person.total_points += 4
print("sorry to break it to you but, you are waaay overweight.")
else:
if 100 <= person.weight <= 200:
person.total_points += 2
print("congrats you fat :).")
# points acoording to age
if person.age > 65:
person.total_points += 3
if person.age < 3:
person.total_points += 2
# points according to temperature
if 37.2 <= person.temperature_cel <= 100:
person.total_points += 2
print("burning up bro:).")
# calculates forenheight
person.temperature_for = (person.temperature_cel * (9 / 5)) + 32
tkinter.messagebox.showinfo("well done", "record added succesfully")
print("name: " + person.f_name)
print("name: " + person.l_name)
print("weight " + str(person.weight)) # converts weight back to string for output
print("age: " + str(person.age))
print("gender: " + person.gender)
print("ethnicity: " + str(person.ethnicity))
print("temperature: " + str(person.temperature_cel) + " C")
print("temperature: " + str(person.temperature_for) + " F")
print("total Points: " + str(person.total_points))
self.write_to_file()
except ValueError:
tkinter.messagebox.showerror("please enter valid numbers in the number fields")
print("That is not a number")
except FileNotFoundError:
tkinter.messagebox.showerror("file could not be found")
print("file not found")
class ReportWindow:
def __init__(self, report_window):
self. spacer = Label(report_window, height=4, text=" ")
self.text = Text(report_window, height=30, width=80)
self.spacer.pack()
self.text.pack()
self.build_report()
self.text.config(state=DISABLED)
def build_report(self):
try:
file_handle = open('patients.txt', "r")
if file_handle.mode =="r":
records = file_handle.readlines()
file_handle.close()
heading ="First " + "\t" +"Last " + "\t" +"Weight" + "\t" +"Age " + "\t" +"Gender" + \
"\t" +"Ethinic" + "\t" +"Temp C" + "\t" +"Temp F" + "\t" +"Points" + "\n"
print("The last line is:")
print(records[len(records) - 1])
self.text.insert('end', "Record Result"+"\n")
self.text.insert('end', heading)
self.text.insert('end', records[len(records) - 1])
except FileNotFoundError:
tkinter.messagebox.showerror("file not found")
class AdminReportWindow:
def __init__(self, report_window):
self. spacer = Label(report_window, height=4, text=" ")
self.text = Text(report_window, height=30, width=80)
self.spacer.pack()
self.text.pack()
self.build_report()
self.text.config(state=DISABLED)
def build_report(self):
try:
file_handle = open("patients.txt", "r")
if file_handle.mode =="r":
records = file_handle.read()
file_handle.close()
heading ="First " + "\t" +"Last " + "\t" +"Weight" + "\t" +"Age " + "\t" +"Gender" + \
"\t" +"Ethinic" + "\t" +"Temp C" + "\t" +"Temp F" + "\t" +"Points" + "\n"
self.text.insert('end',heading)
print(records)
self.text.insert('end', records)
record = records[len(records) - 1]
self.text.insert('end', record)
# self.text.insert("Record Result")
except FileNotFoundError:
tkinter.messagebox.showerror("file not found")
class DiagnosisWindow:
def __init__(self, diagnosis_win):
self.count =0
self.questions = ["do you have a cold", "Do you cough a lot", "do you have the flu",
"Do you have any other bacterial/fungal", "has the infection lasted more than three weeks.",
"Are you experiencing chest pain", "Do you often feel more fatigue than you normally would",
"Have you been vomiting", "experiencing Nausea", "Have you been having diarrhea",
"Have you been wheezing or experiencing shortness of breath"]
self.answer = [None]*11
self.spacer1 = Label(diagnosis_win, height=4)
self.question_area = Entry(diagnosis_win, justify='center', relief='solid', font="Times 13", width=60)
self.spacer2 = Label(diagnosis_win)
self.answer_area = Entry(diagnosis_win,justify='center', relief='solid', font="Times 11", width=30)
self.spacer3 = Label(diagnosis_win)
self.submit_btn = Button(diagnosis_win, text="submit", command=self.question_changer)
#pack created variables to window
self.spacer1.pack()
self.question_area.pack()
self.spacer2.pack()
self.answer_area.pack()
self.spacer3.pack()
self.submit_btn.pack()
print("question{}: {}".format(self.count, self.questions[self.count]))
self.question_area.insert('end', self.questions[self.count])
def question_changer(self):
self.count += 1
self.question_area.delete(0,'end')
self.answer_area.delete(0,'end')
self.question_area.insert('end', self.questions[self.count])
self.answer[self.count] = self.answer_area.get()
print(self.answer[self.count])
# main window
class Main_Window:
def __init__(self, main_window):
# create all window widgets
self.spacer = Label(main_window, text=" ")
self.lbl1 = Label(main_window, text="JahMedicare", relief="solid", font="Times 32", width=50)
self.lbl2 = Label(main_window, text="Digital Doctor", relief="solid", font="Times 20", width=50)
self.lbl3 = Label(main_window, text="You get here, you get better", width=50)
self.space = Label(main_window, text=" ")
self.btn1 = Button(main_window, text="add a patient record", command=self.register)
self.btn2 = Button(main_window, text="diagnose a patient", command=self.diagnosis)
self.btn3 = Button(main_window, text="show result", command=self.person_record)
self.btn4 = Button(main_window, text="admin login", command=self.all_records)
# add all widgets to window
self.spacer.pack()
self.lbl1.pack()
self.lbl2.pack()
self.lbl3.pack()
self.space.pack()
self.btn1.pack()
self.btn2.pack()
self.btn3.pack()
self.btn4.pack()
# display registration window on command
def register(self):
root_register = Tk()
reg_win = RegistrationWindow(root_register)
root_register.title("JahMedicare Registration")
root_register.geometry("800x500+10+10")
root_register.mainloop()
def person_record(self):
root_record = Tk()
rec_win = ReportWindow(root_record)
root_record.title("JahMedicare Report")
root_record.geometry("800x500+10+10")
root_record.mainloop()
def all_records(self):
root_record = Tk()
ad_rep_win = AdminReportWindow(root_record)
root_record.title("JahMedicare Report")
root_record.geometry("800x500+10+10")
root_record.mainloop()
def diagnosis(self):
root = Tk()
diagnosis_win = DiagnosisWindow(root)
root.title('JahMedicare Diagnosis')
root.geometry("800x400+10+10")
root.mainloop()
# display main menu
main_window = Tk()
window = Main_Window(main_window)
main_window.title('JahMedicare System')
main_window.geometry("800x400+10+10")
main_window.mainloop()
|
import sqlite3
class SQL:
""" sql class containing all methods, which connects the project to database """
@staticmethod
def sql_connection(database="database"):
""" create database connection """
return sqlite3.connect(database)
@staticmethod
def execute_query(query, params=""):
""" execute query with specific params, return list of objects or None, if list is empty """
conn = SQL.sql_connection()
cur = conn.cursor()
cur.execute(query, params)
result = cur.fetchall()
conn.commit()
conn.close()
if result:
return result
|
# '''
# Basic hash table key/value pair
# '''
class Pair:
def __init__(self, key, value):
self.key = key
self.value = value
# '''
# Basic hash table
# Fill this in. All storage values should be initialized to None
# Done
# '''
class BasicHashTable:
def __init__(self, capacity):
self.hash_table = [None] * capacity
self.capacity = capacity
#return hash_table
# '''
# Fill this in.
# Research and implement the djb2 hash function
# '''
def hash(string, capacity):
m = 0
for i in string:
m = m + ord(i)
m = m%capacity
return m
# '''
# Fill this in.
# If you are overwriting a value with a different key, print a warning.
# '''
def hash_table_insert(bht, key, value):
l = len(bht.hash_table)
if bht.hash_table[hash(key, l)] == None:
bht.hash_table[hash(key, l)] = value
else:
print("ERROR: overwriting")
return None
# '''
# Fill this in.
# If you try to remove a value that isn't there, print a warning.
# '''
def hash_table_remove(bht, key):
l = len(bht.hash_table)
if bht.hash_table[hash(key, l)] == None:
print("ERROR: Value does not exist")
return None
else:
bht.hash_table[hash(key, l)] = None
# '''
# Fill this in.
# Should return None if the key is not found.
# '''
def hash_table_retrieve(bht, key):
l = len(bht.hash_table)
if bht.hash_table[hash(key, l)] == None:
return None
else:
value = bht.hash_table[hash(key, l)]
bht.hash_table[hash(key, l)] = None
return value
def Testing():
bht = BasicHashTable(16)
#list = MyLinkedList()
hash_table_insert(bht, "line", "Here today...\n")
hash_table_remove(bht, "line")
if hash_table_retrieve(bht, "line") is None:
print("...gone tomorrow (success!)")
else:
print("ERROR: STILL HERE")
Testing()
|
# Maze Program Written by Michael Toth
setMediaPath('/Users/toth/Documents/Github/turtlemaze')
import time
import random
class Maze(object):
""" Solves a maze with a turtle in JES """
def __init__(self):
""" Initializer, sets image """
self.image = makePicture('maze.jpg')
self.w = makeWorld(getWidth(self.image),getHeight(self.image))
self.w.setPicture(self.image)
self.t = makeTurtle(self.w)
self.home()
self.endSound = makeSound('end.wav')
self.searchSound = makeSound('searching.wav')
self.soundOn=false
def home(self):
penUp(self.t)
moveTo(self.t,30,190)
self.t.setHeading(90)
def clear(self):
""" sets the maze to all walls """
for col in range(0,420,20):
for row in range(0,300,20):
addRectFilled(self.image,col,row,20,20,blue)
addRectFilled(self.image,20,180,20,20,white)
self.w.hide()
self.w.show()
def reset(self):
""" resets the turtle and image. """
self.image = makePicture('maze.jpg')
self.w.setPicture(self.image)
self.t.clearPath()
penUp(self.t)
moveTo(self.t,30,190)
self.t.setHeading(90)
penDown(self.t)
def find_space(self):
''' finds 9x9 all blue area '''
for col in range(30,getWidth(self.image),20):
printNow(col)
for row in range(30,getHeight(self.image),20):
empty=true
for dx in range(-20,40,20):
for dy in range(-20,40,20):
if col+dx>=0 and col+dx<420 and row+dy>=0 and row+dy<300:
p=getPixel(self.image,col+dx,row+dy)
if getColor(p)!=blue:
empty=false
if empty:
return (col,row)
def dig(self,through=false):
"""
digs in the current direction and returns true if successful
if through is true, it will dig through to existing paths
"""
if self.colorInFront() != blue:
#printNow("color in front is " + str(self.colorInFront()))
return false
x=getXPos(self.t)
y=getYPos(self.t)
x=x-10
y=y-10
h=self.t.getHeading()
#printNow(str(x)+","+str(y)+" "+str(h))
if h==0:
y=y-20; yy=y-20; xx=x
if xx<=0 or yy<=0:
return false
if not through:
if getColor(getPixelAt(self.image,xx-20,yy))!=blue:
return false
if getColor(getPixelAt(self.image,xx+20,yy))!=blue:
return false
if getColor(getPixelAt(self.image,xx-20,y))!=blue:
return false
if getColor(getPixelAt(self.image,xx+20,y))!=blue:
return false
if h==90 or h==-270:
x=x+20; xx=x+20; yy=y
if not through:
try:
if getColor(getPixelAt(self.image,xx,yy-20))!=blue:
#printNow(str(x)+","+str(y))
#printNow(getColor(getPixelAt(self.image,xx,yy-20)))
return false
if getColor(getPixelAt(self.image,xx,yy+20))!=blue:
#printNow(str(x)+","+str(y))
#printNow(getColor(getPixelAt(self.image,xx,yy+20)))
return false
if getColor(getPixelAt(self.image,x,yy-20))!=blue:
#printNow(str(x)+","+str(y))
#printNow(getColor(getPixelAt(self.image,x,yy-20)))
return false
if getColor(getPixelAt(self.image,x,yy+20))!=blue:
#printNow(str(x)+","+str(y))
#printNow(getColor(getPixelAt(self.image,xx,yy+20)))
return false
except:
print "."
# do nothing
if h==180 or h==-180:
y=y+20; yy=y+20; xx=x
if not through:
try:
if getColor(getPixelAt(self.image,xx-20,yy))!=blue:
return false
if getColor(getPixelAt(self.image,xx+20,yy))!=blue:
return false
if getColor(getPixelAt(self.image,xx-20,y))!=blue:
return false
if getColor(getPixelAt(self.image,xx+20,y))!=blue:
return false
except:
print "."
# return false
if h==-90 or h==270:
x=x-20; xx=x-20; yy=y
if not through:
try:
if getColor(getPixelAt(self.image,x,yy-20))!=blue:
#printNow(getColor(getPixelAt(self.image,x,yy-20)))
return false
if getColor(getPixelAt(self.image,x,yy+20))!=blue:
#printNow(getColor(getPixelAt(self.image,x,yy+20)))
return false
if getColor(getPixelAt(self.image,xx,yy-20))!=blue:
#printNow(getColor(getPixelAt(self.image,xx,yy-20)))
return false
if getColor(getPixelAt(self.image,xx,yy+20))!=blue:
#printNow(getColor(getPixelAt(self.image,xx,yy+20)))
return false
except:
print "."
# return false
if x<=0 or x>=420 or y<=0 or y>=280:
return false
if xx<=0 or xx>=420 or yy<=0 or yy>=280:
return false
if getColor(getPixelAt(self.image,xx,yy))==white:
return false
addRectFilled(self.image,x,y,20,20,white)
self.w.hide()
self.w.show()
return true
def makePathFrom(self,t):
''' t is a tuple specifying a starting location surrounded by walls. '''
self.t.moveTo(t[0],t[1])
addRectFilled(self.image,t[0]-10,t[1]-10,20,20,white)
ntimes=0
while self.colorInFront()!=white and ntimes<1000:
ntimes=ntimes+1
dx=random.randint(-3,5)
dy=random.randint(-3,5)
if dx<0: # direction is west
self.t.setHeading(-90)
else:
self.t.setHeading(90)
while dx!=0 and self.colorInFront()!=white:
if dx<0:
dx=dx+1
elif dx>0:
dx=dx-1
self.dig(through=true)
self.move()
if dy<0: # direction is north
self.t.setHeading(0)
else:
self.t.setHeading(180)
while dy!=0 and self.colorInFront()!=white:
if dy<0:
dy=dy+1
elif dy>0:
dy=dy-1
self.dig(through=true)
self.move()
if ntimes>=1000:
return false
else:
return true
def makePath(self,mark_end=True):
''' makes a path to the right hand wall '''
ntimes=0
while self.t.getXPos() < 380 and ntimes<1000:
ntimes=ntimes+1
dx=random.randint(-3,5)
dy=random.randint(-3,5)
if dx<0: # direction is west
self.t.setHeading(-90)
else:
self.t.setHeading(90)
while dx!=0:
if dx<0:
dx=dx+1
elif dx>0:
dx=dx-1
self.dig()
self.move()
if dy<0: # direction is north
self.t.setHeading(0)
else:
self.t.setHeading(180)
while dy!=0:
if dy<0:
dy=dy+1
elif dy>0:
dy=dy-1
self.dig()
self.move()
if ntimes>=1000:
return false
else:
x=self.t.getXPos()+10
y=self.t.getYPos()-10
if mark_end:
addRectFilled(self.image,x,y,20,20,yellow)
return true
def move(self):
''' moves without painting '''
if self.colorInFront()!=white:
return false
self.t.forward(20)
return true
def colorInFront(self):
""" Returns the color 11 pixels in front of the turtle. """
dx = 11
xpos = self.t.getXPos()
ypos = self.t.getYPos()
h = self.t.getHeading()
if h == 0:
ypos = ypos - dx
if h == 90 or h == -270:
xpos = xpos + dx
if h == 180 or h == -180:
ypos = ypos + dx
if h == -90 or h == 270:
xpos = xpos - dx
try:
c = getColor(getPixelAt(self.image,xpos,ypos))
except:
return blue
if distance(c,white) < 150:
return white
if distance(c,blue) < 150:
return blue
if distance(c,green) < 150:
return green
if distance(c,red) < 150:
return red
if distance(c,yellow) < 150:
return yellow
return blue # assume wall if uncertain
def travel2BranchOrWall(self):
""" Moves the mouse to the next occurrance of a branch or a wall. """
if self.surroundings().count(white) > 1:
while self.surroundings().count(white) > 1:
self.forward(1)
if self.colorInFront() == white:
while self.colorInFront() == white and self.surroundings().count(white) == 1:
self.forward(1)
if self.surroundings().count(white) > 1:
if self.soundOn:
play(self.searchSound)
time.sleep(0.6)
self.forward(9)
def forward(self,dist):
while dist > 0:
if self.colorInFront() == green:
addOvalFilled(self.image,self.t.getXPos()-10,self.t.getYPos()-10,20,20,red)
else:
addOvalFilled(self.image,self.t.getXPos()-10,self.t.getYPos()-10,20,20,green)
dist = dist - 1
forward(self.t,1)
def surroundings(self):
s=[]
for i in range(4):
s.append(self.colorInFront())
turn(self.t)
return s
def turnOnSound(self):
self.soundOn=true
def turnOffSound(self):
self.soundOn=false
def solveFrom(self,xpos,ypos,hdg):
penUp(self.t)
moveTo(self.t,xpos,ypos)
self.t.setHeading(hdg)
penDown(self.t)
self.solve()
def solve(self,xpos=30,ypos=190,hdg=90):
if self.colorInFront() == yellow:
if self.soundOn:
play(self.endSound)
return true
for i in range(4):
if self.colorInFront()==yellow:
return true
if self.colorInFront()==white:
saveX = m.t.getXPos()
saveY = m.t.getYPos()
saveH = m.t.getHeading()
self.travel2BranchOrWall()
if self.solve():
return true
else:
penUp(self.t)
turnToFace(self.t,saveX,saveY)
d=sqrt((self.t.getXPos()-saveX)**2+(self.t.getYPos()-saveY)**2)
penDown(self.t)
self.forward(d)
self.t.setHeading(saveH)
self.t.turnRight()
return false
def create(self):
m.t.penUp()
m.clear()
m.makePath()
m.t.moveTo(30,190)
m.t.setHeading(90)
# Tests Follow This Line
if true:
m=Maze()
m.clear()
assert(m.find_space()!=None)
printNow("find_space is ok")
printNow(str(m.find_space()))
m.create()
s=m.find_space()
while s!=None:
m.makePathFrom(s)
s=m.find_space()
m.home()
m.solve()
if false:
# we should be able to dig to second-to-last column
m=Maze()
m.clear()
addRectFilled(m.image,360,180,20,20,white)
m.t.moveTo(370,190)
m.t.setHeading(90)
assert(m.dig())
# we want to draw a maze.
# blank the screen
m=Maze()
m.reset()
m.clear()
if m.colorInFront() == blue:
printNow("Test 20 passed")
else:
printNow("Test 20 failed, color should be blue in front after clear.")
# our current position should be white.
if getColor(getPixelAt(m.image,getXPos(m.t),getYPos(m.t))) != white:
printNow("Test 21 failed, not white at home location")
else:
printNow("Test 21 passed.")
# we should not be able to move
assert(m.move()==false)
# we should be able to dig
assert(m.dig())
# we should be able to move
assert(m.move())
# insure a wall separates previous trails from current dig
m=Maze()
m.clear()
addRectFilled(m.image,60,180,20,20,white)
m.w.hide(); m.w.show()
assert(m.dig()==false)
m.clear()
addRectFilled(m.image,60,200,20,20,white)
m.w.hide(); m.w.show()
assert(m.dig()==false)
m.clear()
addRectFilled(m.image,60,160,20,20,white)
m.w.hide(); m.w.show()
assert(m.dig()==false)
# make a path to the right hand side
m=Maze()
m.clear()
m.t.penUp()
assert(m.makePath()==true)
m.t.moveTo(30,190)
m.t.setHeading(90)
m.solve()
doTests = false
if doTests:
# First Test
m=Maze()
if m.__class__ == Maze:
printNow("Test 1 passed, Maze exists.")
else:
printNow("Test 1 failed. Maze does not exist.")
# Second Test, Test for image
if m.image.__class__ == Picture:
printNow("Test 2 passed, Image exists.")
else:
printNow("Test 2 failed, Image does not exist.")
# Third test. Test for existence of the turtle 'world'.
try:
if m.w.__class__ == World:
printNow("Test 3 passed, World exists.")
# m.w.hideFrame()
except:
printNow("Test 3 failed, World does not exist.")
# Test 4: Test for maze.jpg as background image
try:
if m.w.getPicture().fileName[-8:] == 'maze.jpg':
printNow("Test 4 passed, world picture is maze.jpg")
else:
printNow("Test 4 failed, world picture is " + m.w.getPicture().fileName)
except:
printNow("Test 4 failed, unable to get file name.")
# Test 5: Check for turtle.
try:
if m.t.__class__ == Turtle:
printNow("Test 5 passed, turtle exists.")
else:
printNow("Test 5 failed, turtle does not exist.")
except:
printNow("Test 5 failed, unable to access turtle.")
# Test 6: Check for turtle in proper starting location
if m.t.getXPos() == 30 and m.t.getYPos() == 190:
printNow("Test 6 passed, turtle is in the correct position.")
else:
printNow("Test 6 failed, turtle is not in the correct starting position.")
# Test 7: Check for colorInFront. It should return None
if dir(m).index('colorInFront') > 0:
printNow("Test 7 passed, colorInFront exists.")
else:
printNow("Test 7 failed, colorInFront does not exist")
# Test 8: Check that colorInFront returns white
if m.colorInFront() == white:
printNow("Test 8 passed, colorInFront returns white.")
else:
printNow("Test 8 failed, colorInFront does not return white.")
# Test 9: Check that colorInFront returns blue when facing a wall
turnLeft(m.t)
turnLeft(m.t)
if m.colorInFront() == blue:
printNow("Test 9 passed, colorInFront is blue when facing a wall.")
else:
printNow("Test 9 failed, colorInFront returned " + str(m.colorInFront()))
# Test 10: Check for existence of travel2BranchOrWall
try:
if dir(m).index('travel2BranchOrWall') > 0:
printNow("Test 10 passed, travel2BranchOrWall exists.")
else:
printNow("Test 10 failed, travel2BranchOrWall does not exist")
except:
printNow("Test 10 failed, travel2BranchOrWall does not exist.")
# Test 11: Check for existence of reset
try:
if dir(m).index('reset') > 0:
printNow("Test 11 passed, reset exists.")
else:
printNow("Test 11 failed, reset does not exist")
except:
printNow("Test 11 failed, reset does not exist.")
# Test 12: Check that reset puts the turtle at 30,190 facing north.
m.reset()
assert m.t.getXPos() == 30, "Test 12 failed, x position is " + str(m.t.getXPos())
assert m.t.getYPos() == 190, "Test 12 failed, y position is " + str(m.t.getYPos())
assert m.t.getHeading() == 90, "Test 12 failed, heading is " + str(m.t.getHeading())
printNow("Test 12 passed, x,y, and heading are correct after reset.")
# Test 13: Check that we travel to wall after travel2BranchOrWall
m.reset()
m.travel2BranchOrWall()
if m.t.getXPos() != 109:
printNow("Test 13 failed, x position is " + str(m.t.getXPos()))
elif m.t.getYPos() != 190:
printNow("Test 13 failed, y position is " + str(m.t.getYPos()))
else:
printNow("Test 13 passed.")
# Test 14: Check travel2BranchOrWall going north
m.reset()
turnLeft(m.t)
m.travel2BranchOrWall()
if m.t.getXPos() != 30:
printNow("Test 14 failed, x position is " + str(m.t.getXPos()))
elif m.t.getYPos() != 110:
printNow("Test 14 failed, y position is " + str(m.t.getYPos()))
else:
printNow("Test 14 passed.")
# Test 15: Check that we are leaving a green trail
m.reset()
m.forward(30)
m.t.setHeading(-90)
if m.colorInFront() != green:
printNow("Test 15 failed, color is not green but " + str(m.colorInFront()))
else:
printNow("Test 15 passed")
# Test 16: Checks that surroundings passes back [white,blue,blue,white]
m.reset()
if m.surroundings() != [white,blue,blue,white]:
printNow("Test 16 failed, surroundings returned " + str(m.surroundings()))
else:
printNow("Test 16 passed.")
# Test 17: Check for solve when turtle is at the cheese
m.reset()
penUp(m.t)
moveTo(m.t,390,155)
m.t.setHeading(180)
if m.solve():
printNow("Test 17 passed")
else:
printNow("Test 17 failed")
# Test 18: Check for solve returning false from 150,230
m.reset()
penUp(m.t)
moveTo(m.t,150,230)
m.t.setHeading(0)
if m.solve():
printNow("Test 18 failed, returned true")
else:
printNow("Test 18 passed.")
# Test 19: Check for a red trail
m.reset()
m.forward(50)
m.t.setHeading(-90)
m.forward(50)
m.t.setHeading(90)
if m.colorInFront() == red:
printNow("Test 19 passed")
else:
printNow("Test 19 failed, expected red but got " + str(m.colorInFront()))
# Test xx: Check that surroundings returns ['empty','wall','wall','empty'] after reset
# m.reset()
# if m.surroundings() != ['empty','wall','wall','empty']:
# printNow("Test 15 failed, surroundings returned " + str(m.surroundings()))
# else:
# printNow("Test 15 passed, surroundings are correct")
|
from datetime import datetime, date, time, timedelta
def str_to_date(date, format="%Y-%m-%d"):
if type(date) == str:
date = datetime.strptime(date, format)
return date
def str_to_time(time, format="%H:%M:%S"):
if type(time) == str:
time = datetime.strptime(time, format).time()
return time
def str_to_date_time(date, format="%Y-%m-%d %H:%M:%S"):
if type(date) == str:
date = datetime.strptime(date, format)
return date
def get_datetime(date, time, dateformat="%Y-%m-%d", timeformat="%H:%M:%S"):
return datetime.combine(str_to_date(date, dateformat), str_to_time(time, timeformat))
# the same for df columns
def df_str_to_date(df, column, format="%Y-%m-%d"):
df[column] = df[column].apply(lambda x: str_to_date(x, format))
def df_str_to_time(df, column, format="%H:%M:%S"):
df[column] = df[column].apply(lambda x: str_to_time(x, format))
def df_add_datetime(df, date="date", time="time", column_name="date_time", dateformat="%Y-%m-%d", timeformat="%H:%M:%S"):
df[column_name] = df.apply(lambda x: get_datetime(x[date], x[time], dateformat, timeformat), axis=1)
|
lucky_num = 28
count = 0
#for循环列表
magicians=['alice','david','carolina']
for magician in magicians:
print('%s that was a great trick!'%magician.title())
while count<3:
in_num = int(input("input your guess num:"))
if in_num==lucky_num:
print("bingo!")
break
elif in_num > lucky_num:
print("guess num is bigger!")
else:
print("guess num is smaller!")
count+=1
#while … else 循环条件正常结束,执行
else:
print("count out!")
|
#!/usr/bin/env python
# HW04_ch08_ex04
# The following functions are all intended to check whether a string contains
# any lowercase letters, but at least some of them are wrong. For each
# function, describe (is the docstring) what the function actually does.
# You can assume that the parameter is a string.
# Do not merely paste the output as a counterexample into the documentation
# string, explain what is wrong.
###############################################################################
# Body
def any_lowercase1(s):
"""Explain what is wrong, if anything, here.
It is only checking the first value of the string , the return is causing it to leave
the function
"""
for c in s:
if c.islower():
return( True)
else:
return( False)
def any_lowercase2(s):
"""Explain what is wrong, if anything, here.
The 'c' is wrong , it treats the 'c' as a string and therefore will always return True
"""
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
def any_lowercase3(s):
"""Explain what is wrong, if anything, here.
The function is wrong and works only on the last letter of the string , if the last
letter is in lower case we get a True or else a False , its not evaluating the entire
string
"""
for c in s:
flag = c.islower()
return flag
def any_lowercase4(s):
"""Explain what is wrong, if anything, here.
works fine
"""
flag = False
for c in s:
flag = flag or c.islower()
return flag
def any_lowercase5(s):
"""Explain what is wrong, if anything, here.
Fails for any case which has even one upper case letter
"""
for c in s:
if not c.islower():
return False
return True
###############################################################################
def main():
# Remove print("Hello World!") and for each function above that is wrong,
# call that function with a string for which the function returns
# incorrectly.
# ex.: any_lowercase_("thisstringmessesupthefunction")
print("Hello World!")
s = input("Enter the string ")
print(any_lowercase5(s))
if __name__ == '__main__':
main()
|
from turtle import Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time
screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong")
# Used to turn off animation
# You need manually update any changes required on the screen henceforth
# The screen also requires refreshing
screen.tracer(0)
r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()
screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")
game_is_on = True
while game_is_on:
# To move the ball at a reasonable pace
# Increase pace after each paddle hit
time.sleep(ball.pace)
# NOTE: Screen Tracer is off prevent animations from showing onscreen
# Here, we update the screen after performing the necessary turtle movements
# without the corresponding animations from turning up onscreen
screen.update()
ball.move()
# Detect collision with ball at the top and bottom
if ball.ycor() > 280 or ball.ycor() < -280:
ball.bounce_y()
# Detect contact with the paddle
if (ball.distance(r_paddle) < 50 and ball.xcor() > 320) or (ball.distance(l_paddle) < 50 and ball.xcor() < -320):
ball.bounce_x()
# Detect r paddle miss
if ball.xcor() > 380:
ball.reset_position()
scoreboard.l_point()
# Detect l paddle miss
if ball.xcor() < -380:
ball.reset_position()
scoreboard.r_point()
# To check the screen specifications
# The screen disappears otherwise
screen.exitonclick()
|
"""
HTML on Popups - Simple
Note that if you want to have stylized text
(bold, different fonts, etc) in the popup window
you can use HTML.
"""
import folium
import pandas
data = pandas.read_csv("volcanoes.txt")
latitude = list(data["Latitude"])
longitude = list(data["Longitude"])
elevation = list(data["Elev"])
# the text for displaying elevation
html = """<h4>Volcano information:</h4>
Height: %s m
"""
map = folium.Map(location=[13.100883217642943, 80.24192569506516], zoom_start=3, tiles="Stamen Terrain")
fg = folium.FeatureGroup(name="My Map")
for lt, ln, el in zip(latitude, longitude, elevation):
# creating an iframe for the html
iframe = folium.IFrame(html=html % str(el), width=200, height=100)
# changing popup object to iframe
fg.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(iframe), icon=folium.Icon(color='red')))
map.add_child(fg)
map.save("Map.html") |
"""Plain English
start
define function to calculate what percentage of grades lie above the average
initialize counter and percentage
create a loop that iterates through the Final.txt file
add 1 to counter that tracks how many grades exist above the average value of the grades
divide the count of grades above the average by the total number of grades and multiply by 100
after this number is found, round the number to two decimal places to return the final answer
define a function that calculates the average grade
add all of the numbers in the file up and divide by how many grades exist in the file
define main and open the text file to read
append all of the grades in the file into a list
call the function that calculates the average grade to determine the avgerage grade
print out values that state the number of grades total, the average grade, and what percentage of grades
lie above the average value
use sep to remove the space between the number and the percentage sign
call main and execute all of the defined functions in the proper order and print to the user
the total number of grades, the average grade, and the percentage of grades above average
end
"""
""" PSEUDOCODE
define calculate_percentage_above_average(avg, grades)
counter = 0
create a float percent = 0.0
for i in grades:
if float(i) > avg:
increment counter by one if above average counter = counter + 1
solve for the percent = counter/len(grades) * 100
return the rounded decimal with round(percent, 2)
define average_grade(grades)
find value of all grades added, add = sum(grades)
set an integer for the length of the file, length = len(grades)
solve for the average grade, avg = add / length
return avg
define main()
open the Final.txt file and set a_file equal to it
define an empty list, grades = []
run a for loop for all values in the file,for i in a_file:
append the values in the file to a list, grades.append(int(i))
avg = average_grade(grades)
print("Number of grades:", len(grades))
print("Average grade:", avg)
print("Percentage of grades above average: ", calculate_percentage_above_average(avg, grades))
close the file
if __name__ == "__main__"
main()
"""
# Code for sorting grades
def calculate_percentage_above_average(avg, grades):
counter = 0
percent = 0.0
for i in grades:
if float(i) > avg:
counter = counter+1
percent = counter/len(grades) * 100
return round(percent,2)
def average_grade(grades):
add = sum(grades)
length = len(grades)
avg = add / length
return avg
def main():
a_file = open("/Users/CCott_000/Desktop/Spring2021/FinalExam/Final.txt", "r")
grades = []
for i in a_file:
grades.append(int(i))
avg = average_grade(grades)
print("Number of grades:", len(grades))
print("Average grade:", avg)
print("Percentage of grades above average: ", calculate_percentage_above_average(avg, grades), "%", sep='')
a_file.close()
if __name__ == "__main__":
main()
|
from bs4 import BeautifulSoup
import ssl
#import urllib2
import os
import json
import requests
import urllib
import urllib.request
from urllib.request import urlopen
class DownloadImagesService(object):
"""
This class provides a functionality to download images from google search based on a query string
The service downloads the image to a specified location and also returns a list of the image urls of images
which can be used by the tagging service to get the tags for the images
"""
def __init__(self,ua,location):
"""
:param ua: User agent for the computer which will be used to construct the header object
"""
self.directory = location
self.header ={'User-Agent':ua}
def extractImagesFromHtml(self,html):
"""
:param html: the html of the google image search results page
:return: returns a list of the image urls extracted from the html
"""
ActualImages = []
for a in html.find_all("div", {"class": "rg_meta"}):
link, Type = json.loads(a.text)["ou"], json.loads(a.text)["ity"]
ActualImages.append((link, Type))
#print (ActualImages)
#print (len(ActualImages))
return ActualImages
def get_soup(self,url):
"""
used to get the html in a form that we can parse using the library beautiful soup
:param url(str): url of the page that we want to parse using beautiful soup
:return: html of the url page
"""
#return BeautifulSoup(urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')
soup =None
ssl._create_default_https_context = ssl._create_unverified_context
req = urllib.request.Request(url, headers=self.header)
with urllib.request.urlopen(req) as response:
soup = BeautifulSoup(response,'html.parser')
return soup
def downloadImages(self,ActualImages,query) :
"""
Used to download the images extracted using from the html of the google search page
The qquery string is used to create a new folder based on query string
:param ActualImages(list): A list of image urls that we want to download
:param query(str): query string for which we need the images
:return: metadata of the images downloaded
"""
metadata=[]
#this dictionary keeps a count of each of the file types and their count in the downloads folder
#this is important because when we are downloading images we need to name them accordingly
imageTypes = {'jpg': 0, 'gif': 0, 'png': 0, 'jpeg': 0}
#print (imageTypes)
#creating a folder for the downloadedImages
if not os.path.exists(self.directory):
os.mkdir(self.directory)
#creating a folder for the current query
dir = os.path.join(self.directory, query)
#print (dir)
if not os.path.exists(dir):
os.mkdir(dir)
# for i in range(0,len(ActualImages)) : for 100 image
for i in range(0,min(1,len(ActualImages))) :
metadataDict={}
data = ActualImages[i]
imageLink = data[0]
imageType = data[1]
metadataDict['type'] = imageType
#print (imageType)
if(len(imageType) > 0 and imageType in imageTypes) :
#print (imageType)
#print (i)
imageTypes[imageType]+=1
cnt = imageTypes[imageType]
try:
Image = ''
req = urllib.request.Request(imageLink, headers=self.header)
with urllib.request.urlopen(req) as response:
Image = response.read()
#req = request(imageLink, headers={'User-Agent': self.header})
#Image = urllib2.urlopen(req).read()
#creating the exact file path for the image
metadataDict['path'] = os.path.join(dir, imageType + "_" + str(cnt) + "." + imageType)
f = open(os.path.join(dir, imageType + "_" + str(cnt) + "." + imageType), 'wb')
# print dir
f.write(Image)
f.close()
metadata.append(metadataDict)
except Exception as e:
print ("could not load : " + imageLink)
#print (e)
else:
imageType = 'jpg'
metadataDict['type'] = imageType
#print (imageType)
#print (i)
imageTypes[imageType] += 1
cnt = imageTypes[imageType]
try:
#req = requests.get(imageLink,headers = {'User-Agent': self.header})
#req = urllib.Request(imageLink, headers={'User-Agent': self.header})
#Image = urllib2.urlopen(req).read()
Image = ''
req = urllib.request.Request(imageLink, headers=self.header)
with urllib.request.urlopen(req) as response:
Image = response.read()
# creating the exact file path for the image
metadataDict['path'] = os.path.join(dir, imageType + "_" + str(cnt) + "." + imageType)
f = open(os.path.join(dir, imageType + "_" + str(cnt) + "." + imageType), 'wb')
# print dir
f.write(Image)
f.close()
metadata.append(metadataDict)
except Exception as e:
print ("could not load : " + imageLink)
# print (e)
return metadata
def downloadImagesFromSearch(self,query):
"""
performs all the tasks invovlved in downloading images like getting html of results page and then parsing the html and extracting img links and
finally to download the images
:param query(str): query string for image
:return:
imageLinksList(list) : a list of image url strings
metdata(list) : metadata of the images
"""
query = query.split()
query = '+'.join(query)
prettyHtml = self.getHtml(query)
imageLinksList = self.extractImagesFromHtml(prettyHtml)
#print (len(imageLinksList))
#print (imageLinksList)
if len(imageLinksList) == 0 :
return imageLinksList,[]
metadata = self.downloadImages(imageLinksList,query)
#print ('printing metadata of downloaded images ')
#print (metadata)
return imageLinksList[:1],metadata
def getHtml(self,query):
"""
gets the html from the google search results page
:param query(str): query string
:return: returns the beautiful soup version of html of the search results page
"""
#print(query)
#print (query.split()[0])
url = "https://www.google.co.in/search?q=" + query + "&source=lnms&tbm=isch"
#print (url)
return self.get_soup(url)
#print(html)
def main():
downloads = DownloadImagesService()
query = "harry potter"
downloads.downloadImagesFromSearch(query)
if __name__ == '__main__':
main()
|
'''
leetcode - 62 - unique paths - https://leetcode.com/problems/unique-paths/
time complexity - O(2^N*2)
approach - recursive approach
'''
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
i=0
j=0
return self.helper(0,0,m,n)
def helper(self,i,j,m,n):
#base case
if (i==m-1 and j==n-1): return 1
if (i>=m or j>=n): return 0
#logic
right=self.helper(i,j+1,m,n)
bottom=self.helper(i+1,j,m,n)
return right+bottom
'''
Approach - DP - bottom-up
Time complexity - O(M*N)
space complexity - O(M*N)
'''
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
#dp =[[ for _ in range(n+1)] for _ in range(m+1)]
dp = [[0]*(n+1) for _ in range(m+1)]
dp[m-1][n-1]=1
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
if (i==m-1 and j==n-1): continue
dp[i][j]=dp[i+1][j]+dp[i][j+1]
return dp[0][0]
''''
Approach - DP - Tom bottom
'''
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[1]*(n) for _ in range(m)]
for i in range(1,m):
for j in range(1,n):
dp[i][j]=dp[i-1][j]+dp[i][j-1]
return dp[m-1][n-1]
|
# 문제 :
# 생일을 입력하면 태어난 연도의 띠를 리턴해주는 함수
#
# 힌트:
# 1980년도는 원숭이 띠입니다.
# 쥐 – 소 – 호랑이 – 토끼 – 용 – 뱀 – 말 – 양 – 원숭이 – 닭 – 개 – 돼지
띠 = ['쥐', '소', '호랑이', '토끼', '용', '뱀', '말', '양', '원숭이', '닭', '개', '돼지']
def zodiac_sign(birthday):
year = birthday.split('-')[0]
return f'{year}는 {띠[(int(year)+8) % 12]}의 해입니다.'
#
# animal = ['원숭이', '닭', '개', '돼지', '쥐', '소', '호랑이', '토끼', '용', '뱀', '말', '양']
# arr = ""
# num = 0
# for i in birthday:
# if i == "-":
# break
# arr += i
# num = int(arr)%12
# return arr+"년도는 "+animal[num]+"의 해입니다."
# 함수 호출 코드:
print(zodiac_sign("1990-10-21"))
print(zodiac_sign("1999-10-21"))
print(zodiac_sign("2003-10-21"))
# 실행결과:
# 1990년도는 말의 해 입니다.
# 1999년도는 토끼의 해 입니다.
# 2003년도는 양의 해 입니다.
|
def phonenumber_to_region(phone):
phone_numbers = {"02": "서울", "051": "부산", "053": "대구", "032" : "인천",
"062": "광주", "042": "대전", "052": "울산", "044": "세종",
"031": "경기", "033": "강원", "043": "충북", "041": "충남",
"063": "전북", "061": "전남", "054": "경북", "055": "경남",
"064": "제주", "010":"휴대전화", "070":"인터넷전화"}
phoneNum = "".join(phone.split("-"))
phones=""
for i in range(3):
phones += phoneNum[i]
for key, val in phone_numbers.items():
if("02" in phones):
return "서울"
if(phones == key):
return val
r1 = phonenumber_to_region("010-2357-9607")
r2 = phonenumber_to_region("062-872-4071")
r3 = phonenumber_to_region("031-872-4071")
print(r1)
print(r2)
print(r3) |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 09:25:22 2020
@author: Amarnadh
"""
x=[False,False,False,False]
print("all=",all(x)) #if any one value is false, then it retursn false
print("any=",any(x)) #if any one value is true, then it retursn true
print("ASCII char is ",chr(65)) #returns character of ASCII value
print("ord('A')=",ord('A')) #returns ASCII value of character
print("divmod 50/2 is ",divmod(50,2)) #returns quotient and remainder
print("id(2)=",id(2)) #gives the address of a number or variable
print("type(5)=",type(5))# returns the class to which the instance of obj belongs to
print("type(5.2)=",type(5.2))
print("isinstance=",isinstance(5.2,float))#returns bool value if obj is instance of a class or not
print("isinstance=",isinstance(5.5,int))
x = iter(["sachin", "dhoni", "virat"])#returns an iterator object
print(next(x),next(x),next(x)) #returns the next elm reported by iterator
x = iter([10, 20, 30])#returns an iterator object
print(next(x),next(x),next(x))
print("len('GITAM')=",len("GITAM"))#returns length of string or list
n=[100,200,300,400]
print("len(n)=",len(n))
print("max=",max(n))# returns max value
print("min=",min(n))# returns min value
print("pow(4,2)=",pow(4,3)) #returns 4 power 2
print("pow(5,3,2)=",pow(5,3,2)) #returns (5 power 3) mod 2
r=reversed([100,200,300,400])#reversed used to reverse the list
for i in r:
print(i,end=' ')
print("\n",abs(-2)) #Gives a positive number
print("round(2.6789)=",round(2.6789))#returns the nearest value
print("round(2.6789,2)=",round(2.6789,2))#returns the value rounded to the nearest 10 pow -2
s=sorted([1,3,2,5,4,0])# used to sort the list in sequential order
for i in s:
print(i,end=' ')
print()
print("sum(s)=",sum(s))
fp=open("hi.txt","r")#used to open the file with given name and access mode
r=input("Enter a value") #reads the input value in the form of string
print("r=",r)#used to print the values
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 25 00:22:04 2020
@author: Amarnadh
"""
x=[10,20,30,40,50]
print("x=",x)
y=x
y+=[60,70] #in list this expression acts like a reference to list 'x'
print("x=",x)
y=y+[80,90]#in this case, it doesnt acts lika a reference to the list 'x'
print("x=",x)
print("y=",y)
a=3
a+=1
print(a) |
import timeit
from time import sleep
# def maopao_sort(alist):
# """mao pao pai xv"""
# for cm in range(len(alist)-1,0,-1):
# for cn in range(cm):
# if alist[cn]>alist[cn+1]:
# temp = alist[cn+1]
# alist[cn+1] = alist[cn]
# alist[cn] = temp
def maopao_sort():
"""mao pao pai xv"""
a = [11,12,20,10,9,8,7,30,6,5,4,3,2,1,40,1200,400,500,4210,78129,12984,0]
for cm in range(len(a)-1,0,-1):
for cn in range(cm):
if a[cn]>a[cn+1]:
temp = a[cn+1]
a[cn+1] = a[cn]
a[cn] = temp
def k_maopao_sort():
"""k mao pao pai xv"""
a = [11,12,20,10,9,8,7,30,6,5,4,3,2,1,40,1200,400,500,4210,78129,12984,0]
passnum = len(a) -1
exchange = True
while passnum >0 and exchange:
exchange = False
for cn in range(passnum):
if a[cn]>a[cn+1]:
exchange = True
temp = a[cn+1]
a[cn+1] = a[cn]
a[cn] = temp
passnum -=1
def selection_sort():
"""xuan ze pai xv"""
a = [11,12,20,10,9,8,7,30,6,5,4,3,2,1,40,1200,400,500,4210,78129,12984,0]
for cm in range(len(a)-1,0,-1):
position_max = 0
for location in range(1,cm+1):
if a[location]>a[position_max]:
position_max = location
temp = a[cm]
a[cm] = a[position_max]
a[position_max] = temp
def insertion_sort():
"""cha ru pai xv"""
a = [11,12,20,10,9,8,7,30,6,5,4,3,2,1,40,1200,400,500,4210,78129,12984,0]
for index in range(1,len(a)):
current_value = a[index]
position = index
while position > 0 and a[position-1]>current_value:
a[position] = a[position-1]
position = position -1
a[position] = current_value
def shell_sort():
"""shell sort pai xv"""
a = [11,12,20,10,9,8,7,30,6,5,4,3,2,1,40,1200,400,500,4210,78129,12984,0]
sublist_count = len(a)//4
while sublist_count > 0:
for start_position in range(sublist_count):
#print(str(start_position)+","+str(sublist_count))
gap_insertion_sort(a,start_position,sublist_count)
sublist_count = sublist_count//4
return a
def gap_insertion_sort(a,start_position,sublist_count):
"""gap insertion sort"""
for index in range(start_position+sublist_count,len(a),sublist_count):
current_value = a[index]
position = index
#print(str(index))
while position >= sublist_count and a[position-sublist_count]>current_value:
a[position] = a[position-sublist_count]
position = position -sublist_count
a[position] = current_value
a = [11,12,20,10,9,8,7,30,6,5,4,3,2,1,40,1200,400,500,4210,78129,12984,0]
T1 = timeit.Timer("maopao_sort()","from __main__ import maopao_sort")
T2 = timeit.Timer("k_maopao_sort()","from __main__ import k_maopao_sort")
T3 = timeit.Timer("selection_sort()","from __main__ import selection_sort")
T4 = timeit.Timer("insertion_sort()","from __main__ import insertion_sort")
T5 = timeit.Timer("shell_sort()","from __main__ import shell_sort")
print("maopao: ",T1.timeit(10000))
print("K—maopao: ",T2.timeit(10000))
print("selection: ",T3.timeit(10000))
print("insertion: ",T4.timeit(10000))
print("shell: ",T5.timeit(10000))
|
# -*- coding: utf-8 -*-
# python栈的实现
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
# s = Stack()
#
# s=Stack()
#
# print(s.isEmpty())
# s.push(4)
# s.push('dog')
# print(s.peek())
# s.push(True)
# print(s.size())
# print(s.isEmpty())
# s.push(8.4)
# print(s.pop())
# print(s.pop())
# print(s.size())
# 括号匹配
def parChecker(symbol):
s = Stack()
balanced = True
index = 0
while balanced and index < len(symbol):
x = symbol[index]
if x == '(':
s.push(x)
else:
if s.isEmpty():
balanced = False
else:
s.pop()
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
# print(parChecker('(((())))'))
# print(parChecker('(((()))))'))
# 符号匹配
def parChecker2(symbol):
s = Stack()
balanced = True
index = 0
while balanced and index < len(symbol):
x = symbol[index]
if x in '([{':
s.push(x)
else:
if s.isEmpty():
balanced = False
else:
top = s.pop()
if not matches(top, x):
balanced = False
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
def matches(open, close):
opens = "([{"
closers = ")]}"
return opens.index(open) == closers.index(close)
# print(parChecker2('{{([][])}()}'))
# print(parChecker2('[{()]'))
# 十进制转二进制
def divideBy2(decNumber):
s = Stack()
while decNumber > 0:
rest = decNumber % 2
s.push(rest)
decNumber = decNumber // 2
binString = ""
while not s.isEmpty():
binString = binString + str(s.pop())
return binString
# print(divideBy2(142857))
# 改进,变成十进制转换为任何进制(2~16)
def divideByn(decNumber, base):
digits = "0123456789ABCEDF"
s = Stack()
while decNumber > 0:
rest = decNumber % base
s.push(rest)
decNumber = decNumber // base
binString = ""
while not s.isEmpty():
binString = binString + digits[s.pop()]
return binString
# print(divideByn(123456789, 16)) |
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initialise the CNN
classifier = Sequential()
# 1. Add Convolution layer - this describes the feature maps, args = no. of features, rows, columns
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
# 2. Add Pooling layer - this reduces the size of the feature maps
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Add second Convolution layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# 3. Add Flattening layer - take pooled feature map and flatten it to single dimension
classifier.add(Flatten())
# 4. Construct an ANN for training with the above layers
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting CNN to Images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory(
'Datasets/Convolutional_Neural_Networks/dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory(
'Datasets/Convolutional_Neural_Networks/dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
classifier.fit_generator(
training_set,
steps_per_epoch=8000,
epochs=25,
validation_data=test_set,
validation_steps=2000) |
import datetime
from calendar import monthrange
#*******************************************************************
# Extract something bounded by <string></string>
# tag is not decorated with "<" or ">" or "/"
# The opening tag is assumed to be of the form "<tag...>" (where "..." is random stuff)
# The closing tag is assumed to be "</tag>"
# String will be treated in a case-insensitive way
def ExtractTaggedStuff(string, start, tag):
begin=string.lower().find("<"+tag.lower(), start)
if begin < start:
return None
# Now find the closing ">" for the opening tag.
begin=string.find(">", begin)
if begin == -1:
return None
begin += 1 # Need to skip over the ">"
end=string.lower().find("</"+tag.lower()+">", begin)
if end < begin:
return None
# We return a tuple, containing the string found and the ending position of the string found in the input string
return string[begin:end], end + len(tag) + 3
# ---------------------------------------------------------------------
def Date(year, month, day):
if day is None or month is None or year is None:
return None
# We want to deal with days that are just outside the month's range -- anything more than about 10 days is probably not deliberate,
# but some sort of parsing error feeding in garbage data.
# First deal with dates later than the month's range
dayrange=monthrange(year, month)
if dayrange[1] < day < 40:
day=day-dayrange[1]
month += 1
if month > 12:
month=month-12
year += 1
# Now deal with days before the start of the month
if 1 > day > -10:
month += 1
if month < 1:
month=12
year=year-1
dayrange=monthrange(year, month)
day=dayrange[1]-day
# Returning you now to your mundane date function...
return datetime.datetime(year, month, day).date()
# ---------------------------------------------------------------------
def InterpretInt(intstring):
try:
return int(intstring)
except:
return None
#---------------------------------------------------------------------
def InterpretYear(yearstring):
# Remove leading and trailing cruft
cruft=['.']
while len(yearstring) > 0 and yearstring[0] in cruft:
yearstring=yearstring[1:]
while len(yearstring) > 0 and yearstring[:-1] in cruft:
yearstring=yearstring[:-1]
# Handle 2-digit years
if len(yearstring) == 2:
year2=InterpretInt(yearstring)
if year2 is None:
return None
if year2 < 30: # We handle the years 1930-2029
return 2000+year2
return 1900+year2
# 4-digit years are easier...
if len(yearstring) == 4:
return InterpretInt(yearstring)
return None
#---------------------------------------------------------------------
def InterpretMonth(monthstring):
monthConversionTable={"jan" : 1, "january" : 1, "1" : 1,
"feb" : 2, "february" : 2, "2" : 2,
"mar" : 3, "march" : 3, "3" : 3,
"apr" : 4, "april" : 4, "4" : 4,
"may" : 5, "5" : 5,
"jun" : 6, "june" : 6, "6" : 6,
"jul" : 7, "july" : 7, "7" : 7,
"aug" : 8, "august" : 8, "8" : 8,
"sep" : 9, "sept" : 9, "september" : 9, "9" : 9,
"oct" : 10, "october" : 10, "10" : 10,
"nov" : 11, "november" : 11, "11" : 11,
"dec" : 12, "december" : 12, "12" : 12,
"1q" : 1,
"4q" : 4,
"7q" : 7,
"10q" : 10,
"winter": 1,
"spring" : 4,
"summer" : 7,
"fall" : 10, "autumn" : 10,
"january-february" : 2,
"january/february" : 2,
"winter/spring" : 3,
"march-april" : 4,
"april-may" : 5,
"apr-may" : 5,
"may-june" : 6,
"july-august" : 8,
"august-september" : 9,
"september-october" : 10,
"sep-oct" : 10,
"october-november" : 11,
"oct-nov" : 11,
"september-december" : 12,
"november-december" : 12,
"december-january" : 12,
"dec-jan" : 12}
try:
return monthConversionTable[monthstring.replace(" ", "").lower()]
except:
return None
#-----------------------------------------------------
# Handle dates like "Thanksgiving"
# Returns a month/day tuple which will often be exactly correct and rarely off by enough to matter
# Note that we don't (currently) attempt to handle moveable feasts by taking the year in account
def InterpretNamedDay(dayString):
namedDayConverstionTable={
"unknown": (1, 1),
"unknown ?": (1, 1),
"new year's day" : (1, 1),
"edgar allen poe's birthday": (1, 19),
"edgar allan poe's birthday": (1, 19),
"groundhog day": (2, 4),
"canadian national flag day": (2, 15),
"national flag day": (2, 15),
"chinese new year": (2, 15),
"lunar new year": (2, 15),
"leap day": (2, 29),
"st urho's day": (3, 16),
"st. urho's day": (3, 16),
"saint urho's day": (3, 16),
"april fool's day" : (4, 1),
"good friday": (4, 8),
"easter": (4, 10),
"national garlic day": (4, 19),
"world free press day": (5, 3),
"cinco de mayo": (5, 5),
"victoria day": (5, 22),
"world no tobacco day": (5, 31),
"world environment day": (6, 5),
"great flood": (6, 19), # Opuntia, 2013 Calgary floods
"summer solstice": (6, 21),
"world wide party": (6, 21),
"canada day": (7, 1),
"stampede": (7, 10),
"stampede rodeo": (7, 10),
"stampede parade": (7, 10),
"system administrator appreciation day": (7, 25),
"apres le deluge": (8, 1), # Opuntia, 2013 Calgary floods
"international whale shark day": (8, 30),
"labor day": (9, 3),
"labour day": (9, 3),
"(canadian) thanksgiving": (10, 15),
"halloween": (10, 31),
"remembrance day": (11, 11),
"rememberance day": (11, 11),
"thanksgiving": (11, 24),
"before christmas december": (12, 15),
"saturnalia": (12, 21),
"winter solstice": (12, 21),
"christmas": (12, 25),
"christmas issue": (12, 25),
"christmas issue december": (12, 25),
"xmas ish the end of december": (12, 25),
"boxing day": (12, 26),
"hogmanay": (12, 31),
"auld lang syne": (12, 31),
}
try:
return namedDayConverstionTable[dayString.lower()]
except:
return None
#-----------------------------------------------------------------------
# Deal with situtions like "late December"
# We replace the vague relative term by a non-vague (albeit unreasonably precise) number
def InterpretRelativeWords(daystring):
conversionTable={
"start of": 1,
"early": 8,
"early in": 8,
"mid": 15,
"middle": 15,
"?": 15,
"middle-late": 19,
"late": 24,
"end of": 30,
"the end of": 30,
"around the end of": 30
}
try:
return conversionTable[daystring.replace(",", " ").replace("-", " ").lower()]
except:
return None
#---------------------------------------------------
# Try to make sense of a date string which might be like "10/22/85" or like "October 1984" or just funky randomness
def InterpretDate(dateStr):
dateStr=dateStr.strip() # Remove leading and trailing whitespace
# Some names are of the form "<named day> year" as in "Christmas, 1955" of "Groundhog Day 2001"
ds=dateStr.replace(",", " ").replace("-", " ").lower().split() # We ignore hyphens and commas
if len(ds) > 1:
year=InterpretYear(ds[len(ds)-1])
if year is not None: # Fpr this case, the last token must be a year
dayString=" ".join(ds[:-1])
dayTuple=InterpretNamedDay(dayString)
if dayTuple is not None:
return Date(year, dayTuple[0], dayTuple[1])
# Case: late/early <month> <year> ("Late October 1999")
# We recognize this by seeing three or more tokens separated by whitespace, with the first comprising a recognized string, the second-last a month name and the last a year
ds = dateStr.replace(",", " ").replace("-", " ").lower().split()
if len(ds) >= 3:
if len(ds) > 3: # If there's more than one early token, recombine just the early tokens.
temp=" ".join(ds[:-2])
ds=(temp, ds[len(ds)-2], ds[len(ds)-1])
day=InterpretRelativeWords(ds[0])
if day is not None:
month = InterpretMonth(ds[1])
year = InterpretYear(ds[2])
if month is not None and year is not None:
return Date(year, month, day)
# Case: <Month> <year> ("October 1984", "Jun 73", etc. Possibly including a comma after the month)
# We recognize this by seeing two tokens separate by whitespace, with the first a month name and the second a number
ds=dateStr.replace(",", " ").split()
if len(ds) == 2:
month=InterpretMonth(ds[0])
year=InterpretYear(ds[1])
if month is not None and year is not None:
return Date(year, month, 1)
# Case: mm/dd/yy or mm/dd/yyyy
ds=dateStr.split("/")
if len(ds) == 3:
day=InterpretInt(ds[1])
month=InterpretInt(ds[0])
year=InterpretInt(ds[2])
return Date(year, month, day)
# Case: October 11, 1973 or 11 October 1973
# We want there to be three tokens, the last one to be a year and one of the first two tokens to be a number and the other to be a month name
ds=dateStr.replace(",", " ").split()
if len(ds) == 3:
year=InterpretYear(ds[2])
if year is not None:
m0=InterpretMonth(ds[0])
m1=InterpretMonth(ds[1])
d0=InterpretInt(ds[0])
d1=InterpretInt(ds[1])
if m0 is not None and d1 is not None:
return Date(year, m0, d1)
if m1 is not None and d0 is not None:
return Date(year, m1, d0)
# Case: A 2-digit or 4-digit year by itself
year=InterpretYear(dateStr)
if year is None:
return None
try:
return Date(year, 1, 1)
except:
return None
#---------------------------------------------------
# Try to make sense of the date information supplied as separate
# Unknown input arguments should be None
def InterpretDayMonthYear(dayStr, monthStr, yearStr):
# Let's figure out the date
year=None
month=None
day=None
if yearStr is not None:
year = InterpretYear(yearStr)
if year is None:
print(" ***Can't interpret year '"+yearStr+"'")
return None
if monthStr is not None:
month = InterpretMonth(monthStr)
if month is None:
print(" ***Can't interpret month '" + monthStr + "'")
if dayStr is not None:
day = int(dayStr)
if day is None:
print(" ***Can't interpret day '" + dayStr + "'")
day = day or 1
month = month or 1
return Date(year, month, day)
#--------------------------------------------------------------------
# Strip the hyperlink stuff from around its display text
def SeparateHyperlink(text):
# <A ...HREF=...>display text</A>
# We'll do this the quick and dirty way and assume that '<' and '>' are not used except in the html
text=text.strip()
if text is None or len(text) < 8: # Bail if it's too short to contain a hyperlink
return None
if text[0:2].lower() != "<a": # Bail if it doesn't start with "<A"
return None
if text[-4:].lower() != "</a>": # Bail if it doesn't end with "</A>"
return None
loc=text.find(">") # Find the ">" which ends the opening part of the HTML
if loc < 0:
return None
# OK, it looks like this is a hyperlink. Extract the HREF
# The text we want begins with 'href="' and end with '"'
hypertext=text[:loc]
loc_href=hypertext.lower().find("href=")
if loc_href < 0:
return None
loc_quote1=hypertext.find('"', loc_href+1) # This should find the start of the url
if loc_quote1 < 0:
return None
loc_quote2=hypertext.find('"', loc_quote1+1)
if loc_quote2 < 0:
return None
hypertext=hypertext[loc_quote1+1:loc_quote2]
# Now extract the display text and replace ' ' with spaces
displayText = text[loc + 1:-4]
displayText.replace(" ", " ")
return (hypertext, displayText)
#----------------------------------------------------------------------
# Get the index of an entry in a list or return None
def GetIndex(list, str):
try:
return list.index(str)
except:
return None |
from Tkinter import *
#from Tkinter import messagebox
top = Tk()
top.geometry("{0}x{1}+0+0".format(top.winfo_screenwidth(), top.winfo_screenheight()))
t1 = Button(top, text = "", bg = "Yellow")
t1.place(x = 50, y = 50)
top.mainloop()
|
# loop
# for loop
# find the min
# place in the front
integerList = [9,4,18,3,8,66,9,11]
def insert(list,src,dest):
# src: the index of which to be inserted
# dest: the index of where to insert in
a = list[src]
for i in range(src-1,dest-1,-1):
list[i+1] = list[i]
list[dest] = a
return list
def insertionSort(list):
for i in range(0,len(list)):
for j in range(0,i):
if list[i]<list[j]:
list = insert(list,i,j)
return list
|
"""
This program help work with some kind of JSON data sample and collate out the needed
set of key->values into a specified file format to save into.
"""
import json
from random import randint
def collate_json_values_to_file():
with open('file.json', 'r') as o:
file_object = json.load(o)
with open('output.txt', 'w') as output:
for person in file_object:
output.write(person['first_name'] + ' ' + person['last_name'] + '\n')
print('Done')
write_heading = False
csv_heading = []
outputfilename = str(randint(0, 100000)) + 'result.csv'
def convert_json_to_csv():
global write_heading, outputfilename
json_file = input('Enter JSON file name to convert: ')
try:
print("====================================================================================")
print("Program Starting...")
with open(str(json_file), 'r') as o:
file_object = json.load(o)
print("Json file given loaded...")
with open(outputfilename, 'a') as result:
print("Output csv file created...")
if not write_heading:
for head in file_object[0].keys():
result.write(head + ',')
csv_heading.append(str(head))
print("CSV heading title appended to the output file...")
write_heading = True
print("Started dumping json values to the CSV file...")
for obj in file_object:
result.write('\n')
for csv_head in csv_heading:
result.write(str(obj[csv_head]) + ',')
# result.write('\n' + str(obj['user_id']) + ','+ obj['first_name'] + ',' + obj['last_name'])
print('Program completed successfully! with file name of' + outputfilename)
print("====================================================================================")
except FileNotFoundError:
print("File not found program exit!")
convert_json_to_csv()
|
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> word = 'banana'
>>> count = 0
>>> for letter in word:
if letter == 'a':
count = count + 1
>>> print(count)
3
>>> word = 'banana'
>>> print(count('a'))
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print(count('a'))
TypeError: 'int' object is not callable
>>> word = 'banana'
>>> print(count('a')in('banana'))
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print(count('a')in('banana'))
TypeError: 'int' object is not callable
>>> count('a').print('banana')
SyntaxError: invalid syntax
>>> print(count('a'))
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print(count('a'))
TypeError: 'int' object is not callable
>>> print(word.count('a'))
3
>>>
|
from math import exp, pi, sqrt
def get_criteria_dict_and_criteria_count(csv_data):
"""
Analyse data in file and delete all non-usable stuff
:param csv_data:
:return: count of criterias in dict and dict of criterias
"""
criteria_dict = {}
criteria_count = 0
for key in csv_data:
if key[0] == 'Q': # As we discussed before, all criteria names should start with Q
criteria_dict[key] = csv_data[key]
criteria_count += 1
criteria_dict[key] = list(map(int, criteria_dict[key]))
return criteria_count, criteria_dict
def get_sum_on_criteria_dict(criteria_dict):
"""
:param criteria_dict:
:return: dictionary of marks' sum on a criteria
"""
sum_on_criteria = 0
sum_on_criteria_dict = {}
for key in criteria_dict:
for i in range(len(criteria_dict[key])):
sum_on_criteria += int(criteria_dict[key][i])
sum_on_criteria_dict[key] = sum_on_criteria
sum_on_criteria = 0
return sum_on_criteria_dict
def get_overall_average_mark(sum_on_criteria_dict, criteria_count):
"""
:param sum_on_criteria_dict:
:param criteria_count:
:return: average mark on criteria, it also equals to mathematical expectation on a criteria
"""
overall_sum = 0
for key in sum_on_criteria_dict:
overall_sum += int(sum_on_criteria_dict[key])
average_mark = overall_sum / criteria_count
return float("{:5.2f}".format(average_mark))
def get_squared_difference_sum(sum_on_criteria_dict, average_mark):
"""
This sum is for concordance and dispersion counting
:param sum_on_criteria_dict:
:param average_mark:
:return: sum of squared differences to average mark
"""
squared_difference_sum = 0.0
for key in sum_on_criteria_dict:
squared_difference_sum += ((int(sum_on_criteria_dict[key]) - float(average_mark)) ** 2)
return squared_difference_sum
def get_concordance(squared_difference_sum, expert_count, criteria_count):
"""
Concordance shows how agreed are experts' opinions to each other
:param squared_difference_sum:
:param expert_count:
:param criteria_count:
:return: concordance for used params
"""
concordance = (12 * squared_difference_sum) / ((expert_count ** 2) * ((criteria_count ** 3) - criteria_count))
return "{:2.2f}".format(concordance)
def split_blocks(criteria_dict):
"""
This is used to get blocks of criteria which are related to a certain question
:param criteria_dict:
:return: dictionary of blocks of criterias, where question is a primary key, and criteria with marks are secondary
"""
blocks_dict = {}
block = {}
header = ''
new_header = ''
first = True
i = 0
for criteria in criteria_dict: # Todo: refactor split_blocks, remove first and last
i += 1
for char in criteria:
if char != '_':
new_header += char
else:
break
if first:
header = new_header
first = False
if i == len(criteria_dict) - 1:
blocks_dict[header] = block
if new_header == header and new_header != '':
block[criteria] = criteria_dict[criteria]
new_header = ''
elif new_header != '' and new_header != header:
blocks_dict[header] = block
block = {criteria: criteria_dict[criteria]}
header = new_header
new_header = ''
elif new_header == '':
break
return blocks_dict
def get_average_on_criteria(criteria_dict, expert_count):
"""
average_on_criteria equals to mathematical expectation
:param criteria_dict:
:param expert_count:
:return: average_on_criteria_dict
"""
average_on_criteria_dict = {}
for criteria in criteria_dict:
average_on_criteria_dict[criteria] = float(sum(criteria_dict[criteria]) / expert_count)
return average_on_criteria_dict
def get_avg_squared_diff_and_dispersion(mark_list, average_on_criteria, expert_count):
"""
:return: sigma and squared sigma
"""
difference = {}
squared_difference = {}
for mark in mark_list:
difference[mark] = mark_list[mark] - average_on_criteria
squared_difference[mark] = difference[mark] ** 2
false_avg_squared_diff = sum(squared_difference) / expert_count
avg_squared_diff = false_avg_squared_diff * expert_count / (expert_count - 1)
dispersion = avg_squared_diff ** 2
return avg_squared_diff, dispersion
def get_gaussian_distribution(dispersion, avg_squared_diff, average_mark, criteria):
"""
In probability theory, a gaussian distribution is a type of continuous probability distribution for a rea-valued
random variable.
:return: gaussian_distribution_dict
"""
gaussian_distribution_list = []
for mark in criteria:
gaussian_distribution_list.append((1 / (avg_squared_diff * sqrt(2 * pi))) * exp(
((-1 * (criteria[mark] - average_mark)) ** 2) / 2 * dispersion))
return gaussian_distribution_list
# graphics can be built with imported libs
|
def checkConsecutivePowers(num):
sum = 0
numList=list(str(num)) # разбиваем число
for power,val in enumerate(numList): # присваем каждому числу индекс
sum+=pow(int(val),power+1) # находим сумму
if sum==num: # проверяем
return True
else:
return False
def sum_dig_pow(a, b): # range(a, b + 1) will be studied by the function
specialNums=[] # пустой список для вывода
for num in range(a,b+1): # последнее число включительно
if checkConsecutivePowers(num):
specialNums.append(num)
return specialNums
print(sum_dig_pow(15,15)) |
# Your parking gargage class should have the following methods:
# - takeTicket
# - This should decrease the amount of tickets available by 1
# - This should decrease the amount of parkingSpaces available by 1
# - payForParking
# - Display an input that waits for an amount from the user and store it in a variable
# - If the payment variable is not empty then (meaning the ticket has been paid) -> display a message to the user that their ticket has been paid and they have 15mins to leave
# - This should update the "currentTicket" dictionary key "paid" to True. The key is 'paid' and the value is 'true or false'
# - leaveGarage
# - If the ticket has been paid, display a message of "Thank You, have a nice day"
# - If the ticket has not been paid, display an input prompt for payment
# - Once paid, display message "Thank you, have a nice day!"
# - Update parkingSpaces list to increase by 1 (meaning add to the parkingSpaces list)
# - Update tickets list to increase by 1 (meaning add to the tickets list)
# You will need a few attributes as well:
# - tickets -> list
# - parkingSpaces -> list
# - currentTicket -> dictionary
class ParkingGarage():
'''
The ParkingGarage class creates a parking garage with a maximum of 10 parking spaces, represented in the parkingSpaces list.
Each parked car will appear in the designated location. The tickets list will correspond to the parked car's paid or unpaid ticket.
'''
def __init__ (self, tickets=[0,0,0,0,0,0,0,0,0,0], parkingSpaces=[0,0,0,0,0,0,0,0,0,0], currentTicket={'Paid': False}):
self.tickets = tickets
self.parkingSpaces = parkingSpaces
self.currentTicket = currentTicket
self.car_id = {}
def takeTicket(self):
'''
Asks user what car they want to park [car1-car10] and where they want to park [1-10]. The dictionary car_id keeps track of
all parked cars in the garage along with their unique index location for parkingSpaces and paid/unpaid status. Updates the tickets and
parkingSpaces list.
'''
user_car = input("To park and take a ticket, please choose a car: car1, car2,..., car10. \n").title()
user_parking = int(input("Where would you like to park? [1-10] \n"))
index = user_parking - 1
self.car_id[user_car] = [index, 'Unpaid'] # keeps track of all cars in the garage and their parked location (in index) and paid tickets
self.tickets[index] = 'Unpaid'
self.parkingSpaces[index] = user_car
return self.tickets, self.parkingSpaces, self.car_id
def payforParking(self):
'''
Asks user to identify their car, then asks the amount they would like to pay for that car. If the user pays the full amount, then
update the car_id dictionary to Paid status. If not, ask the user to pay more.
'''
remainder = 10
user_car = input("To pay for parking, please input your car number (car1, car2,..., car10) \n").title()
while True:
user_pay = input('Please pay for you parking ticket ($10) [exclude "$"]: \n')
ticket_amount_paid = int(user_pay)
remainder -= ticket_amount_paid
if remainder <= 0:
self.currentTicket['Paid'] = True
self.car_id[user_car][1] = 'Paid'
index = self.car_id[user_car][0]
self.tickets[index] = 'Paid'
print(f"You have paid the full amount for {user_car}. You have 15 minutes to leave the parking garage.")
break
else:
self.currentTicket['Paid'] = False
print(f'Please pay the remainder: ${remainder}')
print(f'The current parking status is: {self.parkingSpaces}')
print(f'The current ticket stauts is: {self.tickets}')
def leaveGarage(self):
'''
Asks user to identify their car, then checks if the user's car ticket is paid or unpaid. If paid, they can leave. If not,
run the payforParking method to have the user pay. Show the updated parking garage and ticket status at the end.
'''
user_car = input("To leave the garage, please input your car number (car1, car2,..., car10) \n").title()
if self.car_id[user_car][1] == 'Paid':
index = self.car_id[user_car][0]
self.parkingSpaces[index] = 0
self.tickets[index] = 0
del self.car_id[user_car]
print(f"Thank You {user_car}, have a nice day!")
print(f'The current parking status is: {self.parkingSpaces}')
print(f'The current ticket stauts is: {self.tickets}')
else:
print("You have an unpaid ticket. Please pay for your ticket to proceed.")
self.payforParking()
car = ParkingGarage()
car.takeTicket()
car.takeTicket()
car.takeTicket()
car.payforParking()
car.leaveGarage() |
#Generate a hailstone sequence
number = int(input("Enter a positive integer:"))
count = 0
print("Starting with number:", number)
print("Sequence is: ", end=' ')
while number > 1: #stops the sequence when we hit 1
if number%2: #don't be fooled by the 2, this means the number is odd!
number = number * 3 + 1
else:
number = number / 2
print(number,",", end=' ') #adds the number to the sequence
count += 1
else:
print() #just a blank line for a nicer output
print("Sequence is ", count, " numbers long")
|
import math
#let's start with defining the function that asks for input
def get_vertex():
x = float(input(" Please enter x: "))
y = float(input(" Please enter y: "))
return x,y
#for get_triangle we simply need to call get_vertex three times and adding a print to differentiate each one
def get_triangle():
print("First vertex")
x1,y1 = get_vertex()
print("Second vertex")
x2,y2 = get_vertex()
print("Third vertex")
x3,y3 = get_vertex()
return x1, y1, x2, y2, x3, y3
#this can also be written as return (x1,y1) , (x2,y2) , (x3, y3) to return a tuple (ch. 7.7)
#next we tackle side length. We need the math module in order to use the square root
def side_length(x1, y1, x2, y2):
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
#next we have to calculate the area of the triangle with Heron's formula, this function will need all 3 corners of the triangle
def calculate_area(x1, y1, x2, y2, x3, y3):
a = side_length(x1, y2, x2, y2)
b = side_length(x2, y2, x3, y3)
c = side_length(x3, y3, x1, y1)
s = (1/2) * (a + b + c)
return math.sqrt(s*(s-a) * (s-b) * (s-c))
x1, y1, x2, y2, x3, y3 = get_triangle()
area = calculate_area(x1, y1, x2, y2, x3, y3)
print("Area is ", area) |
def reverse(string):
string = string[::-1]
return string
s =input("enter a string")
print(reverse(s))
|
'''
programa que tenha uma tupla unica com nomes de produtos e seus
respectivos preços na sequencia
mostre uma listagem de preços organizando dados em forma tabular.
'''
listagem = ('Tenis',1.355, 'Camisa',245.25, 'Calca',600.12, 'Bermuda',52.15, 'Cinto',182.00,
'Meias',250.00, 'Jaqueta',1.255)
print('-'*41)
print(f'{"LISTAGEM DE PREÇO":=^41}') #centraliza o texto com quarenta espaços e preenche com (=).
print('-'*41)
for pos in range(0,len(listagem)):
if pos % 2 == 0:
print(f'{listagem[pos]:.<30}', end='') #insere trinta espaços a esquerda e preenche com (pontos).
else:
print(f' R$:{listagem[pos]:>7.2f}') #insere sete espaços a direita com 2 casas decimais
print('-'*41) |
#matriz
matriz = [[1,2,3],[4,5,6],[7,8,9]]
for x in matriz:
print(x,end='')
print('\n')
# -------------
matriz[0][0] = 'X'
matriz[1][1] = 'X'
matriz[2][2] = 'X'
matriz[0][1] = 0
matriz[0][2] = 0
matriz[1][0] = 0
matriz[1][2] = 0
matriz[2][0] = 0
matriz[2][1] = 0
print('-'*20)
for y in range(len(matriz)):
for z in range(len(matriz[y])):
print(matriz[y][z], end=' ')
print('\n') |
'''
http://www1.caixa.gov.br/loterias/loterias/lotofacil/lotofacil_pesquisa_new.asp
Obtem dados da web
<img src="/dolar_hoje/img/icon-moeda-2.png" alt="Dólar Comercial" title="Dólar Comercial">
<input type="text" value="3,81" class="text-verde" id="comercial" calc="sim">
https://www.melhorcambio.com/dolar-hoje
'''
import urllib.request
url = urllib.request.urlopen('https://www.melhorcambio.com/dolar-hoje').read()
url = str(url)
busca = '<input type="text" value="'
pos = int(url.index(busca) + len(busca) + 1022)
dolar = url[pos:pos + 4]
print('-+'*30)
print(f'Dolar hoje: R${dolar}') |
# teste laço While
'''n = 1
cont = 0
while n != 0:
n = int(input('Valor: '))
if n != 0:
cont += 1
print('FIM!', cont)'''
# leia a idade e o sexo de pessoas: - qts pessoas com mais de 18 anos -
# qts homens foram cadastrados - qts mulheres tem menos de 20 anos
cont = 1
idade = 0
contFinal = 0
nome = ' '
while True:
print(f'========={cont}ºPessoa=========')
#nome = input('Nome: ')
idade = int(input('Idade: '))
sexo = ' '
while sexo not in 'MF':
sexo = input('Sexo[M/F]: ').strip()[0].upper()
resp = ' '
while resp not in 'SN':
resp = input('Continuar? [S/N]').strip()[0].upper()
cont += 1
contFinal = cont - 1
if resp == 'N':
break
print(f'\n*** Foram cadastradas {contFinal} pessoas. ***')
print('='*30) |
#
#
#
valores = []
for cont in range(0,4):
valores.append(int(input('Valor: ')))
for i,v in enumerate(valores):
print(f'o valor {v} esta no indice {i}.')
print('OK!') |
__author__ = 'abdullahabdullah'
# --- Dictionaries ---
adres = {'Abdullah': 'yenisehir','Feride':'Uskudar'}
print(adres)
adresi = adres['Abdullah']
print(adresi)
print('Adresi : {}'.format(adresi))
#degisiklik
adres['Abdullah'] = 'Kadikoy'
print(adres)
# ekleme
adres['Ali'] = 'Uskudar'
print(adres)
# silme
del adres['Ali']
print(adres)
#print(adres['Abdullah'])
if 'Abdullah' in adres:
print(adres['Abdullah'])
print('beyoglu' in adres.values())
for liste in adres:
print('Kisi adi : {} ve adresi {}'.format(liste,adres[liste]))
# adres['Abdullah'] = Kadikoy
# liste = Abdullah
|
import sys
#Get string from input and encode to hex
html_string = (input()).encode('utf-8').hex()
#returns utf-8 encoded byte size
def utf8len(s):
return len(s.encode('utf-8'))
split_list = []
temp = ''
#Iterate over every character until a 80 byte data slice is made
for char in html_string:
if utf8len(temp)<80:
temp = temp+char
else :
split_list.append(temp)
temp = char
if temp != '':
split_list.append(temp)
for item in split_list:
print (item)
|
#!/usr/bin/python3
"""
script that takes in the name of a state as an argument
and lists all cities of that state,
using the database hbtn_0e_4_usa
"""
if __name__ == "__main__":
from sys import argv
import MySQLdb
usr = argv[1]
pswd = argv[2]
database = argv[3]
cityName = argv[4]
dbConnection = MySQLdb.connect(user=usr, passwd=pswd,
db=database, port=3306,
host="localhost")
cursr = dbConnection.cursor()
query = """SELECT cities.name FROM cities
WHERE state_id IN (SELECT states.id
FROM states WHERE name = %s);"""
cursr.execute(query, (cityName,))
cities = cursr.fetchall()
separator = ""
for city in cities:
print(separator, end="")
print(city[0], end="")
separator = ", "
print()
cursr.close()
dbConnection.close()
|
#!/usr/bin/python3
def search_replace(my_list, search, replace):
return ([replace if ele is search else ele for ele in my_list])
|
#!/usr/bin/python3
def text_indentation(text):
'''
This is the 5-text_indentation module
This function that prints a text with 2 new lines
after each of those characters: ., ? and :
There should be no space at the beginning or
at the end of each printed line
text must be a string, otherwise raise a TypeError exception
with the message text must be a string
'''
if(not isinstance(text, str) or text is None):
raise TypeError("text must be a string")
txt1 = text.replace('.', '.\n\n')
txt1 = txt1.replace('?', '?\n\n')
txt1 = txt1.replace(':', ':\n\n')
print("\n".join([txt2.strip() for txt2 in txt1.split("\n")]), end="")
|
#!/usr/bin/python3
def say_my_name(first_name, last_name=""):
"""
This is the say_my_name module
This is a function that prints My name is {first_name} {last_name}
"""
if (isinstance(first_name, str) is False or first_name is None):
raise TypeError("first_name must be a string")
if (isinstance(last_name, str) is False or last_name is None):
raise TypeError("last_name must be a string")
print("My name is {} {}".format(first_name, last_name))
|
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
while nums[i] != (i + 1) and nums[nums[i] - 1] != nums[i]:
value = nums[i] - 1
nums[i], nums[value] = nums[value], nums[i]
answer = []
for i in range(len(nums)):
if i != nums[i] - 1:
answer.append(nums[i])
return answer |
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.d = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
answer = []
for i, v in enumerate(self.d):
if v == target:
answer.append(i)
return random.choice(answer)
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target) |
num = int(input())
total = 0
for x in range(1, 11):
if x == len(str(num)):
total += (num - 10**(x - 1) + 1) * x
elif x < len(str(num)):
total += (9 * 10**(x - 1)) * x
else:
break
print(total)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
cache = {}
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.helper(root, 0, False)
def helper(self, node, total, choice):
if (node, total, choice) in cache:
return cache[(node, total, choice)]
if node:
v = node.val
if choice:
a = self.helper(node.left, 0, False)
b = self.helper(node.right, total, False)
cache[(node, total, choice)] = a + b
return a + b
else:
c = self.helper(node.left, total + v, True)
d = self.helper(node.right, 0, True)
e = self.helper(node.left, total, False)
f = self.helper(node.right, 0, False)
cache[(node, total, choice)] = max(c + d, e + f)
return max(c + d, e + f)
else:
return total
|
"""
@author: Brando Sánchez BR7
@Version: 12/03/19
INSTITUTO POLITÉCNICO NACIONAL
ESCUELA SUPERIOR DE CÓMPUTO
CRYPTOGRAPHY
"""
def main():
base = 50321
exp = 60749
modN = 77851
result = squareAndMultiply(base, exp, modN)
print(str(base) + " to " + str(exp) + " mod " + str(modN) + " is " + str(result))
def squareAndMultiply(base, exp, modN):
expBin = str(bin(exp)[2:])
z=1
for i in range(len(expBin)-1, -1, -1):
"""
print(i)
print(expBin[len(expBin)-1-i])
"""
z = z * z % modN
if expBin[len(expBin)-1-i] == '1':
z = z * base % modN
"""
print(z)
print()
"""
return z
|
temp = list() # lista temporária, usada pra guardar input do usuário
par = list()
impar = list()
lista = par,impar # movendo listas par e impar para Lista
for i in range(0,7): # Entrada do usuário
temp.append(int(input('Insira um número: ')))
for i in temp: # Validação de par/impar
if i % 2 == 0:
lista[0].append(i)
else:
lista[1].append(i)
# Organizando as listas em ordem crescente
par.sort()
impar.sort()
print(f'Resultado: {lista}') |
import json
from pprint import pprint
with open('swjson.json') as data_file:
data = json.load(data_file)
contador=0
print("Ahora listará las naves que aparezcan en el episodio que quieras")
episodio=input("Introduzca el número del episodio: ")
listapelis=[]
for pelicula in data ["results"]:
for titulo in pelicula["films"]:
if titulo["id"] not in listapelis:
listapelis.append(titulo["id"])
if episodio not in listapelis:
print("Pelicula inexistente")
else:
for nave in data["results"]:
for pelicula in nave["films"]:
if pelicula["id"]==episodio:
nombre=pelicula["title"]
contador=contador+1
print(nave["name"])
print("El total de naves en",nombre,"son",contador) |
import json, time
from pprint import pprint
with open('ej3.json') as data_file:
data = json.load(data_file)
nombremun=input("Introduzca un municipio: ")
for provincia in data["lista"]["provincia"]:
nombreprov=provincia["nombre"]["__cdata"]
if type(provincia["localidades"]["localidad"])==list:
for municipio in provincia["localidades"]["localidad"]:
if nombremun==municipio["__cdata"]:
print(nombremun, "pertenece a la provincia de",nombreprov)
break
else:
if nombremun==municipio["__cdata"]:
print(nombremun, "pertenece a la provincia de",nombreprov)
break |
import json
from pprint import pprint
with open('books.json') as data_file:
data = json.load(data_file)
cadena=input("Introduzca la cadena por la que quiere buscar el titulo: ")
for libro in data['bookstore']['book']:
if libro["title"]["__text"].startswith(cadena):
print("Titulo:",libro["title"]["__text"],'\n'
"Año:",libro["year"]) |
#! python3
"""
A function that takes a string and does the same thing as the strip()
string method. If no other arguments are passed other than the string to
strip, then whitespace characters will be removed from the beginning and
end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string. And then return stripped string
"""
import re
def stripMe(strings, characters=None):
if characters == None:
return re.sub(r"\s*(.*)\b\s*", r"\1", strings)
else:
return re.sub(r"[" + characters + "]", "", strings)
|
#! python3
"""
a program that opens all .txt files in a folder and searches for any
line that matches a user-supplied regular expression. The results should
be printed to the screen.
"""
import os, re
print("Whats is the path of the folder?")
path = r"{}".format(input())
print("What is the regex pattern?")
pattern = r"{}".format(input())
# remember if you don't want to join the dirname and filename use chdir
# if you don't want to then join them in that open method os.path.join(path, file)
os.chdir(path)
files = os.listdir(path)
lines = []
for file in files:
if file[-4:] == ".txt":
textFile = open(file) # <---- join them here
text = textFile.read()
textFile.close()
linya = re.finditer(r"{}".format(pattern), text)
for match in linya:
lines.append(match.group())
print(lines)
|
"""
Implement a method to perform basic string compression using the counts
of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the
"compressed" string would not become smaller than the original string, your method should return
the original string. You can assume the string has only uppercase and lowercase letters (a - z).
"""
def compressor(string):
"""
:param string: string
:return: string
"""
if not string:
return ''
solution = []
focus = string[0]
count = 0
for _ in string:
if _ != focus:
solution.append(f'{focus}{count}')
count = 0
focus = _
count += 1
solution.append(f'{focus}{count}')
return ''.join(solution)
print(compressor('aaaahhhhhssss'))
|
"""
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: If implementing in Java, please use a character array so that you can
perform this operation in place.)
"""
def urlify(url):
"""
:param url: string
:return: string
"""
broken_url = url.split(' ')
return '%20'.join(broken_url)
print(urlify('Mr John Smith'))
|
list = [1,2,4,6,8]
target = 9
for i,j in enumerate(list):
if target - j in list:
print(i)
for i in range(len(list)):
for j in range(len(list)):
if list[i] + list[j] == target:
print(i,j) |
import os
#EMPIEZA LA CLASE
class Libro:
titulo = ''
autor = ''
#1º METODO PARA GUARDAR
def guardar(self):
self.titulo = input("Indica el título de un libro: ")
self.autor = input("Indica el autor: ")
f = open("text.txt", "r")
lectura=f.read()
resultado=lectura.find(self.titulo)
if resultado<0:
print("no existe")
f = open("text.txt", "a")
f.write(self.titulo + "-")
f.write(self.autor + "\n")
else:
print("libro ya existe")
f.close()
def consultar(self):
f = open("text.txt", "r")
print(f.read())
def validar(self):
f = open("text.txt")
def eliminar(self):
self.titulo = input("Indica el título de un libro: ")
f = open("text.txt", "r")
lineas = f.readlines()
f.close()
f = open("text.txt","w")
for linea in lineas:
if linea!= self.titulo +"\n":
f.write(linea)
f.close()
|
import random
import math
def isCoPrime(i,z):
if(math.gcd(i,z)==1 and i!=z):
return True
return False
def isPrime(x):
if x >= 2:
for y in range(2, x):
if not (x % y):
return False
else:
return False
return True
primes = [i for i in range(1,1000) if isPrime(i)]
p = random.choice(primes)
q= random.choice(primes)
print("Value of p:",p)
print("Value of q:",q)
n=p*q
z=(p-1)*(q-1)
coprimes = [i for i in range(1,z) if isCoPrime(i,z)]
e = random.choice(coprimes)
print("Public key("+str(n)+","+str(e)+")")
for i in range(1,z):
if(i*e%z==1):
d=i
print("Private key(d)=",d)
messl=[]
asc=[]
en=[]
de=[]
enS=""
message=input("Enter message")
for i in message:
messl.append(i)
for i in messl:
asc.append(ord(i))
for i in asc:
en.append(pow(i,e)%n)
for i in en:
de.append(chr(pow(i,d)%n))
enS += str(i)
deS="".join(de)
print("Original Message")
print(message)
print("Encrypted message")
print(enS)
print("Decrypted message")
print(deS)
|
#Algorithm to win is n n e e s s
#https://github.com/liljag/tileTraveller
#import os, sys
x, y = 1, 1
#print("You can travel: (N)orth.")
N = True
S = False
E = False
W = False
win = False
while(win == False):
string = ''
if(N == True):
string = string+ '(N)orth'
if(E==True):
string = string + ' or (E)ast'
if(S==True):
string=string+ ' or (S)outh'
if(W==True):
string = string+ ' or (W)est'
elif(E==True):
string = string+'(E)ast'
if(S==True):
string=string+ ' or (S)outh'
if(W==True):
string = string+ ' or (W)est'
elif(S==True):
string = string+ '(S)outh'
if(W==True):
string = string+ ' or (W)est'
elif(W==True):
string=string+ '(W)est'
string = string + "."
print("You can travel: "+string)
valid = True
while(valid):
d = input("Direction: ")
if(d.lower() == 'n' and N==True):
y+=1
valid = False
elif(d.lower() == 's' and S==True):
y-=1
valid = False
elif(d.lower() == 'e' and E==True):
x+=1
valid = False
elif(d.lower() == 'w' and W==True):
x-=1
valid = False
else:
print("Not a valid direction!")
if(y == 1 or (y==2 and (x==1 or x==3))):
N = True
else:
N = False
if((y == 3 and (x==1 or x==3)) or y == 2):
S = True
else:
S = False
if((x==1 and (y==2 or y==3)) or (x==2 and y==3) or (x==1 and y!=1)):
E = True
else:
E = False
if((x==2 and y == 2) or ((x==2 or x==3) and y==3)):
W = True
else:
W = False
if(x==3 and y==1):
win = True
if(d == 'q'):
win = True
#print("You can travel: {0}".format(["(N)orth"]))
print('Victory!') |
from tkinter import *
win = Tk()
win.title("CALCULATOR")
equation = StringVar()
expression = ""
def input_number(number, equation):
global expression
expression = expression + str(number)
equation.set(expression)
def clear_input_field(equation):
global expression
expression = ""
equation.set("0")
def evaluate(equation):
global expression
try:
result = str(eval(expression))
equation.set(result)
expression = ""
except:
expression = ""
def main():
win.geometry("325x175")
input_field = Entry(win,textvariable=equation)#,textvariable=equation)
input_field.place(height=200)
input_field.grid(columnspan=6, ipadx=90, ipady=6)
equation.set("0")
_1=Button(win,text="1", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(1, equation))#, command=lambda: input_number(1, equation)
_1.grid(row=2,column=0)
_2=Button(win,text="2", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(2, equation))#, command=lambda: input_number(2, equation)
_2.grid(row=2, column=1)
_3=Button(win,text="3", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(3, equation))#, command=lambda: input_number(3, equation)
_3.grid(row=2, column=2)
_4=Button(win,text="4", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(4, equation))#, command=lambda: input_number(4, equation)
_4.grid(row=3,column=0)
_5=Button(win,text="5", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(5, equation))#, command=lambda: input_number(5, equation)
_5.grid(row=3,column=1)
_6=Button(win,text="6", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(6, equation))#, command=lambda: input_number(6, equation)
_6.grid(row=3,column=2)
_7=Button(win,text="7", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(7, equation))#, command=lambda: input_number(7, equation)
_7.grid(row=4,column=0)
_8=Button(win,text="8", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(8, equation))#, command=lambda: input_number(8, equation)
_8.grid(row=4,column=1)
_9=Button(win,text="9", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(9, equation))#, command=lambda: input_number(9, equation)
_9.grid(row=4,column=2)
_0=Button(win,text="0", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number(0, equation))#, command=lambda: input_number(0, equation)
_0.grid(row=5,column=0)
plus=Button(win,text="+", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number('+', equation))#, command=lambda: input_number(+, equation)
plus.grid(row=2, column=3)
minus=Button(win,text="-", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number('-', equation))#, command=lambda: input_number(-, equation)
minus.grid(row=3, column=3)
multiply=Button(win,text="*", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number('*', equation))#, command=lambda: input_number(*, equation)
multiply.grid(row=4, column=3)
divide=Button(win,text="/", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: input_number('/', equation))#, command=lambda: input_number(/, equation)
divide.grid(row=5, column=3)
equal=Button(win,text="=", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: evaluate(equation))#, command=lambda: evaluate(equation)
equal.grid(row=5, column=2)
clear=Button(win,text="clear", fg='white', bg='black', bd=0, height=2, width=10, command=lambda: clear_input_field(equation))#, command=lambda: clear_input_field(equation)
clear.grid(row=5, column=1)
win.mainloop()
if __name__ == '_main_':
main()
|
import os
import sys
import logging
from Calculator import Calculator
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
log = logging.getLogger("S_Expr : ")
# Validate the list of keywords
# For now add and multiply are allowed ones
# We evaluate the first sub-word of the sent partial expression and validate against the allowed keywords
# We also lstrip the spaces for this partial expression to remove the preceeding spaces
def validateKeywords(tempword):
flag=0
allowed_kw=["add", "multiply"]
for kw in allowed_kw:
if(tempword.lstrip().split()[0] == kw):
flag=1
if(flag!=1):
raise Exception("It looks like there is no valid keyword. Valid keywords are add, multiply")
# Parse the provided partial expression and pass it on to calculator for arithmetic operations
def operateOnNumbers(word):
result=0
str_add="add"
str_mul="multiply"
start_index=0
word=word.lstrip()
log.debug(word)
if (word[start_index:len(str_add)] == str_add):
result=0
newlist=word[len(str_add):].split()
if (len(newlist)<2):
raise Exception("It looks like the number of operands are less than 2. Please follow the S-Expression syntax ("+word+")")
for myitem in newlist:
calc=Calculator(result,int(myitem))
result=calc.add()
elif (word[start_index:len(str_mul)] == str_mul):
result=1
newlist=word[len(str_mul):].split()
log.debug("Length of new list is "+str(len(newlist)))
if (len(newlist)<2):
raise Exception("It looks like the number of operands are less than 2. Please follow the S-Expression syntax ("+word+")")
for myitem in newlist:
if(int(myitem) == 0):
result=0
break
calc=Calculator(result,int(myitem))
result=calc.multiply()
return result
#Recursively, parse the right extreme expression and keep working left to complete the arithmetic operations, following the S-Expression syntax
def calculate(word):
log.debug(word)
#Get the count of left paranthesis. This is to used for evaluating the expressions and come out of the recursion.
c=word.count('(')
#If the left and right are not equal, that is not a valid S-Expression syntax
if(c!=word.count(')')):
raise Exception("It looks like the expression is invalid. Please check the expression. It should follow the S-Expression syntax.")
if(c==0):
print(word)
return
tempstart=0
tempend=0
#Getting the index of the right most paranthesis. Start of identifying the right most expression
tempstart = word.rindex('(')
flag=0
tempword=word[tempstart:len(word)]
tempend= tempword.index(')')+tempstart
#First validate the keyword for this expresion.
#We remove the current expression right paranthesis and send the remaining.
validateKeywords(tempword[1:])
#Start the operation to perform the calculation.
result = operateOnNumbers(word[tempstart+1:tempend])
log.debug(result)
c=c-1
if(c>0):
newword=word[0:tempstart-1] +' ' + str(result) + word[tempend+1:len(word)]
log.debug(newword)
calculate(newword)
else:
print(result)
#Main program starts here
expression=sys.argv[1].lower()
log.debug(expression)
calculate(expression)
|
# Import library functions of 'pygame'
import pygame
# Initialize pygame
pygame.init()
# constants
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
PI = 3.141592653
# screen size
size = (400, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Rotate Text")
# Loop until closining.
done = False
clock = pygame.time.Clock()
text_rotate_degrees = 0
# Loop as long as done == False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
# Clear and fill as black
screen.fill(RED)
# Draw some borders
pygame.draw.rect(screen, BLACK, [150, 200, 123, 123], 7)
pygame.draw.rect(screen, BLUE, [125, 175, 175, 175], 7)
# Font specifics
font = pygame.font.SysFont('Calibri', 25, True, False)
# rotation details
text = font.render("Stacy Bates", True, BLUE)
text = pygame.transform.rotate(text, text_rotate_degrees)
text_rotate_degrees += 1
screen.blit(text, [150, 200])
# Update screen with above draw code.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# at the minute all speed to prog. but untick# below and will slow to 60 cycles
#clock.tick(60)
# Pygame on VS CODE S BATES
pygame.quit() |
def checkAnagram(str1, str2):
letras_str1 = list(str1)
letras_str2 = list(str2)
letras_str1.sort()
letras_str2.sort()
i = 0
for letra in letras_str1:
if letra is not letras_str2[i]:
return False
i = i + 1
return True
print('Ingresar primer palabra: ')
str1=input()
print('Ingresar segunda palabra: ')
str2=input()
if checkAnagram(str1, str2):
print('La palabra '+str1+' es un anagrama de '+str2)
else:
print('La palabra '+str1+' no es un anagrama de '+str2)
|
"""
To be safe, the CPU also needs to know the highest value held in any register during this process so that it can decide how much memory to allocate to these operations. For example, in the above instructions, the highest value ever held was 10 (in register c after the third instruction was evaluated).
"""
from collections import defaultdict
import fileinput
inputs = fileinput.input()
# inputs = [
# "b inc 5 if a > 1",
# "a inc 1 if b < 5",
# "c dec -10 if a >= 1",
# "c inc -20 if c == 10",
# ]
def inc_or_dec(register, iod, value, maximum):
if iod == "dec":
value = registers.get(register, 0) - int(value)
else:
value = registers.get(register, 0) + int(value)
if value > maximum:
maximum = value
registers[register] = value
return maximum
MAXIMUM = 0
registers = defaultdict(int)
for line in inputs:
instruction = line.strip()
register, iod, value, _, cond1, cond2, cond3 = instruction.split()
if cond2 == ">":
if registers.get(cond1, 0) > int(cond3):
MAXIMUM = inc_or_dec(register, iod, value, MAXIMUM)
elif cond2 == "<":
if registers.get(cond1, 0) < int(cond3):
MAXIMUM = inc_or_dec(register, iod, value, MAXIMUM)
elif cond2 == ">=":
if registers.get(cond1, 0) >= int(cond3):
MAXIMUM = inc_or_dec(register, iod, value, MAXIMUM)
elif cond2 == "==":
if registers.get(cond1, 0) == int(cond3):
MAXIMUM = inc_or_dec(register, iod, value, MAXIMUM)
elif cond2 == "<=":
if registers.get(cond1, 0) <= int(cond3):
MAXIMUM = inc_or_dec(register, iod, value, MAXIMUM)
elif cond2 == "!=":
if registers.get(cond1, 0) != int(cond3):
MAXIMUM = inc_or_dec(register, iod, value, MAXIMUM)
print(MAXIMUM)
|
"""
In the example above, there were 2 groups: one consisting of programs 0,2,3,4,5,6, and the other consisting solely of program 1.
How many groups are there in total?
"""
from collections import namedtuple, deque
import fileinput
inputs = [
"0 <-> 2",
"1 <-> 1",
"2 <-> 0, 3, 4",
"3 <-> 2, 4",
"4 <-> 2, 3, 6",
"5 <-> 6",
"6 <-> 4, 5",
]
inputs = fileinput.input()
Program = namedtuple('Program', ['name', 'connections'])
programs = {}
for line in inputs:
name, connections = list(map(str.strip , line.split("<->")))
connections = list(map(str.strip, connections.split(",")))
programs[name] = Program(name, connections)
# in the given example we only need to start with one group and work from there
# but now we need to go through all possible group starting points that we
# haven't seen already as part of another group
groups = 0
seen = set({})
for program in programs.keys():
if program not in seen:
seen.add(program)
stack = deque(programs[program].connections)
connections = set({})
while stack:
current = stack.popleft()
connections.add(current)
for c in programs[current].connections:
if c not in connections:
stack.append(c)
seen.update(connections)
groups += 1
print(groups)
|
"""
How many programs are in the group that contains program ID 0?
"""
from collections import namedtuple, deque
import fileinput
# inputs = [
# "0 <-> 2",
# "1 <-> 1",
# "2 <-> 0, 3, 4",
# "3 <-> 2, 4",
# "4 <-> 2, 3, 6",
# "5 <-> 6",
# "6 <-> 4, 5",
# ]
inputs = fileinput.input()
Program = namedtuple('Program', ['name', 'connections'])
programs = {}
for line in inputs:
name, connections = list(map(str.strip , line.split("<->")))
connections = list(map(str.strip, connections.split(",")))
programs[name] = Program(name, connections)
stack = deque(programs['0'].connections)
connections = set({})
while stack:
current = stack.popleft()
connections.add(current)
for c in programs[current].connections:
if c not in connections:
stack.append(c)
print(len(connections))
|
# -*- coding: utf-8 -*-
TEMPERATURA_CRITICA = 60
class Temperatura(Exception):
def __init__(self, temperatura):
self._temperatura = temperatura
def __str__(self):
return "Se ha alcanzado la temperatura crítica: {}. Todos muertos!!!".format(self._temperatura)
def preparar_materiales(producto, temperatura):
mezclar_elementos(temperatura)
print ("Se ha preparado: {} a {}ºC".format(producto, temperatura))
#no se puede mezclar si se alcanza la temperatura critica
def mezclar_elementos(temperatura):
if temperatura > 60:
raise Temperatura(temperatura)
pass |
'''
Expresiones regulares
libreria re
'''
# [ ] = delimits a group of characters, any of which are a match
# [0-9] = matches characters between zero and nine
# [^0-9] = matches any characters except zero through nine
# [0-9]* = matches number of Gmes (zero or more repeGGons)
# . = matches any character except a newline
# \s = matches any whitespace character
import re
string = "kkads dsa aadsa dasda, dasasd;adsdasas "
# r Python raw: significa que los que vaya dentro de las comillas es literal no se interpreta
# [] es cualquier elemento individual
# \s concuerda con un espacio en blanco
# \s* 0 o + espacios en blanco
# [;,\s] representa una coma, un punto y coma o un espacio en blanco
x = re.split(r'[;,\s]\s*', string)
filesname = ['makefile','foo.c','bar.py','span.c']
files = [name for name in filesname if name.endswith('.c')]
print (files)
files = [name for name in filesname if name.endswith(('.c', '.h'))]
print (files)
text1 = '27/11/2018'
text2 = '27/11/18'
#\d un digitos
#\d+ uno o mas digitos (al menos un digito)
assert ( re.match(r'\d+/\d+/\d+', text1))
assert ( re.match(r'\d+/\d+/\d+', text2))
#\d{4} 4 digitos
#compilamos la regex y la guardamos por rendimiento
date_pattern = re.compile(r'\d{2}/\d{2}/\d{4}')
date_pattern = re.compile(r'(\d{2})/(\d{2})/(\d{4})')
assert not ( re.match(date_pattern, '27/11/18'))
assert ( re.match(date_pattern, '27/11/2018'))
same_date_pattern = re.compile(r'(\d{2})/(\d{2})/(\d{4})')
m = same_date_pattern.match('27/11/2018')
#m es un Match Objects
print(m)
print (m.groups()) #tupla con todos los elementos
print (m.group(0)) #Todos los grupos
print (m.group(1)) #primer elemento
|
#!/usr/bin/env python3
def main(txtFile):
f = open(txtFile, 'r')
txtlist = f.read().split()
try:
numbers = [int(x) for x in txtlist]
except:
print("Error converting list to ints")
return -1
for i in range(len(numbers)-1):
ans = 2020 - numbers[i]
for j in range(i, len(numbers)-1):
if numbers[j] == ans:
print("The answer is {}".format(ans * numbers[i]))
return ans * numbers[i]
return -1
if __name__ == "__main__":
main("C:\\Users\\Backal\\Python_tests\\2020_day1_advent.txt") |
from itertools import product
from collections import namedtuple
class atom(namedtuple('atom',['num','bval'])):
""" Represents an integer with an associated boolean value
"""
def __str__(self):
return '{}{}'.format('' if self.bval else '~', self.num)
def __repr__(self):
return '({},{})'.format(self.num, self.bval)
class tree:
""" A logic tree customized for use by the clue solver.
It is implemented as a list of sets, where each set
represents a branch of a tree
"""
def __init__(self):
self.branches = []
def add_pos(self, query):
""" Add a query (tuple) positively to the tree. This results in
a copy of each existing branch for each atom in the disjunction.
Multiple references to a given atom are created in the process.
"""
self.branches = [b | set((atom(q, True),))
for b in self.branches for q in query] \
if self.branches else [set((atom(q, True),)) for q in query]
self.prune()
self.clean()
def add_neg(self, query):
""" Add a query (tuple) negatively to the tree. A chain of negative
atoms is created for the conjunction. It is then and unioned
with each existing branch.
"""
qset = set(atom(q, False) for q in query)
self.branches = [b | qset for b in self.branches] \
if self.branches else [qset]
self.prune()
self.clean()
def contr(self, branch):
""" Check if a branch contains one or more logical contradictions.
If so, the branch can be deleted from the tree.
"""
yes = {a.num for a in branch if a.bval}
no = {a.num for a in branch if not a.bval}
return yes & no
def prune(self):
""" remove any branches with contradictions """
self.branches = [b for b in self.branches if not self.contr(b)]
def clean(self):
""" Remove duplicate branches.
"""
self.branches = [set(b) for b in set([tuple(b) for b in self.branches])]
#---------------------------
# Information about the tree
#---------------------------
def print(self):
for b in self.branches:
print(sorted(list(b), key=lambda a: a.num))
def common_elements(self):
""" get a set of the atoms common to all branches """
return set.intersection(*self.branches) if self.branches else set()
def possibles(self):
""" get a nested list representing the disjuctive part of the tree
bvals are not included since they will always be True
inner and outer lists are sorted in ascending order
"""
if not self.branches: return []
ce = self.common_elements()
diff = [b - ce for b in self.branches if b - ce]
return sorted([sorted([a.num for a in sub]) for sub in diff])
def simple(self):
""" return a simple representation of the tree """
return sorted(list(self.common_elements()),
key=lambda a: a.num) + self.possibles() \
if self.branches else []
def pos_elements(self):
""" the common atoms with bval True """
return {a.num for a in self.common_elements() if a.bval}
def neg_elements(self):
""" the common atoms with bval False """
return {a.num for a in self.common_elements() if not a.bval}
def contains_any(self, nums):
""" compare the positive common atoms with the given enumerable
to see if any are included
"""
return self.pos_elements() & set(nums)
|
#assert.py
#此示例assert用法
def get_age():
a = int(input("请输入年龄: "))
assert 0 <= a <= 140, '年龄不在合法范围内'
return a
try:
age = get_age()
except AssertionError as e:
print("错误原因是:", e)
age = 0
print("年龄是:", age)
|
#21_try_except_as.py
#此示例示意try-except语句的用法
def div_apple(n):
print('%d个苹果您想分给几个人?' % n)
s = input('请输入人数: ')
#<<=可能触发ValueError错误异常
cnt = int(s)
#<<==可能触发ZeroDivisionError错误异常
result = n/cnt
print("每个人分了",result, '个评估')
#以下是调用者
#用try-except语句捕获并处理ValueError类型的错误
try:
print("开始分平台")
div_apple(10)
print("分苹果完成")
except ValueError as err:
print("苹果退回来不分了")
print("错误信息是:", err)
except:
print("除ValueError外的错误")
print("程序正常退出") |
#练习:
# 修改前的Student 类,
# 1) 为该类添加初始化方法,实现在创建对象时自动设置 '姓名', '年龄', '成绩' 属性
# 2) 添加set_score方法能为对象修改成绩信息
# 3) 添加show_info方法打印学生对象的信息
class Student:
def __init__(self, name, age=0, score=0):
'''初始化方法用来给学生对象添加'姓名'和'年龄'属性'''
# 此处自己实现
self.name = name
self.age = age
self.score = score
def set_score(self, score):
self.score = score
def show_info(self):
'''此处显示此学生的信息'''
print(self.name,'今年',self.age,'岁',
'成绩是',self.score)
s1 = Student('小张', 20, 100)
s2 = Student('小李', 18, 90)
s1.show_info() # 小张信息
s2.show_info() # 小李信息
s1.set_score(97)
s1.show_info() # 成绩修改
|
#方法1
#def mymax(a, b):
# s = max(a, b)
# return s
#方法2
#def mymax(a, b):
# if a> b:
# return a
# else:
# return b
#方法3
def mymax(a, b):
if a > b:
return a
return b
print(mymax(100, 200)
|
class Mylist(list):
def insert_head(self, value):
'''将value值插入到列表前面去
'''
self.insert(0, value)
L = Mylist(range(1,5))
print(L) #[1, 2, 3, 4]
L.insert_head(0)
print(L) #[0, 1, 2, 3, 4]
L.append(5)
print(L) #[0,1,2,3,4,5] |
#raise.py
#此示例用raise语句来发出异常通知
#供try-except语句来捕获
def make_except():
print("开始....")
raise ZeroDivisionError #手动发生一个错误通知
print("结束....")
#try语句解决上述问题
try:
make_except()
print("make_except调用完毕!")
except ZeroDivisionError:
print("出现了被零除的错误,已处理并转为正常状态")
###########################################
#类型当函数调用
def make_except():
print("开始....")
#raise ZeroDivisionError #手动发生一个错误通知
e = ZeroDivisionError("被零除了!!!!")
raise e #触发e绑定的错误,进入异常状态
print("结束....")
try:
make_except()
print("make_except调用完毕!")
except ZeroDivisionError as err:
print("出现了被零除的错误,已处理并转为正常状态")
print("err绑定的对象是:", err) |
#联系:输入三行文字,让这些文字一次以20字符的宽度右对齐输出
#如:
#请输入第一行:hello world
#请输入第二行:abcd
#请输入第三行:a
#输出结果:
# hello world
# abcd
# a
#之后,思考:
#能否以最长字符串的长度进行右对齐显示(左侧填充空格)
s1 =input("请输入第一行: ")
s2 =input("请输入第二行: ")
s3 =input("请输入第三行: ")
print('---以下是所有字符串占20个字符串宽度')
print('%20s' % s1)
print('%20s' % s2)
print('%20s' % s3)
print('---一以下按照最长的字符串左对齐')
m = max(len(s1), len(s2), len(s3))
print('最大长度是: ', m)
print(' '*(m - len(s1)) + s1)
print(' '*(m - len(s2)) + s2)
print(' '*(m - len(s3)) + s3)
print("-----------方法3---------")
fmt = '%%%ds' % m #生成一个含占位符的字符串
print('fmt = ', fmt)
print(fmt % s1)
print(fmt % s2)
print(fmt % s3)
|
#写程序,用while循环计算
# 1 + 2 + 3 + 4 + ...+ 99 + 100的和
i = 1
s = 0 #此变量保存所有数的和
while i <= 100:
s += i #把当前的i值累加到s
i += 1
else:
print()
print("1+2+3+...+99+100的和是:", s)
|
#instance_method.py
#此实例示意如何用实例方法(method)来描述Dog类的行为
class Dog:
def eat(self, food):
'''此方法用来描述小狗吃东西的行为'''
print("小狗正在吃:", food)
def sleep(self, hour):
print("小狗睡了",hour,"小时")
def play(self, obj):
print("小狗正在玩", obj)
#创建一个Dog的类的实例:
dog1 = Dog()
dog1.eat('狗粮') #self-dog1;food-'狗粮'
dog1.sleep(1)
dog1.play("球") #对象不能调用类内不存在的实例方法
#创建另一个Dog对象:
dog2 = Dog() #self-dog2
dog2.play("飞盘")
dog2.eat("骨头")
dog2.sleep(2)
#dog2.paly("杂技")
Dog.play(dog2, '杂技') |
#练习 :
# 1. 写一个函数 mysum(), 可以传入两个实参或三个实参.
# 1) 如果传入两个实参,则返回两个实参的和
# 2) 如果传入三个实参,则返回前两个实参的和对第三个实参求余的结果
# print(mysum(1, 100)) # 101
# print(mysum(2, 10, 7)) # 5 返回:(2+10) % 5
#方法1
#def mysum(a, b, c=1):
# if c !=1 :
# return (a + b) % c
# return (a + b)
#print(mysum(1, 100))
#print(mysum(2, 10, 7))
##方法2
def mysum(x, y, z=None):
if z is None:
return x + y
return (x + y) % z |
#输入一个字符串,判断这个字符串有几个空格‘ ’
#(要求不允许使用s.count方法),建议使用for语句实现
s = input("输入一段字符串: ")
count = 0 #此变量替代,用来记录空格的个数
for ch in s:
if ch == ' ':
count +=1
print("空格的个数是",count)
|
# 打印如下宽度的正方形:
# 1 2 3 4
# 2 3 4 5
# 3 4 5 6
# 4 5 6 7
n = int(input("请输入: "))
for y in range(1, n + 1):
for x in range(y, y + n):
print("%2d" % x, end = " ")
print()
|
#This is a simple snake game made using Python 3
#By Aaron Avers
#Inspired by @TokyoEdTech's Python Game Programming Tutorial: Snake Game
import time
import turtle
import random
delay = 0.2
#Score
score = 0
high_score = 0
#Create screen
screen = turtle.Screen()
screen.title("Snake Game by UnderratedRon")
screen.bgcolor("white")
screen.setup(width=600, height=600)
screen.tracer(0)
#Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("green")
head.penup()
head.goto(0,0)
head.direction = "stop"
#Food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,100)
segments = []
#Pen
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("black")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0 High Score: 0", align="center", font=("Courier", 24, "normal"))
#functions
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
#Keybinds
screen.listen()
screen.onkeypress(go_up, "w")
screen.onkeypress(go_down, "s")
screen.onkeypress(go_left, "a")
screen.onkeypress(go_right, "d")
#Game Loop
while True:
screen.update()
#check for collision with the border
if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
#Hide the segments
for segment in segments:
segment.goto(1000, 1000)
#clear the segments list
segments.clear()
#Reset the score
score = 0
#Reset the delay
delay = 0.2
pen.clear()
pen.write("Score: {} High Score: {}". format(score, high_score), align="center", font=("Courier", 24, "normal"))
#check for collision with the food
if head.distance(food) < 20:
#move the food to a random spot on the screen
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)
#Add a segment to the snakes body
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("purple")
new_segment.penup()
segments.append(new_segment)
#shorten the delay
delay -= 0.002
#Increase the score
score += 100
if score > high_score:
high_score =score
pen.clear()
pen.write("Score: {} High Score: {}". format(score, high_score), align="center", font=("Courier", 24, "normal"))
#Moving the segments starting at the end
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y)
#Move segment 0 to where the head is
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x,y)
move()
#Check for head collision with the body segments
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
#Hide the segments
for segment in segments:
segment.goto(1000, 1000)
#clear the segments list
segments.clear()
#Reset the score
score = 0
#Reset the delay
delay = 0.2
pen.clear()
pen.write("Score: {} High Score: {}". format(score, high_score), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
screen.mainloop() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.