text stringlengths 37 1.41M |
|---|
# Rolando Josue Quijije Banchon
# Software
# #Tercer semestre
#Tarea 5 de ejercicios de pagina web
"""EJEMPLO 5:
Dado como dato la calificación de un alumno en un examen,
escriba “aprobado” si su calificación es mayor o igual que 7
y “Reprobado” en caso contrario."""
class Tarea5:
def __init__(self):
pass
def Calcular(self):
print("_______________________________________")
cal=float(input("Ingrese su calificacion:"))
if cal >= 7 :
print()
print("!!!!!!Felicidades!!!!!!")
print(" APROBADO")
else:
print()
print("!!!!!!Ho no, esfuerzate mas!!!!!!")
print(" REPROBADO")
print()
print("_______________________________________")
input("enter para salir")
tarea = Tarea5()
tarea.Calcular() |
class Disciplin:
def __init__(self, id, name, first_name,
second_name, exam, coursework,
count_lec, count_pr,count_lab = 0):
self.id = id #код
self.name = name #название
self.first_name = first_name #имя преподователя
self.second_name = second_name #фамиля преподователя
self.exam = exam #форма контроля
self.coursework = coursework #наличие курсовой 1-есть, 0-нет
self.count_lec = count_lec #кол-во лек
self.count_pr = count_pr #кол-во пр
self.count_lab = count_lab #кол-во лаб
def showInfo(self):
print("|%-7s|%-15s|%-15s|%-15s|%-6s|%-10s|%-11s|%-15s|%-10s|" % (str(self.id), self.name, self.first_name , self.second_name , self.exam, str(self.coursework), str(self.count_lec), self.count_pr , str(self.count_lab)))
person = [Disciplin(1, "math" , "Person1", "Person1", "exam", 1, 12, 2, 8),
Disciplin(2,"Python", "Person2", "Person2", "test", 0, 12, 2, 8)]
while True:
try:
k = int(input("==========================\n"
"1. Добавление информации.\n"
"2. Удаление информации.\n"
"3. Отображение информации.\n"
"4. Поиск по форме контроля.\n"
"Для выхода введите 0.\n"
"Введите номер задания: "))
except:
print("Ошибка, введен не верный номер задания. Попробуйте снова.")
continue
break
while k != 0:
if k == 1:
while True:
try:
id = int(input("Код: "))
except:
print("Ошибка. Попробуйте снова.")
continue
break
name = (input("Название дисциплины: "))
first_name = (input("Имя: "))
second_name = (input("Фамилия: "))
exam = (input("Форма контроля: "))
while True:
try:
coursework = (input("Наличие курсовой: "))
except:
print("Ошибка. Попробуйте снова.")
continue
break
while True:
try:
count_lec = int(input("Количество лекций: "))
except:
print("Ошибка. Попробуйте снова.")
continue
break
while True:
try:
count_pr = (input("Количество практик: "))
except:
print("Ошибка. Попробуйте снова.")
continue
break
while True:
try:
count_lab = int(input("Количество лабораторных: "))
except:
print("Ошибка. Попробуйте снова.")
continue
break
if (count_lab < 0):
person.append(Disciplin(id, name, first_name,
second_name, exam, coursework,
count_lec, count_pr))
else:
person.append(Disciplin(id, name, first_name,
second_name, exam, coursework,
count_lec, count_pr, count_lab ))
elif k == 2:
# удаление по номеру элемента в списке начиная с 0
while True:
try:
x = int(input("Номер для удаления: "))
except:
print("Ошибка. Попробуйте снова.")
continue
break
for i in range(len(person)):
if(i == x):
person.pop(i)
elif k == 3:
print("|%-7s|%-15s|%-15s|%-15s|%-6s|%-10s|%-11s|%-15s|%-10s|" % ("id", "name", "first_name", "second_name", "exam", "coursework","count_lec","count_pr","count_lab"))
for i in range(len(person)):
person[i].showInfo()
elif k == 4:
while True:
try:
x = (input("Форма контроля: "))
except:
print("Ошибка. Попробуйте снова.")
continue
break
f = False
for i in range(len(person)):
if (person[i].exam == x):
f = True
person[i].showInfo()
if not(f):
print("Дисциплин с этой формой контроля нет.")
else: print("Ошибка, введен не верный номер задания. Попробуйте снова.")
while True:
try:
k = int(input("==========================\n"
"1. Добавление информации.\n"
"2. Удаление информации.\n"
"3. Отображение информации.\n"
"4. Поиск по форме контроля.\n"
"Для выхода введите 0.\n"
"Введите номер задания: "))
except:
print("Ошибка, введен не верный номер задания. Попробуйте снова.")
continue
break |
# you can use print for debugging purposes, e.g.
# print "this is a debug message"
def solution(A):
# write your code in Python 2.7
lower_value = min(A)
size = len(A)
centinel = lower_value
for i in xrange(size):
if ( centinel not in A ) :
return centinel
else :
centinel = centinel + 1
A = [2,3,1,5]
print solution(A);
|
#!/usr/bin/env python
import sys
import csv
cookies = sys.argv[1]
targetDate = sys.argv[3]
dictionary = {}
with open(cookies) as csvfile:
content = csv.reader(csvfile)
highestRepetition = 0
answer = []
# loop through each row in the csv file
for row in content:
cookie = row[0]
cookieTimestamp = row[1][:10]
# check if the cookie timestamp is equal to are target date
if cookieTimestamp == targetDate:
# if cookie isn't in dictionary set value to 1 else increase value by 1
if cookie not in dictionary:
dictionary[cookie] = 1
else:
dictionary[cookie] += 1
# check if the dictionary key is greater to or equal to the highestRepetition
if dictionary[cookie] > highestRepetition:
answer = cookie
highestRepetition = dictionary[cookie]
elif dictionary[cookie] == highestRepetition:
answer = answer + ',' + cookie
# loop through dictionary and print keys that match the highest repetition
for key in dictionary:
if dictionary[key] == highestRepetition:
print(key)
|
import numpy as np
import csv
import xlsxwriter
import os
# Use these to test the function before using a for loop (optional) or use the files provided for practice
name = 'cerda'
source1 = f"/Users/{name}/Desktop/ColdFingerData/06262020list.csv" # the file we are editing
newFileName1 = f"/Users/{name}/Desktop/ColdFingerData_Filtered/TEST.xlsx" # the file that is edited ALREADY
# Function that reads CSV files and writes the data into excel format
def fileEditor(source, newFileName):
time = [] # Inititating the arrays (Determine how many arrays are needed)
temp_rack = []
temp_fing = []
temp_rack2 = []
temp_fing2 = []
with open(source) as File: # Open the CSV file
reader = csv.reader(File, delimiter=';')
for row in reader:
time.append(row[0]) # Append the data into separated arrays
temp_rack.append(row[1])
temp_fing.append(row[2])
temp_rack2.append(row[13]) # since se have several empty columns of data, we skip to the desired data columns
temp_fing2.append(row[14])
a = [time, temp_rack, temp_fing, temp_rack2, temp_fing2] # array that contains all the CSV columns in one array
wb = xlsxwriter.Workbook(newFileName) # Create a new Excel file
ws = wb.add_worksheet()
row = 0
col = 0
for i in range(len(a)): # Write all the data into separate columns
for i2 in range(len(a[0])):
ws.write(row, col, a[i][i2])
row += 1
col += 1
row = 0
wb.close() # closing the workbook
# fileEditor(source1, newFileName1) # Testing the function with only one file
# print("PASS")
"""
Gathering all the file names in the folder and removing the "list.csv" --- ONLY NEED THIS ONCE ---
"""
path = r"C:/Users/cerda/Desktop/ColdFingerData"
# Call listdir() - Path is a directory of which you want to list
directories = os.listdir(path)
# Need a way to remove the (list.csv) from tall of the names
short_name_list = directories
list_remove_name = []
for r in short_name_list:
list_remove_name.append(r.replace('list.csv', '.xlsx')) # removes "list.csv" and replaces it with " "
# print(list_remove_name)
# New filed path for edited files (once they run through excel_writer function)
edited_files_path = np.array([])
for new_paths in list_remove_name:
edited_files_path = np.append(edited_files_path, f"/Users/{name}/Desktop/ColdFingerData_Filtered/{new_paths}")
# Making a list of all the filed in the folder path
unedited_csv_files_path = np.array([])
for paths in directories:
unedited_csv_files_path = np.append(unedited_csv_files_path, f"/Users/{name}/Desktop/ColdFingerData/{paths}")
|
"""
This module implements the REL (REL) class, used for relational links between tables/objects
A schema definition of thing=REL causes an INT(11) to be added to the database, to store the uid of the related class Thing
On construction of an instance of REL, the link is stored as in integer. It is converted to the object it refers to when first accessed.
So:
- when setting a REL attribute, you are dealing with a uid (ie an integer - this class).
- when getting, you are dealing with an object of the class referred to. This object is cached for the lifespan of the instance.
- when flushing, the uid is flushed
e.g. in config.py or config_base.py:
class = User(req)
account=REL #creates an account column in a user table
and in use:
user=self.User.get(5)
user.account=8
print user.account.name #gives the name of account 8
user.flush() #flushes 8 to the account column in the user table
return user.account.view(req) #the account object remains cached
The magic is done in data.py ( __getattribute__ )
(Ian Howie Mackenzie - April 2007)
"""
from .INT import INT
class REL(INT):
"""
object relationships
"""
|
#!/usr/bin/python2.7
# Map1.py
import sys
import itertools
def main(numberOfArms, stepSize):
rangeMin = 0.0
rangeMax = 1.0
generateBandits(rangeMin, rangeMax, stepSize, numberOfArms)
def arange(rangeMin, rangeMax, stepSize):
probRange = []
currProb = rangeMin
while (currProb <= rangeMax):
probRange.append(currProb)
currProb = round(currProb + stepSize, 3)
return probRange
def generateBandits(rangeMin, rangeMax, stepSize, numberOfArms):
probRange = arange(rangeMin, rangeMax, stepSize)
for p in itertools.product(probRange, repeat=numberOfArms):
print(p)
if __name__ == '__main__':
numberOfArms = int(sys.argv[1])
stepSize = float(sys.argv[2])
main(numberOfArms, stepSize) |
#!/usr/bin/python
"""
Usages:
./test3.py (reads out the entire config file)
./test3.py thiskey thisvalue (sets thiskey and thisvalue in the config file)
"""
import sys
from assignments3 import ConfigDict
cd = ConfigDict('config_file.txt')
if len(sys.argv) == 3:
key = sys.argv[1]
value = sys.argv[2]
print('writing date: {0}, {1}'.format(key, value))
cd[key] = value
else:
print('reading data')
for key in cd.keys():
print(' {0} = {1}'.format(key, cd[key])) |
import os
import argparse
arguments = []
parser = argparse.ArgumentParser()
# parser.add_argument("echo", help="This will print the first variable")
parser.add_argument("x", type=int, help="base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v","--verbose", help="Adding the verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbose >= 2:
print("{} to the power {} equals {}".format(args.x,args.y,answer))
elif args.verbose >= 1:
print("{}^{} == {}".format(args.x,args.y,answer))
else:
print(answer)
|
people=30
cars=40
trucks=15
if cars>people:
print("We should take the cars")
elif cars<people:
print("We should not take the cars")
else:
print("We can't decide")
if trucks>cars:
print("That's too many trucks")
elif trucks<cars:
print("Maybe we could take the trucks")
else:
print("We still can't decide")
if people >trucks:
print("Alright,let's just take the trucks")
else:
print("Fine,let's stay home then")
|
from sys import argv
print("How old are you?",end='')
age=input()
print("How tall are you?",end='')
height=input()
print("How much do you weight?",end='')
weight=input()
print(f"So,you're {age} old,{height} tall and {weight} heavy")
script ,filename=argv
txt=open(filename)
print("Here's your life {filename}:")
print(txt.read())
print("Type the filename again:")
file_again=input(">")
txt_again=open(file_again)
print(txt_again.read())
print("Let's practice everything.")
print("You\'d need to know \'bout escapes with \\ that so \n newlines and \t tabs.")
poem="""\t The lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation
\n \t \t where there is none."""
print("---------------------")
print(poem)
print("---------------------")
five = 10-2+3-6
print(f"This should be five :{five}")
def secret_formula(started):
jelly_beans=started * 500
jars=jelly_beans/1000
crates =jars/100
return jelly_beans,jars,crates
start_point=10000
beans,jars,crates=secret_formula(start_point)
print("with a starting point of:{}".format(start_point))
print(f"We'd have {beans} beans,{jars} jars, and {crates} crates.")
start_point =start_point/10
print("We can also do that this way:")
formula=secret_formula(start_point)
print("We'd have{}beans,{} jars,{}crates.".format(*formula))
people=20
cats=30
dogs=15
if people < cats:
print("Too many cats! The world is doomed!")
if people < cats:
print("Not many cats!The world is saved")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry")
dogs +=5
if people >= dogs:
print("People are greater than or equal to dogs")
if people<=dogs:
print("People are less than or equal to dogs.")
else:
print("People are dogs")
|
def isPrimeNumber(numToCheck):
result = False
res = []
remainders = []
if(numToCheck == 1):
numToCheck = numToCheck + 1
result = True
res.append(result)
res.append(numToCheck)
return res
initialDisvisor =2
for j in range(initialDisvisor,numToCheck):
remainder = numToCheck % j
remainders.append(remainder)
if 0 not in remainders:
numToCheck = numToCheck + 1
result = True
res.append(result)
res.append(numToCheck)
return res
else:
numToCheck = numToCheck + 1
isPrimeNumber(numToCheck)
k = int(input("Enter number of prime numbers to be printed: "))
numToCheck = 1
for _ in range(k):
result = isPrimeNumber(numToCheck)
if(result[0] == True):
print(result[1] - 1)
numToCheck = result[1]
|
#! /usr/bin/env python
import re
import sys
from datetime import datetime
from typing import List, Optional
from boggle import BoggleGrid, FileBasedDictionary
def main(letter_grid: List[List[str]]):
dictionary = FileBasedDictionary(file_path="american-english-large.txt")
boggle_grid = BoggleGrid(
letter_grid=letter_grid,
dictionary=dictionary,
)
print("Finding words...")
start = datetime.now()
matches = {word for word in boggle_grid.traverse()}
end = datetime.now()
print(f"Found {len(matches)} unique word(s) in {round((end-start).total_seconds(), 2)}s. Writing to matches.txt")
with open("matches.txt", "w") as f:
f.write("\n".join(matches))
def get_grid_dimension(val: str) -> Optional[int]:
try:
dimension = int(val)
if dimension > 0:
return dimension
except ValueError:
pass
return None
if __name__ == "__main__":
grid_length = get_grid_dimension(input("Enter length of the grid: "))
if grid_length is None:
print("Grid Length must be a positive integer")
sys.exit(1)
grid_height = get_grid_dimension(input("Enter height of the grid: "))
if grid_height is None:
print("Grid Height must be a positive integer")
sys.exit(1)
letter_grid = []
grid_row_regex = re.compile(rf"^[a-zA-z]{{{grid_length}}}$")
for i in range(grid_height):
row = input(f"Enter row #{i+1} (without any spaces): ")
if re.match(grid_row_regex, row):
letter_grid.append([c.upper() for c in row])
else:
print(f"Row must and only contain exactly {grid_length} alphabets")
sys.exit(1)
main(letter_grid=letter_grid)
|
#Section 1: Terminology
# 1) What is a recursive function? correct
# A recursive function is a function that does one thing or another depending on the input
#
#
# 2) What happens if there is no base case defined in a recursive function? correct
# If there is no base case defined in a recursive function, the function gets an error message.
#
#
# 3) What is the first thing to consider when designing a recursive function? correct
# First thing to consider when designing a recursive function is how the output changes depending on the input user type in
#
#
# 4) How do we put data into a function call? correct
# You can put data into a function call by using arguments.
#
#
# 5) How do we get data out of a function call? correct
# You can get data out of a function call by using return.
#
#
#Section 2: Reading
# Read the following function definitions and function calls.
# Then determine the values of the variables q1-q20.
#a1 = 2
#a2 = 6
#a3 = -1 correct
#b1 = 2 correct
#b2 = 2 correct
#b3 = 4 correct
#c1 = -2 correct
#c2 = 4 correct
#c3 = 4
#d1 = 6 correct
#d2 = 8 correct
#d3 = 4 correct
#Section 3: Programming
#Write a script that asks the user to enter a series of numbers.
#When the user types in nothing, it should return the average of all the odd numbers
#that were typed in.
#In your code for the script, add a comment labeling the base case on the line BEFORE the base case.
#Also add a comment label BEFORE the recursive case.
#It is NOT NECESSARY to print out a running total with each user input.
# HAVE: base case +2, recursion case +2, recursive returns 1, main function +1
def averageOdd(number,next):
# this is a base case
if next == "":
print "The average of your odd numbers was " + float(number)
# recursive case
else:
print next
def main():
next = raw_input("Next: ")
odd = number % 2
number = odd / 2
averageOdd(average,next)
main()
|
#Importing the required models and libraries.
#To run this file one should have Xgboost,scikitlearn and the corresponding libraries installed.
import pandas #Data analysis tools for the Python.
import matplotlib.pyplot as plt #Plotting tools for Python.
from sklearn import model_selection #Sklearn or scikit-learn is a machine learning library.
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor #Importing different models.
from sklearn.neural_network import MLPRegressor
from xgboost import XGBRegressor #Xgboost is also a machine learning model.
#XGBRegressor is for regression models.
import sys
from sklearn.metrics import mean_squared_error,mean_absolute_error #Different error calculation methods.
import time
url= sys.argv[1] # Storing the value received as argument, during the file call, python model.py.
#It should be the name of the file, keeping dataset in CSV format.
dataset = pandas.read_csv(url) #Reading the contents of the file and storing it to the DataFrame.
array = dataset.values #Dataframe is represented as an array.
X = array[:,1:13] #Slicing the input parameters .i.e from columns B to M and storing it to array X.
Y = array[:,0] #Storing the output values to array Y.
validation_size = 0.23
seed = 7
X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)
#train_test_split: Randomly splits 23% rows of data and is kept in X_validation and Y_validation.
#The remaining are kept in X_train and Y_train.
#This helps to avoid overfitting
#The data in X_validation and Y_validation are never used during training.This data is used to
#determine the accuracy of the model after training
#test_size :represent the proportion of the dataset to be included in the test split.
#random_state is the seed used by the random number generator
seed = 7
models = []
#evaluate each model in turn
models.append(('SVM', SVR()))
models.append(('RandomForest', RandomForestRegressor()))
models.append(('LinearRegression', LinearRegression())) #Initializing different regression models ,for evaluation of the fit
models.append(('CNN', MLPRegressor()))
models.append(('XGB', XGBRegressor()))
results = []
names = []
print" Executing cross-validation on 77% data...."
for name, model in models:
kfold = model_selection.KFold(n_splits=10, random_state=seed)
cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold) #RMS
results.append(cv_results)
names.append(name)
msg = "%s: %f " % (name, cv_results.mean())
print(msg)
#The quality of the fit will be assessed using cross-validation with RMS
#The trainingdata is split into groups of 10 rows ,where in each split 9 rows are used for training and 10th row for testing
print"\n Selecting the XGBRegressor AS it it has maximum accuracy.....\n"
#Creating a new XGBRegressor with different parameters tuned to obtain maximum accuracy
xgb = XGBRegressor(
max_depth=5, # Maximum tree depth for base learners
learning_rate= 0.065,#Boosting learning rate
n_estimators=500,#Number of boosted trees to fit
)
xgb.fit(X_train, Y_train) #Training the regressor model on the 77% trainingdata
predictionsv = xgb.predict(X_validation) #Using the trained model to predict on a new dataset (X_validation),that the model has never seen
fullpredict =xgb.predict(X) #Predicting on the input parameters of each row of the dataset
scoreonvalidation=xgb.score(X_validation, Y_validation)#Score is the accuracy.This is the accuracy of the model on validation set
print "**Details of prediction on the (23%) validation set**"
print"score :",scoreonvalidation
print"Root Mean Square Error :",mean_squared_error(predictionsv, Y_validation)**0.5#root mean squared error
print"Average Absolute Error :",mean_absolute_error(Y_validation,predictionsv) #average absolute error
error= fullpredict - Y #error on each row of predictions on the whole dataset
errorv = predictionsv - Y_validation #error on each row of predictions on the validation set
print"Max Absolute Error :",max(error**2)**0.5 #max absolute error
print"\n**Details of prediction on the whole dataset**"
print"score :",xgb.score(X, Y) #accuracy of predictions on the whole dataset of the CSV file
print"Root Mean Square Error :",mean_squared_error(fullpredict, Y)**0.5#root mean squared error
print"Average Absolute Error :",mean_absolute_error(Y,fullpredict)#Average absolute error
print"Max Absolute Error :",max(errorv**2)**0.5 #Maximum absolute error
plt.figure(figsize=(19,9)) #setting the size of the window to plot(in inches)
pred, = plt.plot(fullpredict,'.')
true,=plt.plot(Y,'r')
plt.legend([pred,true], ["Predicted Values","True Values"])
plt.title("Error Plot")
plt.ylabel("Values")
plt.xlabel("Rows")
#plt.plot(error) #plotting the error for predictions on the whole datset
#plt.title('Plot of errors for each row')
#plt.ylabel('Error(Predicted value-Actual value)')
#plt.xlabel('Rows')
plt.show()
|
# The server program is designed to be run on the base station (can be a laptop)
# It will wait and receive messages coming from the rover's Raspberry Pi
# Written with Python 3.9.0
import socket
# IP and port of the server
# TODO: instead of hard-coding let user select
host = "0.0.0.0"
port = 62522
# This function will be used to initially connect to the socket
# Returns the 'connection' tuple
def connect():
server = socket.socket() # create socket object
server.bind((host,port)) # bind the tcp socket to an IP and port
print("Server socket connected")
return server # return tuple of socket object
# This function will be used to disconnect from both socket and file object
# Takes in the 'connection' tuple
def disconnect(connection: 'connection'):
# separate the tuple for ease of use
server = connection[0]
client = connection[1]
server.close()
client.close()
print("Server socket disconnected")
# This function will be used to read a message from the socket
# Takes the clientConnection object
def read(client: 'file object'):
return client.recv(1024).decode()
# TODO: refactor so that UI is in a separate function instead of main body!
if __name__ == '__main__':
server = connect()
server.listen(); # listening for connection from client
while True: # waits for data indefinitely
print("Waiting for data")
(clientConnection, clientAddress) = server.accept(); # accepting from all clients
print (str(clientAddress) + " connected!")
data = read(clientConnection)
if data == "exit": # stops when "exit" is sent
break
elif not data:
break
else:
print("data: " + data) # prints out message to standard output
clientConnection.send("Received!") # sends ACK
disconnect((server, clientConnection))
|
import networkx as nx
class Vertex:
#contructor for Vertex
def __init__(self, int_val, left = None, right = None):
self.int_val = int_val
self.left = left
self.right = right
def add_node(val, node, g):
#check if value is less than nodes value
if(val < node.int_val):
#go to left node
if(node.left != None):
add_node(val, node.left, g)
#add node as left child
else:
g.add_edge(val, node.int_val)
node.left = Vertex(val)
#must be greater than node
else:
#go to right node
if(node.right != None):
add_node(val, node.right, g)
#add node as right child
else:
g.add_edge(val, node.int_val)
node.right = Vertex(val)
def simple_bst(int_list):
g = nx.Graph();
#add root to tree
root = Vertex(int_list.pop(0))
g.add_node(root.int_val)
#add nodes appropriatly
for i in int_list:
add_node(i, root, g)
#convert list to dict
cust_d = {}
for e in g.edges():
cust_d[e[0]] = []
cust_d[e[1]] = []
for e in g.edges():
key = e[0]
value = e[1]
#append to dictionary lists
cust_d[key].append(value)
cust_d[value].append(key)
#return dictionary of tree
return cust_d
print simple_bst([5,0,3,9,10,4,11,2])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pygame
#import time
import turtle
pygame.init()
#taille_police = 12
#taille_police2 = 17
#taille_police3 = 15
#POLICE = ('Arial', taille_police, 'normal')
#POLICE2 = ('Arial', taille_police2, 'normal')
#POLICE3 = ('Arial', taille_police3, 'normal')
police1 = pygame.font.SysFont("comicsansms", 12, True)
police2 = pygame.font.SysFont("comicsansms", 17, True)
police3 = pygame.font.SysFont("comicsansms", 15, True)
fenetre = pygame.display.set_mode((200, 60))
# creer str qui affiche le temps
def temps(minutes,secondes):
turtle.write(temps, police1, police2, police3)
turtle.mainloop()
if len(str(minutes)) > 1:
m = str(minutes)
else:
m = "0" + str(minutes)
if len(str(secondes)) > 1:
s = str(secondes)
else:
s = "0" + str(secondes)
return m + ":" + s
# creer le chrono
def chrono(temps_de_depart):
minutes = 0
secondes = 0
temps_depart = 0
temps_actuelle = temps.temps() - temps_depart
if temps_actuelle > 60:
while True:
if temps_actuelle - 60 > 0:
minutes += 1
temps_actuelle -= 60
else:
secondes += int(temps_actuelle)
break
return [police1.render(temps(minutes, secondes), True, (0, 0, 0), (255, 255, 255)), temps(minutes, secondes)]
pygame.display.flip()
|
import abc
class Cipher(abc.ABC):
@abc.abstractmethod
def decrypt(self, index, data):
pass
class CeasarShift(Cipher):
def decrypt(self, index, data):
key = index + 1
message = data.upper()
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result = ""
for letter in message:
if letter in alpha: # if the letter is actually a letter
# find the corresponding ciphertext letter in the alphabet
letter_index = (alpha.find(letter) - key) % len(alpha)
result = result + alpha[letter_index]
else:
result = result + letter
return result
|
class StandardIWH:
def __init__(self, w: float) -> None:
"""Standard Inertia Weight Handler.
Parameters
----------
w : float
Inertia weight.
"""
self.w = w
def __call__(self, iteration: int) -> float:
"""Returns the inertia weight unchanged.
Parameters
----------
iteration : int
Current iteration of the optimisation process.
Returns
-------
float
Original inertia weight, unchanged.
"""
return self.w
class LinearIWH:
def __init__(self, w_init: float, w_end: float, n_iterations: int) -> None:
"""Linear Inertia Weight Handler.
Parameters
----------
w_init : float
Inertia weight at initialisation.
w_end : float
Inertia weight at end of optimisation.
n_iterations : int
Number of iterations.
"""
self.w_init = w_init
self.w_end = w_end
self.w_diff = self.w_init - self.w_end
self.n_iterations = n_iterations
def __call__(self, iteration: int) -> float:
"""Calculated linearly interpolated intertia weight.
Parameters
----------
iteration : int
Iteration for which to calculate the inertia weight.
Returns
-------
float
Inertia weight interpolated according to iteration.
"""
curr_w = self.w_init - self.w_diff * (iteration / self.n_iterations)
return curr_w
|
# File with sample functions.
def sum(x, y): # sums up two numbers
""" Adds two numbers.Returns the sum."""
return x + y
# Returns the product.
def mul(x, y):
# z is a local variable
z = x * y
return z |
message = "this is a statement in english"
# a starting consonant sound in your word moves to the end of the word followed by "ay"
# This -> isthay
# If the word starts with a wovel, then we add "way" to the end
# other -> otherway
translation = {}
translation["this"] = "isthay"
translation["statement"] = "atementstay"
translation['english'] = 'englishway'
words = message.split()
print(words)
for word in words:
if word in translation.keys():
print(translation[word])
else:
print(word)
|
def copied_word():
word = input("What's your favourite word? ")
print(word * 12)
print('"', word, '"' + " doens't sound like anymore.")
copied_word()
|
phrase = input("Enter a word or phrase:").lower()
data = '_'.join(phrase) + '_'
wrong = 0
while '_' in data and wrong < 6:
print('The thing to guess', data[1::2])
letter = input('What the letter ?').lower()
while len(letter) != 1:
letter = input('What letter ?')
odata = data
data.replace(letter + '_', letter + letter)
if odata == data:
wrong += 1
print('Sorry, there was no letter', letter, 'in the phrase')
else:
print('Good guess')
run += 1
if '_' in data:
print('You lose; it was', phrase)
else:
print('You won in', run, ' steps. The answer was', phrase)
|
votes = {"chipotle": 0,
"rev_soup": 0,
"mellow": 0,
"lemongrass": 0,
"other": 0
}
def vote(restaurant, votes):
"""tabulates one vote for a lunc h place"""
strategy = """Add restaurants to the votes dict
and add one to the values associated with the key in restautant
"""
votes[restaurant.lower()] += 1
def winner():
"""Determines where we are going to lunch, give a multiple in a list if a tie"""
plan = """find how many votes was the max among all give a list of all restaurants
tied for first place."""
max_votes = max(votes.values())
winners = []
for restaurant in votes:
if votes[restaurant] == max_votes:
winners.append(restaurant)
vote("chipoletle", votes)
vote("chipoletle", votes)
vote("chipoletle", votes)
vote("chipoletle", votes)
print(votes)
|
plan = """
dict of results -- election
keys: candidate
values: number of votes
vote(candidate, election)
get votes for this candidate
add 1
set votes for this candidate
ballot = [
"Luther Tychonievich",
"Jame Cohoon",
]
won(election)
"""
names = {"luther": "tychonievich",
"jim": "cohoon",
"james": "cohoon"}
def vote(candidate, election):
"""
Record a vote for 111x professor of the semester
:param candidate:
:param election:
:return:
"""
candidate = candidate.lower().strip()
if candidate in names:
candidate = names[candidate]
if candidate in election:
votes = election[candidate]
votes += 1
election[candidate] = votes
else:
election[candidate] = 1 # this vote is only vote
def won(election):
"""return the list of candidates with the most votes"""
best = []
most_votes = max(election.values())
# find candidate who won, by
# look at each key: key: value pair, for each
# check which of pair is the biggiest
for item in election.items():
candidate, votes = item
if vote == most_votes:
best.append(candidate)
return best
# Check the result
best111x = {}
vote('tychonievich', best111x)
vote('tychonievich', best111x)
vote('brunelle', best111x)
vote('Luther', best111x)
vote('brunelle', best111x)
vote('brunelle', best111x)
print(best111x)
print(won(best111x))
|
# cost = int(input("How much is it ?"))
# if cost > 10:
# cost -= 5
# print("I'll give you", cost, "for it.")
#
# if cost > 500:
# print("I will be paying with a check.")
# else:
# if cost > 20:
# print("I will be paying with cash.")
# else:
# if cost <= 200:
# print("I will be paying with a visa.")
# else:
# print("I will be paying with American express.")
#
#
cost = int(input("How much is it ?"))
if cost > 10:
cost -= 5
print("I'll give you", cost, "for it.")
if cost > 500:
print("I will be paying with a check.")
elif cost > 20:
print("I will be paying with cash.")
if cost <= 200:
print("I will be paying with a visa.")
else:
print("I will be paying with American express. ")
|
racial_words=["nigga","black","white","damn","hispanics","dark skinned"
,"chinks","white skinned","pakis","slave","slut","nigger"] # Set words that indicate racial slur in list #
file=open("Tweet_text_file.txt","r") # It is assumed that each tweet is in each #
count=0 # line in the text file, it is opened # #
def profanity_level(): # Function defined for printing the #
print() # profanity level #
print("Profaniry score : ",racial_count)
if racial_count==0:
print("Profanity level : Nil")
elif racial_count==1:
print("Profanity level : low")
elif racial_count==2:
print("Profanity level : Medium")
elif racial_count>=3:
print("Profanity level : High")
print()
while True: # Loop for reading each tweet from the file #
count=count+1
racial_count=0
line=file.readline()
if not line:
break
line_1="Tweet {}:\n\n {}".format(count,line.strip())
print(line_1)
# The tweet is cleaned by eliminating all #
line_1=line_1.replace(",","") # unwanted characters #
line_1=line_1.replace(".","")
line_1=line_1.replace("'","")
line_1=line_1.replace("?","")
line_1=line_1.replace("/","")
line_1=line_1.replace('"',"")
line_1=line_1.lower() # The cleaned tweet is lower cased to detect #
# words in the given list clearly so no word #
for j in racial_words: # is missed
if j in line_1:
racial_count=racial_count+1 # Loop function for calculating the score of #
# racial words and profanity level #
profanity_level()
file.close() # Closing the file #
|
####################################################
# Python by example
# Problem 003, 004, 005, 006, 007, 008
# Author: Omar Rahman
# Date: 12//2019
####################################################
print("-----------------------------------")
print(" Problem 3 ")
print("-----------------------------------")
print("What would you call a bear with no teeth?\nA Gummy bear!")
print("-----------------------------------")
print(" Problem 4 ")
print("-----------------------------------")
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
total = num1 + num2
print("The Total is " + str(total))
print("-----------------------------------")
print(" Problem 5 ")
print("-----------------------------------")
num3 = int(input("Enter a number: "))
num4 = int(input("Enter a number: "))
num5 = int(input("Enter a number: "))
total = num3 + num4
answer = total * num5
print("The answer is " + str(answer))
print("-----------------------------------")
print(" Problem 6 ")
print("-----------------------------------")
wholePizza = int(input("How many Pizza Slices were there?: "))
pizzaEaten = int(input("How many did you eat?: "))
remainingPizza = wholePizza - pizzaEaten
print("Pizza left: " + str(remainingPizza))
print("-----------------------------------")
print(" Problem 7 ")
print("-----------------------------------")
name = input("What is your name? => ")
age = int(input("How old are you? => "))
newAge = age + 1
print(name +" next birthday you will be",newAge) # this could be done with a comma as well
print("-----------------------------------")
print(" Problem 8 ")
print("-----------------------------------")
bill = int(input("How much is the bill: "))
diners = int(input("How many diners were there: "))
payment = bill / diners
print("Each Diner should pay $",payment)
|
#----------------------------------------------
# Problem 063
# Author: Omar Rahman
# Date: 1/1/2019
#----------------------------------------------
#--------------
# Sqaures with gaps
#--------------
import turtle
turtle.shape("turtle")
Screen = turtle.Screen()
Screen.bgcolor("green")
turtle.pensize(3)
turtle.color("red","red")
turtle.begin_fill()
#----------------------
for i in range(0,360):
turtle.forward(1)
turtle.right(1)
#----------------------
turtle.end_fill()
turtle.exitonclick() |
import math
def sumMultiples(factors, n): #Question 001
total = 0
for x in range(1, n):
for f in factors:
if x%f==0:
total += x
break
return total
def sumEvenTerms(list): #Question 002
sum = 0
for x in list:
if x%2==0: sum+=x
return sum
def fibonacci(n): #Terms <= n
list=[]
a=1
b=2
c=0
while(a<=n):
list.append(a)
c = a+b
a = b
b = c
return list
def nextPrime(ps):
if not ps: return 2
i = ps[-1] + 1
while(True):
isPrime = True
for p in ps:
if i%p==0:
isPrime = False
break
if isPrime: break
i+=1
return i
def primes(n:int):
ps = []
while(True):
np = nextPrime(ps)
if np>n: break
ps.append(np)
return ps
def primeFactors(n):
primes = [2]
p = 2
factors = []
while (True):
if n%p==0:
factors.append(p)
n = n//p
if n==1: break
else:
p = nextPrime(primes)
primes.append(p)
if not factors: return [n]
return factors
def palindrome(n:int):
s = str(n)
l = len(s)
for i in range(0, (l//2)):
if s[i]!=s[(l-i)-1]: return False
return True
def largestPalindromeProduct(d):
n = (10**d) - 1
nn = (10**(d-1)) - 1
for i in range(n,nn, -1):
pairs = pairsWhichSum(n, i)
products = map(lambda x: x[0]*x[1], pairs)
palindromes = list(filter(lambda x: palindrome(x), products))
if palindromes: return max(palindromes)
def pairsWhichSum(a, b):
result = []
while (a>=b):
result.append([a,b])
a-=1
b+=1
return result
def smallestMultiple(n):
primeFactorLists = []
for i in range(2, n+1): #Fetch prime factors for each number from 1 to n
primeFactorLists.append(primeFactors(i)) #Should make this more efficient by reusing calculated primes
d = {}
for primeFactorList in primeFactorLists:
consolidated = {}
for pf in primeFactorList:
if pf in consolidated:
consolidated[pf]+=1
else: consolidated[pf]=1
for k in consolidated:
if k in d:
if consolidated[k]>d[k]: d[k]=consolidated[k]
else:
d[k] = consolidated[k]
product = 1
for k in d:
product *= k**d[k]
return product |
n = int(input("Enter number of step(s)\n"))
list1 = [["" for y in range(n)] for x in range(n)]
print(list1)
def steps(n, y = 0, stair = ""):
if (y == n):
return;
if (n == len(stair)):
print(stair)
return steps(n, y+1)
if (len(stair) <= y):
stair += "#"
else:
stair += "1"
steps(n, y, stair)
steps(n)
|
# Some resources inspiring this demo:
# - https://www.learndatasci.com/tutorials/python-finance-part-yahoo-finance-api-pandas-matplotlib/
# - https://www.codingfinance.com/post/2018-04-05-portfolio-returns-py/
from pandas_datareader import data
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from datetime import date
# First define our 5 tech stocks:
tickers = ['AAPL', 'AMZN', 'GOOG', 'NFLX', 'TSLA']
# Get data starting in 2010 and ending today
start_date = '2010-01-01'
end_date = date.today()
# User pandas_reader.data.DataReader to load the desired data from Yahoo Finance
stock_data = data.DataReader(tickers, 'yahoo', start_date, end_date)
# Get the Adjusted Close columns and store it in a new object, prices
prices = stock_data['Adj Close']
prices.head()
# Calculate daily returns for each stock
returns = prices.pct_change(1)
# Fill missing values with 0
returns = returns.fillna(0)
returns.head()
# Assign weights
weights = [0.3, 0.3, 0.25, 0.10, 0.05]
# Calculate individually weighted returns
weighted_returns = (weights * returns)
weighted_returns.head()
# Sum across columns to calculate portfolio returns
portfolio_returns = weighted_returns.sum(axis=1).to_frame()
# Move Date index to column and rename returns column
portfolio_returns = portfolio_returns.reset_index()
portfolio_returns.rename(columns={0:'returns'}, inplace = True)
portfolio_returns.head()
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
ax1.hist(portfolio_returns['returns'], bins = 100)
ax1.set_xlabel('Portfolio returns')
ax1.set_ylabel("Freq")
plt.show();
|
class Stack:
def __init__(self):
self.items = []
def push(self, val):
self.items.append(val)
def pop(self):
try:
return self.items.pop()
except IndexError:
print("Stack is empty")
# Postfix 계산
# 1. 허용연산자 = 이항연산자(+,-,*,/,^)
# 2. 문자열의 연속된 두 항 사이에는 모두 공백 하나 ' '가 있음)
def compute_postfix(postfix):
S = Stack()
operators = ['+' , '-' , '*' , '/' , '^']
for token in postfix:
if '0' <= token <= '9':
S.push(float(token))
elif token == '+': #뎃셈
n1 = S.pop()
n2 = S.pop()
S.push(n2 + n1)
elif token == '-': #뺄셈
n1 = S.pop()
n2 = S.pop()
S.push(n2 - n1)
elif token == '*': #곱셈
n1 = S.pop()
n2 = S.pop()
S.push(n2 * n1)
elif token == '/': #나눗셈
n1 = S.pop()
n2 = S.pop()
S.push(float(n2 / n1))
elif token == '^': #제곱
n1 = S.pop()
n2 = S.pop()
S.push(float(n2 ** n1))
else:
S.push(token)
return S.pop()
res = compute_postfix(input().split())
print('%.4f ' %res) #소수점 이하 4자리까지 출력
|
from datetime import datetime, date
from dataclasses import dataclass
@dataclass
class User:
name: str
surname: str
address: str
date_of_birth: str # format is YYYY/MM/DD
def age(self, at_date: str = None) -> int:
dob = datetime.strptime(self.date_of_birth, "%Y/%m/%d")
today = date.today() if at_date is None else datetime.strptime(at_date, "%Y/%m/%d")
return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
|
#dfine validation function
def isValid():
#validate the date
monthValid = False
dayValid = False
sizeValid = False
yearValid = False
#set all validation to false to begin with and have user enter input
while (monthValid == False) or (dayValid == False) or (sizeValid == False) or (yearValid == False):
date = input("Please enter a date in the mm/dd/yy format: ")
#if statement to convert - to /
if date.find('-') != -1:
a = date.split('-')
elif date.find('/') != -1:
a = date.split('/')
#split month, day and year and set size of year to 2
month = a[0]
day = a[1]
year = a[2]
month = int(month)
day = int(day)
size = len(year)
year = int(year)
#create month list for validation statement
monthList = ['None', 'Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
#set parameters outside range. if user enters anything false, will return specific statements and go back to while loop
if (month > 12) or (month < 1):
monthValid = False
print("outside month range")
else:
monthValid = True
if (day > 31) or (day < 1):
dayValid = False
print("outside day range")
else:
dayValid = True
if (year != 13):
yearValid = False
print("outside year range")
else:
yearValid = True
if (size != 2):
sizeValid = False
print("date must be in format yy:")
else:
sizeValid = True
#if all validation statements are true, print longdate format
else:
year = "2013"
print("Your date is: ",(monthList[month]), " ", day, ", " , year, sep="")
|
import bankaccount
def main():
#get the starting balance.
start_bal = float(input('enter your starting balance: '))
#create a bankaccount object
savings = bankaccount.BankAccount(start_bal)
#deposit the user's payheck
pay = float(input("How muh were you paid this week? "))
print("I will deposit that into your account")
savings.deposit(pay)
#display your balance
print("Your acount balance is $", \
format(savings.get_balance(), ',.2f'),
sep = '')
#get amout to withdraw
cash = float(input("How much do you want to widthraw? "))
print("I will withdraw that from your acount.")
savings.withdraw(cash)
#display the balance
print("Your account balance is $", \
format(savings.get_balance(), ',.2f'),
sep='')
main()
|
import student2
student_list = [
student2.Student('Julie', 4.0, 23409, 'A', 'Ft'),
student2.Student('Joe', 4.0, 45678, 'A', 'Ft'),
student2.Student('Susie', 3.0, 52980, 'B', 'Pt'),
student2.Student('Sarah', 2.0, 45893, 'C', 'Ft'),
student2.Student('Sam', 1.0, 32409, 'F', 'Pt')
]
def displayMenu():
print(' MENU')
print('1) Look up and print the student GPA')
print('2) Add a new student to the class')
print('3) Change the GPA of a student')
print('4) Change the expected grade of a student')
print('5) Print the data of all the students in a tabular format')
print('6) Quit the Program')
def lookupPrintGPA():
Name = input("Name of the student: ")
for x in student_list:
if x.get_name() == Name:
x.printGPA()
def addNewStudent():
name = input("name: ")
gpa = input("GPA: ")
ID = input("ID: ")
expectedGrade = input("Expected Grade: ")
ftOrPt = input("Enter (FT) for full time or (PT) for part time: ")
OneStudent = student2.Student(name, gpa, ID, expectedGrade, ftOrPt)
student_list.append(OneStudent)
def changeGPA():
Name = input("Name of the student: ")
for x in student_list:
if x.get_name() == Name:
x.change_gpa()
print("The grade has been changed to: ")
x.printGPA()
def changeExpectedGrade():
Name = input("Name of the student: ")
for x in student_list:
if x.get_name() == Name:
x.change_expected_grade()
print("The grade has been changed to: ")
x.printExpectedGrade()
def printAllData():
for x in student_list:
print(x.get_name(), "\t", x.get_gpa(), "\t", x.get_ID(), "\t", x.get_expected_grade(), "\t", x.get_ftOrPt())
def main():
end_of_file = False
choice = 0
while choice != 6:
displayMenu()
choice = int(input('Please enter your choice: '))
if choice == 1:
lookupPrintGPA()
elif choice == 2:
addNewStudent()
elif choice == 3:
changeGPA()
elif choice == 4:
changeExpectedGrade()
elif choice == 5:
printAllData()
elif choice == 6:
print("Exiting the program")
else:
print("Error, invalid selection")
main()
|
carManufacturers = {'Ford': 5, 'Chevy': 10, 'Honda': 4, 'Maserati': 2}
carManufacturerNames = []
carManufacturerNames = list(carManufacturers.keys())
print"Car manufacturer:",carManufacturerNames[0],carManufacturers[carManufacturerNames[0]]
print("Car manufacturer:",carManufacturerNames[1],carManufacturers[carManufacturerNames[1]])
print("Car manufacturer:",carManufacturerNames[2],carManufacturers[carManufacturerNames[2]])
print("Car manufacturer:",carManufacturerNames[3],carManufacturers[carManufacturerNames[3]])
|
#define total Grades for the for statement
totalGrades = 12
#define main function
def main():
#open a file called grades.txt for writing to
grade_file = open('grades.txt', 'w')
#for statement to get name and average.
for choice in range(totalGrades):
name = input("Please enter the student's name: ")
average = int(input("Please enter the student's average grade: "))
#if average is valid, write name and average to grade file and close it
if (average > 0 and average < 101):
grade_file.write("\n The student's name is: ")
grade_file.write(name)
grade_file.write("\n The student's average is: ")
grade_file.write(str(average) + "")
else:
print("That is an invalid grade. Try again")
grade_file.close()
#try/except clause to open grades.txt and read it to the screen.
#if FileNotFoundError, print except statement
try:
read_file = open('grades.txt', 'r')
file_contents = read_file.read()
read_file.close()
print(file_contents)
except FileNotFoundError:
print("The grades file does not exist")
#call main
main()
|
def validVoter():
name = input("What is your name?")
age = int(input("How old are you %s?" % name))
if age >= 18:
return True
elif age > 100:
return ("You are not an elf")
elif age < 0:
return ("You cant be a negative age")
else:
return False
def display():
if validVoter():
print("You are of age!")
else:
print("You are not of age!")
def leapCheck(year):
if year % 100 == 0:
print("Not a leap year")
return False
elif year % 400 == 0:
return True
else:
print("It is a leap year")
return True
def isLeapYear():
year = int(input("What year do you want to see if it is a leap year?"))
if year % 4 == 0:
leapCheck(year)
else:
print("Not a leap year")
main()
|
import re
fileName='3.txt'
f=open(fileName,'r')
pattern='[^A-Z][A-Z][A-Z][A-Z][a-z][A-Z][A-Z][A-Z][^A-Z]'
s=""
for line in f:
m = re.search(pattern,line)
if m:
print(m.group().__getitem__(4))
s=s+m.group().__getitem__(4)
print(s)
# next level http://www.pythonchallenge.com/pc/def/linkedlist.html
# http://www.pythonchallenge.com/pc/def/linkedlist.php |
#Exercício 8
#Implemente um algoritmo que leia um número inteiro, em seguida calcule o fatorial deste número e apresente para o usuários.
#Ex: n = 4
#O Fatorial de 4 é 24
n = int(input("Digite um número: "))
x = 1
for i in range(n,0,-1):
x = x * i
print(x)
|
#Exercício 9
#Escreva um programa que imprima os n primeiros número primos. Peça para o usuário informar o valor de n.
n = int(input("Digite um número: "))
for i in range(1,n+1,1):
primo = True
for j in range(2,i):
if i % j == 0 :
primo = False
if primo :
print(i)
|
#!/usr/bin/python
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host=input('Enter the ip address:')
port=input('Enter the port number:')
port=int(port)
print('Server is initiated\nWait for Client to response')
s.bind((host,port))
s.listen(5)
c,addr=s.accept()
print('Welcome to the Messenging platform')
print('#Sc0Rpi0')
print('Connection from ',addr)
print('Starting........')
i = 0
while (i<100):
msg=input('User1:#\n')
# print('User1 type your message')
c.send(msg.encode('ascii'))
pass
print('User2:#')
# print('Wait for User2 to reply')
msg1=c.recv(10)
print(msg1.decode('ascii'))
pass
i += 1
|
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def BST_insert(root,node):
if node.val == root.val:
return root
if node.val < root.val:
if root.left:
BST_insert(root.left,node)
else:
root.left = node
else:
if root.right:
BST_insert(root.right,node)
else:
root.right = node
def BST_search(root,val):
if root.val == val:
return True
if val < root.val:
if root.left:
return BST_search(root.left,val)
else:
return False
elif val > root.val:
if root.right:
return BST_search(root.right,val)
else:
return False
def preorder_print(root,layers):
if not root:
return
for i in range(layers):
print('-----',end=' ')
print(root.val)
preorder_print(root.left,layers+1)
preorder_print(root.right,layers+1)
def midorder_print(root,layers):
if not root:
return
midorder_print(root.left,layers+1)
for i in range(layers):
print('-----',end=' ')
print(root.val)
midorder_print(root.right,layers+1)
nums = [3,10,1,6,15]
nodes = []
for x in nums:
nodes.append(TreeNode(x))
root = TreeNode(8)
for node in nodes:
print(node.val)
BST_insert(root,node)
preorder_print(root,0)
print("################")
midorder_print(root,0)
print(BST_search(root,3))
print(BST_search(root,10))
print(BST_search(root,140))
|
# 设计哈希集合
# 不使用任何内建的哈希表库设计一个哈希集合
#
# 具体地说,你的设计应该包含以下的功能
#
# add(value):向哈希集合中插入一个值。
# contains(value) :返回哈希集合中是否存在这个值。
# remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
#
# 示例:
#
# MyHashSet hashSet = new MyHashSet();
# hashSet.add(1);
# hashSet.add(2);
# hashSet.contains(1); // 返回 true
# hashSet.contains(3); // 返回 false (未找到)
# hashSet.add(2);
# hashSet.contains(2); // 返回 true
# hashSet.remove(2);
# hashSet.contains(2); // 返回 false (已经被删除)
#
# 注意:
#
# 所有的值都在 [1, 1000000]的范围内。
# 操作的总数目在[1, 10000]范围内。
# 不要使用内建的哈希集合库。
class MyHashSet_myself:
def __init__(self):
"""
Initialize your data structure here.
"""
self.table = [0] * 1000000
def add(self, key):
"""
:type key: int
:rtype: void
"""
k = key % 1000000
self.table[k] = 1
def remove(self, key):
"""
:type key: int
:rtype: void
"""
k = key % 1000000
# if self.table[k] == 1
self.table[k] = 0
def contains(self, key):
"""
Returns true if this set did not already contain the specified element
:type key: int
:rtype: bool
"""
k = key % 1000000
if self.table[k] == 1:
return True
return False
class MyHashSet:
def __init__(self):
self.data = [[] for i in range(0, 10000)]
def add(self, key):
if not key in self.data[(key-1)//100]:#在[1,1000000]的范畴内,key//100-1和(key-1)//100不等效
# if not self.contains(key):##这里能直接用contain的
self.data[(key-1)//100].append(key)
def remove(self, key):
if self.contains(key):
self.data[(key-1)//100].remove(key)
def contains(self, key):
return key in self.data[(key-1)//100]
class MyHashSet_v2:
def __init__(self):
self.bucket = 1000
self.inner_bucket = 1001
self.hashset = [[] for i in range(self.inner_bucket)]#他为了逻辑简洁,多出来了一个?这是桶的内部,其实算下来,就是多了1000个
def hash(self, key):
return key % self.bucket
def point(self, key):
return key // self.bucket
def add(self, key):
hashkey = self.hash(key)
if not self.hashset[hashkey]:
self.hashset[hashkey] = [0] * self.inner_bucket#还要一次初始化
self.hashset[hashkey][self.point(key)] = 1
def remove(self, key):
"""
:type key: int
:rtype: void
"""
hashkey = self.hash(key)
if self.hashset[hashkey]:
self.hashset[hashkey][self.point(key)] = 0
def contains(self, key):
"""
Returns true if this set did not already contain the specified element
:type key: int
:rtype: bool
"""
hashkey = self.hash(key)
return self.hashset[hashkey] != [] and self.hashset[hashkey][self.point(key)] == 1
# Your MyHashSet object will be instantiated and called as such:
obj = MyHashSet()
obj.add(5)
print(obj.contains(5))
obj.remove(5)
print(obj.contains(5))
print(1//100) |
# 计数质数
# 统计所有小于非负整数 n 的质数的数量。
#
# 示例:
#
# 输入: 10
# 输出: 4
# 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
# 一个思路是,逢2、3、5的倍数就跳过去,从根本上减少需要循环检测的数据
# if (i > 2 and i % 2 == 0) or (i > 3 and i % 3 == 0) or (i > 5 and i % 5 == 0) or (i > 7 and i % 7 == 0):
# 还是蠢,还是慢!
import math
class Solution:
def countPrimes_overtime(self, n):
"""
:type n: int
:rtype: int
"""
primes = []#换成字典并不能解决问题,终归要遍历的,字典访问也是O(1),下标访问也是O(1)
if n < 3:
return len(primes)
for i in range(2,n):
j = 0
m = len(primes)
while j < m:
if i % primes[j] == 0:
break
j += 1
if j == m:
primes.append(i)
print(primes)
return len(primes)
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
#primes = []#换成字典并不能解决问题,终归要遍历的,字典访问也是O(1),下标访问也是O(1)
sum = 0
if n < 3:
return sum
for i in range(2,n):
if i == 2 or i == 3:
sum += 1
continue
# print('================i:',i)
sqrt_i = int(math.sqrt(i))
# print(' sqrt_i+1:',sqrt_i + 1)
for j in range(2, sqrt_i+1):
# print('j:',j,' sqrt_i+1:',sqrt_i + 1)
if i % j == 0:
break
if j == sqrt_i:
# print('prime')
sum += 1
return sum
# def countPrimes(self,n):
# import math
#
# count=0
#
# def judge_prime(w):
# sqrt_w=int(math.sqrt(w))
# for i in range(2,sqrt_w+1):
# print('i:',i,' x:',x,' sqrt_w+1:',sqrt_w+1)
#
# if x%i==0:
# return 0
# return 1
#
# for x in range(2,n):
#
# count=count+judge_prime(x)
# return count
# def countPrimes(self, n):
# if n < 3:
# return 0
# primes = [True] * n
# primes[0] = primes[1] = False
# for i in range(2, int(n ** 0.5) + 1):
# if primes[i]:
# primes[i * i: n: i] = [False] * len(primes[i * i: n: i])
# return sum(primes)
# ---------------------
# 作者:二当家的掌柜
# 来源:CSDN
# 原文:https://blog.csdn.net/github_39261590/article/details/73864039
# 版权声明:本文为博主原创文章,转载请附上博文链接!
# class Solution {
# public int countPrimes(int n) {
# int count = 0;
#
# boolean flag[] = new boolean[n]; // 初始全都false
#
# for (int i = 2; i < n; i++)
# if (flag[i] == false){
# count ++;
# for (int j = 1; j * i < n; j++)
# flag[j * i] = true;
# }
#
#
# return count;
# }
# }
s = Solution()
print(s.countPrimes_overtime(100))
# print(10%5)
# print(6%10)
# dic = {5:3,6:5}
# print('l:',len(dic))
# for i in dic:
# print(i)
# print(dic[i]) |
# 至少是其他数字两倍的最大数
# 在一个给定的数组nums中,总是存在一个最大元素 。
#
# 查找数组中的最大元素是否至少是数组中每个其他数字的两倍。
#
# 如果是,则返回最大元素的索引,否则返回 - 1。
#
# 示例
# 1:
#
# 输入: nums = [3, 6, 1, 0]
# 输出: 1
# 解释: 6
# 是最大的整数, 对于数组中的其他整数,
# 6
# 大于数组中其他元素的两倍。6
# 的索引是1, 所以我们返回1.
#
# 示例
# 2:
#
# 输入: nums = [1, 2, 3, 4]
# 输出: -1
# 解释: 4
# 没有超过3的两倍大, 所以我们返回 - 1.
#
# 提示:
#
# nums
# 的长度范围在[1, 50].
# 每个
# nums[i]
# 的整数范围在[0, 99].
class Solution:
def dominantIndex_myself(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first = 0
first_index = -1
second = 0
second_index = -1
for i,v in enumerate(nums):
if v > second:
second = v
second_index = i
if second > first:
second,first = first,second
second_index,first_index = first_index,second_index
# print(first,second)
# print(first_index,second_index)
if first >= second * 2:
return first_index
return -1
def dominantIndex(self, nums):#40ms
"""
:type nums: List[int]
:rtype: int
"""
maxn = max(nums)
for item in nums:
if maxn < 2 * item and maxn != item:
return -1
return nums.index(maxn)
nums = [0,0,0,1]
s = Solution()
print('ret:',s.dominantIndex(nums))
|
# 数组拆分 I
# 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。
#
# 示例 1:
#
# 输入: [1,4,3,2]
#
# 输出: 4
# 解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4).
# 提示:
#
# n 是正整数,范围在 [1, 10000].
# 数组中的元素范围在 [-10000, 10000].
# 思路:其实就是排序,按顺序拿。只有按顺序拿,才能保证被min操作牺牲掉的数值更少
class Solution:
def arrayPairSum_myself(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
nums.sort()
n = len(nums)
i = 0
sum = 0
while i < n:
# sum += min(nums[i],nums[i+1])已经排序了,就不用min操作了。
sum += nums[i]
i += 2
return sum
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return sum(nums[0::2])#更快捷的操作
l = [1,4,3,2]
s = Solution()
print('ret:',s.arrayPairSum(l))
print(l[0::])
print(l[0::1])
print(l[0::2])
# print(l[0::2])
|
# 如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
#
# 例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。
#
# 给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。
#
# 感觉就是简单遍历,这里注意一点就行吧,就是每次失败了,重置长度不是0
class Solution:
def wiggleMaxLength_wrong(self, nums):#少看了一句话,他可以在里边删除元素,自由组合,这也叫子序列。。。。
max_count = 0
count = 0
is_increment = None
last_val = None
for val in nums:
if last_val == None:#init
count += 1
last_val = val
continue
sub = val - last_val
print('sub:',sub)
if is_increment == None:#init
if sub > 0:
is_increment = True
count += 1
elif sub < 0:
is_increment = False
count += 1
else:#reset
#is_increment = None
count = 1
continue
else:
if is_increment == True:
if sub < 0:
count += 1
is_increment = False
else:#reset
count = 1
if sub > 0:
is_increment = True
else:#==0
is_increment = None
continue
else:
if sub > 0:
count += 1
is_increment = True
else:#reset
count = 1
if sub < 0:
is_increment = False
else:#==0
is_increment = None
continue
max_count = count
last_val = val#update last_val
return max_count
def wiggleMaxLength_myself(self, nums):#AC
last_val = None
is_increment = None
count = 0
for val in nums:
# print('last_val:',last_val)
# print('count:',count)
if last_val != None:
sub = val - last_val
if is_increment == None:
if sub > 0:
is_increment = True
elif sub < 0:
is_increment = False
else:
continue
else:
if is_increment == True:
if sub < 0:
# count += 1
# last_val = val
is_increment = False
elif sub > 0:
# last_val = val
count -= 1#为了抵消统一的count++
else:
continue
else:
if sub > 0:
# count += 1
# last_val = val
is_increment = True
elif sub < 0:
count -= 1#为了抵消统一的count++
else:
continue
count += 1
last_val = val
return count
class Solution:##和我时间一样的典型范例,算是用了一个宏
UP, DOWN, BEGIN = 0, 1, 2
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return len(nums)
state = Solution.BEGIN
cnt = 1
for i in range(1, len(nums)):
delta = nums[i] - nums[i - 1]
if state == Solution.BEGIN:
if delta == 0:
state = Solution.BEGIN
elif delta > 0:
state = Solution.UP
cnt += 1
else:
state = Solution.DOWN
cnt += 1
elif state == Solution.UP:
if delta >= 0:
state = Solution.UP
else:
state = Solution.DOWN
cnt += 1
elif state == Solution.DOWN:
if delta <= 0:
state = Solution.DOWN
else:
state = Solution.UP
cnt += 1
return cnt
input = [1,7,4,9,2,5]
# 输出: 6
input = [1,17,5,10,13,15,10,5,16,8]
# 输出: 7
#
input = [1,2,3,4,5,6,7,8,9]
# 输出: 2
# 感觉遇到不合适的不更新last_val也不对,比如这样1,2,3,4,5,4,应该能到3的,但是不更新的话,应该还是2
input = [1,2,4,3]
#那应该是,如果当前状态同为增,且这个数字更大,更新;如果当前状态为减,切数字更小,更新。!
#但是这时候还不加count
sol = Solution()
print(sol.wiggleMaxLength(input))
|
class Solution:
def merge_sort_two(self,nums1,nums2):
result = []
i = 0
j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
result.append(nums1[i])
i += 1
else:
result.append(nums2[j])
j+=1
for k in range(i,len(nums1)):
result.append(nums1[k])
for k in range(j,len(nums2)):
result.append(nums2[k])
return result
def merge_sort(self,nums):
n = len(nums)
if n < 2:
return nums
mid = n // 2
nums1 = self.merge_sort(nums[0:mid])
nums2 = self.merge_sort(nums[mid:])
return self.merge_sort_two(nums1,nums2)
# 他假设这两个子序列有序。
# 前提是,两边相等时,算法是优先插左边的。
#
# 归并排序过程中:
# 他这个规律是,既然不逆序,左边的元素互相都不干扰,你count是几,说明右边有几个比你小的,所以在归并排序过程中,就是j对应的值,j = 0,说明一个比你小的都没有。
# 所以解法就是,进行归并排序,然后在排序过程中,顺便给左边的就给存了count,然后归并能把右边的也分解成左右。
#
# 感觉这么个归并过程,count不只是j,是count += j,好几层累加呢。
# 但是返回顺序怎么办,我返回的结果顺序要原来的,不是打乱后的,得做一个映射,但是最起码,理论上是可行的。
# 所以就是做一个映射,一个dict或者pair这样的东西,我无论怎么排序,都给原始的那个count做累加,就得到结果了
#
# 那么重复的部分呢,如果你先插右边的,左边的count认定就会多 + 1,实际上5不是5的逆序数,不应该加,但是他也没保持不动,他合并了?没有!!!这个图还没完,你看1就是双份。
# 明显感觉到,即便思路有了,实现也差点,数据结构和接口这些还是欠缺。我觉得如果是python,就用一个tuple就行了吧,tuple[0]
# 存nums的实际值,tuple[1]
# 存对应count中的下标,我只去比tuple[0],然后找到count[tuple[1]]
# 去做增量操作
#我需要给排序那个做变形,我传进去的可能是[tuple()]
def countSmaller(self, nums):#AC:364ms
n = len(nums)
count = n * [0]
nums = [(i,nums[i]) for i in range(len(nums))]
ret = self._merge_sort(nums,count)
return count
def _merge_sort_two(self,nums1,nums2,count):
result = []
i = 0
j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i][1] <= nums2[j][1]:
result.append(nums1[i])
count[nums1[i][0]] += j
i += 1
else:
result.append(nums2[j])
j+=1
for k in range(i,len(nums1)):
result.append(nums1[k])
count[nums1[k][0]] += j
for k in range(j,len(nums2)):
result.append(nums2[k])
return result
def _merge_sort(self,nums,count):#分治过程不用改,主要去改排序实际操作,根据映射修改count就好了
n = len(nums)
if n < 2:
return nums
mid = n // 2
nums1 = self._merge_sort(nums[0:mid],count)
nums2 = self._merge_sort(nums[mid:],count)
return self._merge_sort_two(nums1,nums2,count)
# 第二个方法,逆置数组,由求后边比自己小的个数,改成求前边比自己小的个数,给节点加个计数器,每次比某一节点大,加上这个计数。
# 当然,这个计数器维护也需要考虑
#往它左子树插1,计数器+1,往它右子树插的话,当前节点不计,右子树的数量记在当前节点的父节点。
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.count = 0
self.repeat = 0
class Solution2:
def BST_insert(self,root, node,total_count):#因为是递归的,total count要传参进去
print('##################current node:',node.val)
if node.val == root.val:
total_count += root.count
#这也是个坑点,碰到重复元素,计数器还是要更新的,你一堆2,3来了不可能只算一个吧...但是加了好像也不对,比2小的是1,我再碰到2,却给2这个点+1,那以后碰到2,不是也加1了?
#碰到重复的2时,其实我应该做的,是给2的右子树全都 + 1.。。。。
#或者我再用一个计数器,就是计算重复的
#都怪那个网课坑,他说用一个count,我不知道他想怎么利用一个count解决这个重复问题
#他的方法是,重复的也插入,插前边
root.repeat += 1
return total_count
if node.val < root.val:
root.count += 1#update counter
print('node',root.val,'\'scount updated to:',root.count)
if root.left:
return self.BST_insert(root.left, node,total_count)
else:
root.left = node
else:
print('node > root')
total_count += root.count
total_count += root.repeat
total_count += 1#include root self
if root.right:
return self.BST_insert(root.right, node,total_count)
else:
root.right = node
return total_count
def countSmaller(self, nums):
if not nums:
return []
nums = nums[::-1]
n = len(nums)
count = n * [0]
print('reversed:',nums)
root = TreeNode(nums[0])
for i in range(1,len(nums)):
print('nums[i]:',nums[i])
node = TreeNode(nums[i])
current_cnt = self.BST_insert(root,node,0)
print('current count:',current_cnt)
count[i] = current_cnt
print('count:',count)
count = count[::-1]
print('count:',count)
return count
class Solution3:
def BST_insert(self, root, node, total_count): # 因为是递归的,total count要传参进去
if node.val <= root.val:
root.count += 1 # update counter#其实在等于的时候,这样改,已经改坏了,但是之前已经拿到想要的结果了,所以不影响。
if root.left:
return self.BST_insert(root.left, node, total_count)
else:
root.left = node
else:
total_count += root.count
total_count += root.repeat
total_count += 1 # include root self
if root.right:
return self.BST_insert(root.right, node, total_count)
else:
root.right = node
return total_count
def countSmaller(self, nums):
if not nums:
return []
nums = nums[::-1]
n = len(nums)
count = n * [0]
root = TreeNode(nums[0])
for i in range(1, len(nums)):
node = TreeNode(nums[i])
current_cnt = self.BST_insert(root, node, 0)
count[i] = current_cnt
count = count[::-1]
return count
nums1 = [1,6,9,13,22,55,222]
nums2 = [2,7,8,15,22,77,344]
sol = Solution()
print('ret:',sol.merge_sort_two(nums1,nums2))
nums = [3,3,4,5,5,2,3,34,3,42,324]
print('ret:',sol.merge_sort(nums))
nums = [3,2,2,3,1,2,0]
sol.countSmaller(nums)
print('hello')
sol2 = Solution3()
sol2.countSmaller(nums)
|
class Solution:
# def merge(self, nums1, m, nums2, n):
# """
# :type nums1: List[int]
# :type m: int
# :type nums2: List[int]
# :type n: int
# :rtype: void Do not return anything, modify nums1 in-place instead.
# """
# j = 0
# i = 0
# total_c = 0
# while i < m+n:
# print('start with i:',i,' j:',j)
# c = 0
# tmp = []
# print('nums1:',nums1)
# print('nums2:',nums2)
# while j < n and nums2[j] < nums1[i]:
# tmp.append(nums2[j])
# j += 1
# c += 1
# print('c:',c)
# if c != 0:
# # print('i:',i)
# # print('c:',c)
# # print('m:',m)
# # print('before:',nums1)
# # nums1[i+c:i+m+c] = nums1[i:i+m]
# nums1[i+c:m+n] = nums1[i:i+m-total_c]#
# # print('before:',nums1)
# nums1[i: i + c] = tmp[:]
# # print('after:',nums1)
# i += c
# total_c += c
# # print('total_c:',total_c)
# # print('m:',m)
# if nums1[i] == 0:
# # print('i:',i)
# nums1[i] = nums2[j]
# j+=1
# # print('nums1:',nums1)
# if j >= n:
# break
#
# i += 1
# # print('new i:',i)
# def merge(self, nums1, m, nums2, n):
# """
# :type nums1: List[int]
# :type m: int
# :type nums2: List[int]
# :type n: int
# :rtype: void Do not return anything, modify nums1 in-place instead.
# """
# i = 0
# j = 0
# total_c = 0
# while i < m + total_c:
# print('i:',i,' j:',j)
# print('nums1:',nums1)
# if nums2[j] < nums1[i]:
# nums1[i+1:i+m+1] = nums1[i:i+m]
# nums1[i] = nums2[j]
# # print(nums1)
# j += 1
# total_c += 1
# else:
# nums1[i+1] = nums2[j]
# j += 1
# total_c += 1
#
# i += 1
# if j >= n:
# break
# def merge(self, nums1, m, nums2, n):
# """
# :type nums1: List[int]
# :type m: int
# :type nums2: List[int]
# :type n: int
# :rtype: void Do not return anything, modify nums1 in-place instead.
# """
# # sort()可以换成手动快速排序。这个问题绕弯路的根本原因是,把数组的复制复杂化.
# # 数组不像链表,不需要刻意一段一段的拆解,数组可以整段移动。
# # 其实我前边的做法也用到了整段移动,所以,吃亏了。
# nums1[m:m+n] = nums2[:]
# print(nums1)
# nums1.sort()
# print(nums1)
def merge(self, nums1, m, nums2, n):
# 利用数组1后边的空间
# two points
p1 = m - 1
p2 = n - 1
p3 = m + n - 1
# print('init:\tp1:{0}\tp2:{1}\tp3:{2}'.format(p1,p2,p3))
while p3 >= 0:
if p1 >= 0 and p2 >= 0:
if nums1[p1] > nums2[p2]:
nums1[p3] = nums1[p1]
p1 -= 1
else:
nums1[p3] = nums2[p2]
p2 -= 1
elif p1 >= 0:
nums1[p3] = nums1[p1]
p1 -= 1
elif p2 >= 0:
nums1[p3] = nums2[p2]
p2 -= 1
p3 -= 1
# print(nums1)
# if p1 == -1 and p2 == -1:
# break
# print('p1:{0}\tp2:{1}\tp3:{2}'.format(p1,p2,p3))
array = [1,2,3,0,0,0]
array2 = [2,5,6]
print(array)
# array[3:6] = array[0:3]
# print(array)
# array[0:3] = array2[:]
#
# print(array)
# array = [-1, -1]
# print(array)
# # print(array.index(2))
# # print(array.index(3))
# print(array.count(3))
# array2 = []
# # array2.sort()
# k = 2
# # a = array[:k]
# # print('a:',a)
# # a.sort()
# # print('a:',a)
s1 = Solution()
print('ret:',s1.merge(array,3,array2,3))#m=4,n=3
# print(s1.removeDuplicates(array2))
print(array)
|
# 搜索旋转排序数组
# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
# 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
# 你可以假设数组中不存在重复的元素。
# 你的算法时间复杂度必须是 O(log n) 级别。
# 思路,循环数组,mid的计算特殊处理。但是也不是绝对的O(logn),最起码找到起始点还需要n的吧?
class Solution:
# def search(self, nums, target):
# """
# :type nums: List[int]
# :type target: int
# :rtype: int
# """
# n = len(nums)
# if n == 0:
# return -1
# elif n == 1:
# if target == nums[0]:
# return 0
# return -1
# elif n == 2:
# if target == nums[0]:
# return 0
# elif target == nums[1]:
# return 1
# else:
# return -1
# right = n-1
# for i in range(len(nums)-1):
# if nums[i] > nums[i+1]:
# right = i
# break
# left = (right + 1) % n
# # print(left,right)
# # mid = (left + ((right + n - left) // 2)) % n
# # print('mid:',mid)
# while left != right:
# print('left&right:',left,right)
# if right < left:
# mid = (left + ((right + n - left) // 2)) % n
# else:
# mid = (left + right) // 2
# # print('mid:',mid)
# if target > nums[mid]:
# left = ( mid + 1 ) % n
# elif target < nums[mid]:
# if right == left + 1:
# print('break')
# break
# right = ( mid - 1 ) % n
# else:
# return mid
#
# # if left == right:#no need
# if nums[left] == target:
# return left
# return -1
# 不想用这个弱智模板,太麻烦
# 简单的写法反而通过了
def search_mysel(self, nums, target):
if not nums:
return -1
n = len(nums)
right = n-1
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
right = i
break
left = (right + 1) % n
def search_func(nums,target):
left = 0
right = len(nums)-1
while left <= right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
else:
return mid
return -1
if left > right:
if -1 == search_func(nums[left:]+nums[:right + 1],target):
return -1
return (search_func(nums[left:]+nums[:right + 1],target) + left) % n
else:
return search_func(nums,target)
return -1
# 真正的logN算法
#最推荐的方法,逻辑简洁明了:如果左区间有序,并且target在左区间,就去左区间找,否则去右;如果右区间有序,并且target在右区间,就去右区间找,否则去左。
def search_other(self, nums, target):#44ms
left, right = 0, len(nums)-1
while left <= right:
mid = (left+right) // 2
if nums[mid] == target:
return mid
#首先确定mid属于哪个有序序列中
elif nums[mid] >= nums[left]: #确定在上个升序序列中,这里要注意针对数组中只有两个数时的边界问题,=号要放在这里,如果这里用等号,后面nums[mid] <= nums[right]就会陷入死循环,比如实例:[3,1]0
#然后确定target属于哪个部分
if target >= nums[left] and target < nums[mid]: #双重条件才能确定target在mid的前半部分(升序序列的子序列),否则在后半部分(可能是两个升序序列的结合)
right = mid - 1
else:
left = mid + 1
elif nums[mid] < nums[right]:
if nums[mid]<target and target<=nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
#logN算法,框架是二分查找,经过多个条件对比和处理
#但是网课这个破逻辑明显不如上边那个简单清晰,可能是太过于强行套框架了?
# 我不知道算不算生搬硬套二分查找框架,反正他的逻辑是,先区分target比mid大还是小,然后细分之后还可能推翻这个区分,细化一堆逻辑
#强行抄下来以后,答案却是对,但是确实乱,你target小于mid,搞一堆begin和mid的判断,你target大于mid,还用begin和mid,这就太乱了
#他的左右侧都用同一种逻辑,是因为判断哪边升序哪边旋转的逻辑根本不该放在最后,如果真的放最后,你最好用对应的逻辑,别用同一套逻辑
def search(self, nums, target):
begin = 0
end = len(nums) - 1
while begin <= end:
mid = (begin + end) // 2
# 二分查找的主体框架是target比mid大或者小
# 但是旋转数组的话这个逻辑又是错的,所以在细分的逻辑里还得兜回去
if target == nums[mid]:
return mid
elif target < nums[mid]:
if nums[begin] < nums[mid]:#有序区间
if target >= nums[begin]:#true
end = mid - 1
else:##false:推翻了前边的逻辑,还得往另一个区间跑
begin = mid + 1
elif nums[begin] > nums[mid]:#乱序区间:这块才是关键逻辑,前边已经确定了target比mid小,但是这块逻辑并不能说明问题,而是隐含的右侧区间有序,才证明target比右侧的都小
end = mid - 1
elif nums[begin] == nums[mid]:#如果持平了,他就再进一格,再尝试
begin = mid + 1
elif target > nums[mid]:
if nums[begin] < nums[mid]:
begin = mid + 1
elif nums[begin] > nums[mid]:
if target >= nums[begin]:
end = mid - 1
else:
begin = mid + 1
elif nums[begin] == nums[mid]:
begin = mid + 1
return - 1
# elif target > nums[mid]:
# if nums[mid] < nums[end]:
# if target < nums[end]:
# begin = mid + 1
# else:
# end = mid - 1
# elif nums[mid] > nums[end]:#rotated nums[begin] < nums[mid]
# begin = mid + 1
# elif nums[mid] == nums[end]:
# begin = mid - 1
nums = [4,5,6,7,0,1,2]
nums = [4,5,6,7,0,1,2]
target = 6
nums = [4,5,6,7,0,1,2]
target = 3
nums = [1,3]
target = 4
nums = [1,2,3,6,7,9]
target = 0
nums = [3,1]
target = 0
nums = [4,5,6,7,0,1,2]
target = 1
nums = []
target = 5
# print(nums[3:])
s = Solution()
print('ret:',s.search(nums,target)) |
# x 的平方根
# 实现 int sqrt(int x) 函数。
# 计算并返回 x 的平方根,其中 x 是非负整数。
# 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
# 示例 1:
# 输入: 4
# 输出: 2
# 示例 2:
# 输入: 8
# 输出: 2
# 说明: 8 的平方根是 2.82842...,
# 由于返回类型是整数,小数部分将被舍去。
# 优化:超过4以后,应该right直接用x // 2就够吧。,废话,超过9还能用x//3呢.所以说,可以动态的用x的平方根?但是你找的就是平方根,找到了就不用搜了!!
# 利用平方计算?mid ** 2,大于x算结束?保留之前的不大于x的mid,那用什么二分查找啊?
# 那就先把各iter平方和都存起来?有这个复杂度,还用什么二分查找?直接从头到尾遍历,直到平方大于等于x,那多好?#提交结果:超出时间限制!!!!!!!!!!!!!
# 整体思路是循环找不到小数,对小数结果的边界进行处理
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left = 1
right = x
mid = 1
while left <= right:
# print('left:{0},right:{1}'.format(left,right))
mid = (left + right) // 2#left + (right - left) // 2
# print('mid:',mid)
if x // mid == mid:
return mid
elif x // mid > mid:
left = mid + 1
else:
right = mid - 1
# print('finish:left:{0},right:{1}'.format(left,right))
#return mid finish:mid: 3 left:3, right: 2 return 3
return right
# 为什么拿right,找到最后没找到,说明真实的小数处于right和left之间。因为现在已经right小于left了,所以拿right。
# 结束前left==right,结束时无论是right-=1还是left+=1,取更小的那个整数,都是right,而如果用mid的话,最后一步是right-1就完了
# def mySqrt(self, x):
# """
# :type x: int
# :rtype: int
# """
# return int(x ** (1/2))
# def mySqrt_slow(self, x):
# """
# :type x: int
# :rtype: int
# """
# sqrt = 0
# while sqrt < x:
# if (sqrt+1)**2 >x:
# return sqrt
# sqrt+=1
# return sqrt
s = Solution()
print(s.mySqrt(7))
|
#adding two numbers in three lines
a = int(input())
b = int(input())
print(a+b)
|
# 寻找旋转排序数组中的最小值
# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
#
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
#
# 请找出其中最小的元素。
#
# 你可以假设数组中不存在重复元素。
#
# 示例 1:
#
# 输入: [3,4,5,1,2]
# 输出: 1
# 示例 2:
#
# 输入: [4,5,6,7,0,1,2]
# 输出: 0
# 被专题的模板坑了,其实可能并不适用?
class Solution:
def findMin_myself(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if not n:
return 0
left = 0
right = n - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[mid+1]:#实测这一步确实能加速
return nums[mid+1]
elif nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[right]
def findMin_v1(self, nums):#和我一样的,没我的对比拦截,按理说更慢,同时提交,确实更慢
i = 0
j = len(nums) - 1
while i < j:
m = i + (j - i) // 2
if nums[m] > nums[j]:
i = m + 1
else:
j = m
return nums[i]
def findMin(self, nums):#和我一样的
"""
:type nums: List[int]
:rtype: int
"""
low,high = 0,len(nums)-1
while low < high:
if nums[low] < nums[high]:#这个条件和我有所不同,确实也可以用,旋转不可能有其他情况
return nums[low]
mid = (low+high)//2
if nums[mid] >= nums[low]:
low = mid+1
else:
high = mid
return nums[low]
nums = [4,5,6,7,0,1,2]
nums = [1,2,4,5,6,7,0,]
nums = [0,1,2,4,5,6,7,]
nums = [5,1,2,3,4,]
s = Solution()
print('ret:',s.findMin(nums))
|
# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
#
# 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
#
# 注意:给定 n 是一个正整数。
#
# 示例 1:
#
# 输入: 2
# 输出: 2
# 解释: 有两种方法可以爬到楼顶。
# 1. 1 阶 + 1 阶
# 2. 2 阶
# 示例 2:
#
# 输入: 3
# 输出: 3
# 解释: 有三种方法可以爬到楼顶。
# 1. 1 阶 + 1 阶 + 1 阶
# 2. 1 阶 + 2 阶
# 3. 2 阶 + 1 阶
class Solution:
def climbStairs_myself(self, n):
if n == 0:
return 0
if n == 1:
return 1
dp = n * [0]
dp[0] = 1
dp[1] = 2
for i in range(2,n):
dp[i] = dp[i-1] + dp[i-2]
return dp[n-1]#这是错位的,n对应n-1,因为0下标占了一个,也可以从1下标开始
def climbStairs(self, n):
dp = (n+3) * [0]#他这个写法,反而能达到简洁的效果
dp[1] = 1
dp[2] = 2
for i in range(3,n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
n = 2
sol = Solution()
print('ret:',sol.climbStairs(n))
|
# 实现strStr()
# 实现 strStr() 函数。
#
# 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
#
# 示例 1:
#
# 输入: haystack = "hello", needle = "ll"
# 输出: 2
# 示例 2:
#
# 输入: haystack = "aaaaa", needle = "bba"
# 输出: -1
# 说明:
#
# 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
#
# 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
class Solution:
def strStr_myself(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == '':
return 0
if len(haystack) < len(needle):
return -1
for i in range(len(haystack)):
k = i
if (len(haystack) - k) < len(needle):
return -1
for j in range(len(needle)):
if haystack[k] != needle[j]:
break
if j == len(needle) - 1:
return i
k += 1
return -1
def strStr(self, haystack, needle):
if not needle:
return 0
for i in range(len(haystack)-len(needle)+1):
if haystack[i] == needle[0]:
j = 1 #j = 0#放心,没问题,从1开始
while j < len(needle) and haystack[i+j] == needle[j]:
j+=1 #如果接下来相等,则j不断增加
if j == len(needle):
return i
return -1
#相当于是python中find的底层应用
#可以循环,找到第一个相同的字母,记录下位置i和新的下标j,然后逐一对比是否相同
#因为找第一个位置,因此就只循环长-短的就好
#首先判断特殊情况
s = Solution()
# print('ret:',s.strStr(haystack = "helllllo", needle = "llo"))
print('ret:',s.strStr(haystack = "", needle = "a"))
str1 = 'hllla'
str2 = 'lla'
print(str1.find(str2))
|
# 反转字符串中的单词 III
# 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
#
# 示例 1:
#
# 输入: "Let's take LeetCode contest"
# 输出: "s'teL ekat edoCteeL tsetnoc"
# 注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
class Solution:
def reverseWords_myself(self, s):#use api
strs = s.split(' ')
res = ''
print(strs)
for i,k in enumerate(strs):
kk = list(k)
l = 0
r = len(kk) - 1
while l < r:
tmp = kk[l]
kk[l] = kk[r]
kk[r] = tmp
l += 1
r -= 1
# print('kk:',kk)
temp = ''.join(kk)
res += temp
if i != len(strs) - 1:
res += ' '
# print('res:',res)
# print(list)
return res
def reverseWords_v2(self, s):
s_lst = s.split(' ')
output_s = ''
for x in s_lst:
output_s += (x[::-1] + ' ')
return output_s[:-1]#利用[:-1]把多余的空格删掉
# 熟练的转换,还有join的用法
def reverseWords(self, s):
print(s[::-1])
print(s[::-1].split())
print(s[::-1].split()[::-1])
print(' '.join(s[::-1].split()[::-1]))
return ' '.join(s[::-1].split(' ')[::-1])
strs = "Let's take LeetCode contest"
s = Solution()
print('ret:',s.reverseWords(strs))
# l2 = ['a','e','d']
# s2 = str(l2)
# print('s2:',s2)
|
from datetime import datetime
day_now = datetime.now()
print('Today is {} / {} / {}'.format(day_now.day,day_now.month,day_now.year))
def ask():
x = str(input('Enter your name \n Name : '))
if x.isdigit():
print('Only letters are accepted.')
else:
pass
try:
y = int(input('Enter your age \n Age : '))
except ValueError:
print('Age should be numbers.')
raise SystemExit
else:
pass
try:
z = int(input('What year are you thinking? \n Year :'))
if z < (day_now.year - y):
print('You are not born yet.')
raise SystemExit
else:
pass
except ValueError:
print('Numbers only.')
else:
pass
year_difference = z - day_now.year
age_future = year_difference + y
if age_future > 80:
print('You are probably not around anymore. If you are, you are {} years old.'.format(age_future))
else:
print('{} will be {} years old by the year {}.'.format(x,age_future,z))
ask()
|
## WE ARE MAKING AN ITERATOR / COUNTER
board = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
def display():
for row_no,row in enumerate(board):
print(row_no,' ',*row)
for i in range(len(board)**2):
no_of_players = 2
if i%2==0:
print('its X turn')
row = int(input('what row you want to play: '))
col = int(input('what col you want to play: '))
board[row][col] = 'X'
display()
else:
print('its O turn')
row = int(input('what row you want to play: '))
col = int(input('what col you want to play: '))
board[row][col] = 'O'
display()
|
# import modules
from tkinter import *
from englisttohindi.englisttohindi import EngtoHindi
# user define funtion
def eng_to_hindi():
trans = EngtoHindi(str(e.get()))
res = trans.convert
result.set(res)
# object of tkinter
# and background set for grey
master = Tk()
master.configure(bg = 'light grey')
# Variable Classes in tkinter
result = StringVar();
# Creating label for each information
# name using widget Label
Label(master, text="Enter Text : " , bg = "light grey").grid(row = 0, sticky = W)
Label(master, text="Result :", bg = "light grey").grid(row = 3, sticky = W)
# Creating lebel for class variable
# name using widget Entry
Label(master, text="", textvariable=result,bg = "light grey").grid(row = 3,
column = 1,
sticky = W)
e = Entry(master, width = 100)
e.grid(row = 0, column = 1)
# creating a button using the widget
# Button that will call the submit function
b = Button(master, text = "Show", command = eng_to_hindi, bg = "Blue")
b.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5,)
mainloop()
|
import sqlite3
class CoffeeShop:
def __init__(self):
pass
class Item:
def __init__(self, row):
self.ID = row[0]
self.ItemName = row[1]
self.ItemPrice = row[2]
self.QtyRemaining = row[3]
def __repr__(self):
return str(self.ID) + " " + self.ItemName
def loaditemsfromdatabase(self):
conn = sqlite3.connect('mydatabase')
c = conn.cursor()
c.execute('pragma foreign_keys=ON')
c.execute('SELECT ID, ItemName, ItemPrice, QtyRemaining FROM ItemList')
itemList = []
for row in c.fetchall():
itemList.append(CoffeeShop.Item(row))
return itemList |
memo = []
# Dynamic Programming Top-down.
class Solution1:
def canJump(self, nums):
for i in range(len(nums)):
memo.append("UNKNOWN")
memo[len(nums)-1] = True
return self.canJumpFromPosition(0, nums)
def canJumpFromPosition(self, position, nums):
if memo[position] != "UNKNOWN":
return memo[position]
furthestJump = min(position+nums[position], len(nums)-1)
for i in range(position+1, furthestJump+1):
if self.canJumpFromPosition(i, nums):
memo[i] = True
return True
memo[position] = False
return False
# Dynamic Programming Bottom-up
class Solution2:
memo2 = []
def canJump(self, nums):
for i in range(len(nums)):
self.memo2.append("UNKNOWN")
self.memo2[len(nums)-1] = True
for i in range(len(nums)-2, -1, -1):
furthestJump = min(i+nums[i], len(nums)-1)
for j in range(i+1, furthestJump+1):
if self.memo2[j] is True:
self.memo2[i] = True
break
return self.memo2[0] is True
# greedy
def canJump(nums):
lastPos = len(nums) - 1
for i in range(len(nums)-1, -1, -1):
if i + nums[i] >= lastPos:
lastPos = i
return lastPos == 0
t = Solution1()
tt = Solution2()
print(t.canJump([3, 2, 1, 0, 4]))
print(tt.canJump([3, 2, 1, 0, 4]))
print(canJump([3, 2, 1, 0, 4]))
|
##Emily Dennis 13/04/19
###program displays the correct Saffir-Simpson Hurricane Wind
###Scale category for a wind speed entered by the user and the selected unit.
#imports items from tkinter
from tkinter import Frame, OptionMenu, StringVar, Tk, Entry, Button, LEFT, Label
#creates hurricane class
class Hurricane(Frame):
#initialises the class
def __init__(self, master = None):
#intitalises the frame
Frame.__init__(self, master)
loadData = self.LoadData()
#loads in data
list2 = loadData[1]
#sets list2 variable as the 2nd item of loadData
self.populate =[list2[0],list2[1],list2[2]]
#populates the dropdown using the 2nd tuple by splitting it
self.variable = StringVar()
#creates a string variable
self.variable.set(self.populate[0])
#set the first item in the list to appear as default on dropdown
Label(self, text = "select units").pack(side = LEFT)
#sets label
self.HurricaneMenu = OptionMenu(self, self.variable,*self.populate)
#set option menu parameters
self.HurricaneMenu.pack(side = LEFT)
#packs the menu so it appears on the frame
self.e =StringVar()
#creates a string variable
hurricane_entry = Entry(self, width = 7, textvariable = self.e )
#sets the hurricane entry widget
hurricane_entry.pack(side = LEFT)
#packs the entry box so it appears on the frame
self.feedback =loadData[0]
#sets self.feedback as the first item in the tuple from loadData
self.possibleUnits =loadData[1]
#sets self.possibleUnits as the second item in the tuple from loadData
self.thresholds =loadData[2]
#sets self.thresholds as the third item in the tuple from loadData
calc = Button(self, text = "Calculate", command = self.GetFeedback).pack(side = LEFT)
#calculate button runs GetFeedback method
hurricane_entry.focus()
#the application focuses on the entry box on load
for c in self.master.winfo_children():
c.pack_configure(padx = 100, pady = 5)
#configures the packing on the window
self.var = StringVar()
#sets a string variable
self.var.set(" ")
#sets this as blank
self.L2 = Label(self, textvariable=self.var).pack()
#sets the label text as self.var
#loads data from Hurricane.dat
def LoadData(self):
feedback = []
possibleUnits =[]
thresholds=[]
SEPARATOR = '----------'
#set the values to be determined, and the seperator
inf = open("Hurricane.dat", "r")
#open Hurricane.dat
sData = inf.readlines()
#set sData to readlines of file
inf.close()
#close file
i=0
while sData[i].strip() != SEPARATOR:
#when the line being read is not equal to seperator
feedback.append(sData[i].strip())
#appends read data to feedback
i = i + 1
i = i + 1
while i<len(sData):
#while the length of sData is bigger than the iterator
possibleUnits.append(sData[i].strip())
#appends read data to possibleUnits
i = i + 1
thresholdlist = []
while sData[i].strip() != SEPARATOR:
thresholdlist.append(int(sData[i].strip()))
#appends read data to threshold list
i = i + 1
thresholds.append(thresholdlist)
#appends the thresholdlist to threshold
i = i + 1
# @return a tuple
return (feedback, possibleUnits, thresholds)
#is loaded when the calc button is clicked
def GetFeedback(self):
feedback = self.feedback
possibleUnits = self.possibleUnits
thresholds = self.thresholds
#sets the parameters to be used in get feedback using self statements.
units = (self.variable.get())
query = (self.e.get())
#additional parameters set using get statements
feedbackForInput= ["Both inputs are not valid",
"The query type is not correct",
"The query value is not a whole number",
"Inputs are all valid"]
#loop through feedback
validInput = str(query).isdigit() and (units in possibleUnits)
#set what a valid input is
inputValidation = feedbackForInput[int(str(query).isdigit()) + 2*int(units in possibleUnits)]
#determine the correct index
output = ""
if validInput:
#determines things if validInput is True
iquery= int(query)
#a variable for int form of query
iUnit = possibleUnits.index(units)
#a variable for that matches the index for thresholds based on the unit
i = 0
while (i<len(thresholds[iUnit])) and (iquery>thresholds[iUnit][i]):
#determines the threshold values
i = i + 1
output = feedback[i]
#ouput is retrieved
if (inputValidation == ("Inputs are all valid")):
self.var.set(output)
#label to display input if the validation condition is met
else:
self.var.set(inputValidation)
#present error message if input is not valid
if __name__ == "__main__":
Hurricane().mainloop()
#runs the code
|
def matrixMultiply(arr1, arr2):
global n
newArr=[[0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
sum=0
for k in range(n):
sum += arr1[i][k]*arr2[k][j]
newArr[i][j] = sum%1000
return newArr
def matrix(degree):
global arr
if degree==1:
return arr
elif degree%2==1:
return matrixMultiply(arr, matrix(degree-1))
else:
half = matrix(degree/2)
return matrixMultiply(half, half)
n, b = map(int,input().split())
arr=[]
for i in range(n):
arr.append(list(map(int, input().split())))
calcArr= matrix(b)
for i in range(n):
for j in range(n):
print(calcArr[i][j]%1000, end=" ")
print() |
import copy
def path(p, q, r): # p, 5, 3
if (p[q-1][r-1] != 0):
path(p, q, p[q-1][r-1])
print(f"v{p[q-1][r-1]}", end=" ")
path(p, p[q-1][r-1], r)
def allShortestPath(g, n):
# d는 최단거리의 길이가 포함된 배열(결과)
#
d = copy.deepcopy(g)
p=[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
for k in range(n):
for i in range(n):
for j in range(n):
if (d[i][j] > d[i][k]+d[k][j]):
d[i][j] = d[i][k]+d[k][j]
p[i][j] = k+1
return d, p
def printMatrix(d):
n = len(d[0])
for i in range(0, n):
for j in range(0, n):
print(d[i][j], end=" ")
print()
inf = 1000
g = [[0,1,inf,1,5],
[9,0,3,2,inf],
[inf,inf,0,4,inf],
[inf,inf,2,0,3],
[3,inf,inf,inf,0]]
printMatrix(g)
d, p = allShortestPath(g, 5)
print()
printMatrix(d)
print()
printMatrix(p)
path(p, 5, 3) # 5 to 3
print() |
#Artificial Neural Network
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
# Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
#Encoding column 1
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
#Encoding column 2
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
# Making dummy variables for column 1 (any encoded column with more than 2 variables needs this done.) This produces 3 new columns and sticks them in the front (assigns them as columns 0, 1, and 2.)
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
# Removing one dummy variable to prevent dummy variable trap (this is done for country here, however it needs to be done any time there is a category with more than 2 strings that was encoded to numbers.)
# Dummy variable trap is where you overspecify (DOF is too low!)
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Part 2 - Make the ANN!
# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Initialising the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer
# Rectifier function is arguably the best activation functions. Sigmoid functions are good for probabilistic not deterministic models (ie chance of meeting proft?) Therefor use rectifying for hidden layers and sigmoid for output layer!
# The output_dim argument in the Dense() is how many nodes you want for that particular hidden layer. The ideal number is described as being an "art" by Haedlin. There are some rules however. 1. If your data is linearly seperable, you don't need a hidden layer or NN. 2. His tip is to choose the number of nodes in the hidden layer as the average number of nodes in the input layer and number of nodes in the output layer. In this case it would be (11 + 1) / 2 = 6. If you want better, you need to practise/tune your parameters(experiment). This can include K-fold cross validation in part 10.
# init = initialisation method, to make all weights close to 0 uniformly.
# activation is for assigning the activation function. Since we've been told that rectifying is best for hidden layers, we're using that. It's called 'relu'
# input_dim is required, and says how many input independent variables there are. In this case its 11.
classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 11))
# Adding the second hidden layer
classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu'))
# Adding the output layer (you can add infinite more hidden layers. The more the "better", but also more computatively intense.)
# Output dimension is 1 since it is a binary predictor, ie a yes or no. If you have a dependent variable with more than two categories, ie three plus categories, you need to change output dimension to the number of classes. With the onehotencoder this means you have one output dimension for each potential output. ie 3 for 3, 11 for 11, etc. The other thing that must be changed is activation function. You would use softmax instead of sigmoid. Softmax is a sigmoid function applied to a dependent variable with more than two categories. Theres only one output of a 1 or 0. Sigmoid is also selected as the activation function for aforementioned reasons.
classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))
# Compiling the ANN
# Optimizer is algorithm to find optimal set of weights in the NN. We'll use the stochastic gradient descent, and a specific good algorith is known as 'adam'. Loss refers to loss in the adam function. This will be the logarithmic loss function, as it is also the loss function for sigmoid functions (our output layer!). If the output is binary it is known as binary_crossentropy. If it is nonbinary it is categorical_crossentropy.
# The third and final argument is metrics. It is the criterium to evaluate the model. Haedlin likes the accuracy criterium. Metrics wants it's input as a list, even though here we're only goingto use one element. Hence, we use the [] to create a list of 1 element, accuracy.
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting the ANN to the training set
# epochs arguments is how many times you want the weighting between layers to be adjusted. Higher is better but more computatively intensive.
# batch_size is number of observations before weights are adjusted.
# There is no rule of thumb for what to choose for these. Again, you must be an "artist" as Haedlin describes.
# We'll use 10 and 100 just for times sake.
classifier.fit(X_train, y_train, batch_size = 10, nb_epoch = 100)
# Part 3 - Making the predictions and evaluating the model
# Fitting classifier to the Training set
# Create your classifier here
# Predicting the Test set results
y_pred = classifier.predict(X_test)
# Convert percentage to true or false for y_pred
y_pred = (y_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
# We got a 86% accuracy without any tuning. This is insane. |
class Queue:
def __init__(self):
self.first = None # beginning of queue
self.last = None # end of queue
self.n = 0 # Number of elements in the queue
def enqueue(self, item):
oldLast = self.last
self.last = self.Node()
self.last.data = item
self.last.next = None
if self.isEmpty():
self.first = self.last
else:
oldLast.next = self.last
self.n += 1
def dequeue(self):
item = self.first.data
self.first = self.first.next
self.n -= 1
if self.isEmpty():
self.last = None
return item
def isEmpty(self):
return self.first is None
def size(self):
return self.n
## TEST
q = Queue()
q.enqueue("test")
q.enqueue("test2")
print q.dequeue()
print q.dequeue()
q.enqueue("test3")
print q.dequeue()
q.enqueue("test4")
print q.dequeue() |
#list range will start on zero and continue until hit 11
newList = list(range(0,11))
print(newList)
#the same but will be stepping by two elements
list(range(0,11,2))
for i,letter in enumerate('abcde'):
print("At index {} the letter is {}".format(i,letter))
mylist1 = [1,2,3,4,5]
mylist2 = ['a','b','c','d','e']
print(list(zip(mylist1,mylist2)))
# check if x is in that list (returns true) 'x' in ['x','y','z']
|
def ask():
while True:
try:
x = int(input("Enter a number: "))
except ValueError:
print("Wrong input")
continue
else:
break
print(x**2)
try:
for i in ['a','b','c']:
print(i**2)
except TypeError:
print("There was a type error!")
x = 5
y = 0
try:
z = x/y
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("All done")
ask() |
class Animal():
def __init__(self,name) -> None:
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method")
class Dog(Animal):
def speak(self):
return self.name + " says woof!"
class Cat(Animal):
def speak(self):
return self.name + " says meow!"
def pet_speak(pet_class):
print(pet_class.speak())
niko = Dog("niko")
felix = Cat("felix")
print(niko.speak())
print(felix.speak())
|
def exp(m, n):
return m ** n
def divides(m, n):
print("\ndivides: ", end= " ")
for i in range(1,m+1):
if i % n == 0:
print(i, end= " ")
def is_in_string(string, c):
return c in string
def how_many(string, c):
total = 0
for oneChar in string:
if c == oneChar:
total += 1
return total
print(f"exponent number is: {exp(3,4)}") # 8
divides(12, 3) # 3 6 9 12
divides(10, 7) # 7
word = 'Ostrava'
letter = 'a'
print("")
print(f"Is {letter} in {word}: {is_in_string(word, letter)}") # True
print(f"How many times is {letter} in {word}: {how_many(word, letter)}") # 2
|
from random import randint
def startGame():
rndNumber = randint(1,100)
numberOfTries = 0
lastNumber = 0
print(rndNumber)
while True:
guessedNumber = int(input("Enter a number "))
numberOfTries +=1
print(validateGuess(guessedNumber, numberOfTries, rndNumber, lastNumber))
if rndNumber == guessedNumber:
break
lastNumber = guessedNumber
print(f"You have it and took you {numberOfTries} guesses")
def validateGuess(guessedNumber,numberOfTries, rndNumber, lastNumber):
if guessedNumber < 0 or guessedNumber > 100:
print("OUT OF BOUNDS")
return
if numberOfTries == 1:
if rndNumber < guessedNumber+10 and rndNumber > guessedNumber -10:
return "WARM!"
else:
return "COLD!"
if abs(rndNumber - guessedNumber) < abs(rndNumber - lastNumber):
return("WARMER!")
else:
return("COLDER!")
startGame() |
def word_matching(text, keywords):
# keywords = convert_keywords(keywords)
# text = convert_text(text)
text = text.lower()
matching_count = 0
for i in range(len(keywords)):
start_matching_index = 0
matching_keyword = keywords[i].lower()
while(True):
start_matching_index = text.find(matching_keyword, start_matching_index)
if start_matching_index != -1: # find the keyword
start_matching_index += 1 # move on
matching_count += 1
else :
break
return matching_count
# def convert_keywords(keywords):
# # add spaces to both front and end of each keywords
# for i in range(len(keywords)):
# keywords[i] = " " + keywords[i].lower() + " "
# return keywords
def convert_text(text):
# convert symbols in the text into spaces
symbols = [',', '.', '\'', '\"', '?', '!'] # TODO: to complete the list
for i in range(len(symbols)):
text = text.replace(symbols[i], " ")
return text
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
__author__ = 'xutengfei'
__author_email__ = 'xutengfei1@genomics.cn
Fuc: Compute the character with the highest frequency in the string.
'''
import sys
def max_word(in_file,out_file):
with open(in_file,'r') as IN1, open(out_file,'w') as OUT:
data = IN1.readlines()
for i in data:
text = i.upper()
OUT.write(max(text, key=text.count)+"\t"+str(text.count(max(text, key=text.count))/(len(text)-1))+"\n")
if (len(sys.argv)==3):
max_word(sys.argv[1],sys.argv[2])
else:
print("Usage: python in_file out_file")
|
import re
a = 'c|C++|Java|C#|Python|Javascript'
r = re.findall('Python', a)
if len(r) > 0:
print('Python is there')
else:
print('no Python')
|
a=1
b=2
c=3
a,b,c=1,2,3 #上面的代码和下面的相同
d=1,2,3
print(type(d))
a,b,c =d #序列解包
# a,b=d #不能用两个变量来解包3个变量的tuple
# a,b=[1,3,4]
print(d)
|
# 字典不能有重复的key
#字典的key 是不可变的.
d={'Q':'are you ok?','G':'i am fully agree'}
print(d['G']) |
# 4Gewinnt Kristoferz
# Variables
col = 7
row = 6
empty_chip = '.'
human_chip = 'X'
pc_chip = 'O'
moves = 0
playerstart = input ("Who shall start? Please write Pc (1) or Human (2): ")
while str.lower(playerstart) != "pc" and str.lower(playerstart) != "human" and playerstart != str(1) and playerstart != str(2):
print("Invalid input, please try again.")
playerstart = input ("Who shall start? Please write Pc (1) or Human (2): ")
level = input ("Select difficulty. Random (1), Middle (2), Hard (3), Godlike (4): ")
while str.lower(level) != "random" and str.lower(level) != "middle" and str.lower(level) != "hard" and str.lower(level) != "godlike" and level != str(1) and level != str(2) and level != str(3) and level != str(4):
print("Invalid input, please try again.")
level = input ("Select difficulty. Random (1), Middle (2), Hard (3), Godlike (4): ")
# Diesen Teil kann man wahrscheinlich schöner schreiben :)
turn = 0
# 7 columns x 6 rows Field
field = [[i * j for j in range(col)] for i in range(row)]
for i in range(row):
for j in range(col):
field[i][j] = empty_chip
for n in field:
print(' '.join([str(elem) for elem in n]))
print("1 2 3 4 5 6 7")
def human_turn(human_move):
# Human move (geht nicht)
"""
human_move = input ("Select a number between 1 and 7: ")
if human_move<1 or human_move>7:
print("Invalid move")
human_turn(human_move)
for i in range(row):
if field[human_move][i] == empty_chip:
field[human_move][i] = human_chip
else:
print("Invalid move")
human_turn(human_move)
moves+=1
"""
return[human_move];
def pc_turn(pc_move):
# Pc move (in Bearbeitung)
"""
pc_move = random.randint(1,7)
moves+=1
"""
return[pc_move];
def startplayer(playerstart):
# Input to select starting player. Kann auch gross geschrieben werden oder mit 1 und 2
# Eventuell input durch Touch-Screen
if str.lower(playerstart) == "pc" or playerstart == str(1):
print ("Computer starts")
elif str.lower(playerstart) == "human" or playerstart == str(2):
print ("Human starts")
return [playerstart];
startplayer(playerstart)
def turn(playerstart,moves):
# Zeigt wer dran ist
if (str.lower(playerstart) == "human" or playerstart == str(2)) and moves%2 == 0:
turn = "human"
print ("It´s your turn. ")
human_turn(human_move)
elif (str.lower(playerstart) == "pc" or playerstart == str(1)) and moves%2 == 1:
turn = "human"
print ("It´s your turn. ")
human_turn(human_move)
else:
turn = "pc"
pc_turn(pc_move)
return [turn];
turn(playerstart,moves)
|
#Product of array elements
#Return the product of array elements under a given modulo.
#That is, return (Array[0]*Array[1]*Array[2]...*Array[n])%modulo
def product(arr,n,mod):
# your code here
pro=1
for j in range(0,n):
pro=pro*arr[j]
if pro>=mod:
pro=pro%mod
return pro
{
#Initial Template for Python 3
if __name__=="__main__":
t=int(input())
mod=1000000007
for j in range(t):
n=int(input())
arr=list(map(int,input().split()))
print(product(arr,n,mod))
}
|
import sys
from math import sqrt
def DistCalc(x1,x2,y1,y2):
dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
print int(dist)
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
coordinates=[]
for i in test.strip().split(" "):
coordinates.append(i)
x1=coordinates[0].replace("(", "")
x1=x1.replace(",", "")
x2=coordinates[2].replace("(", "")
x2=x2.replace(",", "")
y1=coordinates[1].replace(")", "")
y2=coordinates[3].replace(")", "")
DistCalc(int(x1),int(x2),int(y1),int(y2))
test_cases.close()
|
import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
coin1=1
coin3=3
coin5=5
minimum=0
test=int(test.strip())
if test>=coin5:
while(test>=coin5):
test-=coin5
minimum+=1
if test>=coin3:
while(test>=coin3):
test-=coin3
minimum+=1
if test>=coin1:
while(test>=coin1):
test-=coin1
minimum+=1
print minimum
test_cases.close()
|
import re
import collections
text = open('file_I.O/book.txt').read().lower()
words = re.findall('\w+', text)
print(collections.Counter(words).most_common(10)) |
#!/bin/python
import math
import os
import random
import re
import sys
# Complete the funnyString function below.
def funnyString(s):
rs=s[::-1]
n=len(s)
for i in range(1,n):
d1=abs(ord(s[i])-ord(s[i-1]))
d2=abs(ord(rs[i])-ord(rs[i-1]))
if d1!=d2:
return("Not Funny")
else:
return"Funny"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(raw_input())
for q_itr in xrange(q):
s = raw_input()
result = funnyString(s)
fptr.write(result + '\n')
fptr.close()
|
import json
import arcade
class Score:
def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT):
self.width = SCREEN_WIDTH
self.height = SCREEN_HEIGHT
self.path = "./score.json"
self.score_dict = {}
self.index = -1
self.char_count = 0
self.restart_timer = -1
def load_score(self, player_score):
with open(self.path) as file:
self.score_dict = json.load(file)
if (
player_score > int(list(self.score_dict.keys())[-1])
and str(player_score) not in self.score_dict
):
self.score_dict[str(player_score)] = "___"
dum = [int(x) for x in list(self.score_dict.keys())]
self.score_dict.pop(str(sorted(dum)[0]))
new_score = {}
key_list = [int(x) for x in list(self.score_dict.keys())]
for score in sorted(key_list, reverse=True):
new_score[str(score)] = self.score_dict[str(score)]
self.score_dict = new_score
self.index = list(self.score_dict.keys()).index(str(player_score))
else:
self.restart_timer = 0
def draw_score_screen(self):
arcade.draw_text(
"- HIGH SCORE -",
self.width // 2 - 155,
self.height - self.height // 10 - 10,
arcade.color.RUBY_RED,
40,
)
count = 1
for value, item in self.score_dict.items():
count += 1
if count - 2 == self.index:
arcade.draw_text(
f"* {value} - {item}",
self.width // 2 - 40 - 20 * len(value),
self.height - (self.height // 10) * count,
arcade.color.YELLOW,
30,
)
else:
arcade.draw_text(
f" {value} - {item}",
self.width // 2 - 20 - 20 * len(value),
self.height - (self.height // 10) * count,
arcade.color.RED_DEVIL,
30,
)
if self.restart_timer >= 0:
arcade.draw_text(
"Press a key to play again",
self.width // 2 - 185,
self.height // 9,
arcade.color.YELLOW_ORANGE,
30,
)
def score_input(self, char: str):
if self.restart_timer > 1.5:
return True
elif self.index >= 0 and self.char_count < 3 and char.isalpha():
score = list(self.score_dict.keys())[self.index]
name = list(self.score_dict.values())[self.index]
self.score_dict.pop(score)
replace_name = list(name)
replace_name[self.char_count] = char.upper()
replace_name = "".join(replace_name)
self.score_dict[score] = replace_name
new_score = {}
key_list = [int(x) for x in list(self.score_dict.keys())]
for score in sorted(key_list, reverse=True):
new_score[str(score)] = self.score_dict[str(score)]
self.score_dict = new_score
self.char_count += 1
if self.char_count == 3:
with open("score.json", "w") as file:
json.dump(self.score_dict, file)
self.restart_timer = 0
return False
return False
|
import os, tensorflow as tf
# use the range operation to generate vectors of sequential values
x = tf.range(start=0,limit=10,delta=1,dtype=tf.int32,name='range')
with tf.Session() as sess:
# init log files for tensorboard
sfw = tf.summary.FileWriter(os.getcwd(),sess.graph)
# dump the graph definition as JSON
print(sess.graph.as_graph_def())
# execute the range operation to generate vector
result = sess.run(x)
# clean up
sfw.close()
# show the result of the computation
print('result of executing range operation: {}'.format(result))
'''
Be sure to understand that tf.range is an operation that when
executed produces a 1-dim tf.Tensor object of shape=[10].
Have a look at the graph def output and tensorboard
Notice that all the input args about the range such as start,
limit, etc are stored as constant operators in the compute graph
definition. Therefore, when TF goes to evalueate the range operation
it must find all input nodes (i.e. constant operations whoes output
flows into the range operation) and execute those operations first
to generate the necessary input to execute the range operator.
From this perspective, it should be clear why tf.range can not
be used in the feeds_dict as input to sess.run.
''' |
import unittest
import leetcode_solutions as ls
class test_moviesOnFlight(unittest.TestCase):
print("Test moviesOnFlight")
def test_one(self):
movieDurations = [10,20, 50,30, 90,100] #[60,75,85,90,120,125,150]
d = 150
pair = ls.moviesOnFlight(movieDurations, d)
self.assertEqual(pair,[1,5])
def test_two(self):
movieDurations = [10,20, 50,30, 90,100] #[60,75,85,90,120,125,150]
d = 140
pair = ls.moviesOnFlight(movieDurations, d)
self.assertEqual(pair,[0,5])
class test_isValid(unittest.TestCase):
def test_zero(self):
s = ""
self.assertTrue(ls.isValid(s))
def test_one(self):
s = "()[]{}"
self.assertTrue(ls.isValid(s))
def test_two(self):
s = "(]"
self.assertFalse(ls.isValid(s))
def test_three(self):
s = "([)]"
self.assertFalse(ls.isValid(s))
def test_four(self):
s = "{[]}"
self.assertTrue(ls.isValid(s))
class TestMaxSubArray(unittest.TestCase):
def test_five(self):
lst = [-2,1,-3,4,-1,2,1,-5,4]
self.assertEquals(6, ls.maxSubArray(lst))
class test_groupAnagrams(unittest.TestCase):
def test_one(self):
lst = ["eat", "tea", "tan", "ate", "nat", "bat"]
self.assertEquals([['tan', 'nat'], ['bat'], ['eat', 'tea', 'ate']], ls.groupAnagrams(lst))
if __name__ == '__main__':
unittest.main() |
#!/usr/bin/env python3.6
# Decoradores @classmethod e @classmethod
# TIPOS DE MÉTODOS EM PYTHON:
# Métodos de instância: Recebem o objeto(self) como argumento
# Métodos de classe: Recebem a classe(cls) como argumento
# Métodos estaticos: Não recebem nada como argumento.
# Digamos que temos a seguinte classe:
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
rolf = Student('Rolf', 'MIT')
rolf.marks.append(78)
rolf.marks.append(99)
print(rolf.average()) # aqui temos a sintaxe 'objeto.method()' Isto é chamado método de instância
# não precisamos de um método __init__ nas classes obrigatoriamente
# @CLASSMETHOD
# Frequentemente usamos o @classmethod quando queremos algo que quer se
# relacionar a classe.
class Foo:
@classmethod
def hi(cls): # cls guarda o valor da classe 'Foo', posso chamar de qualquer
# coisa porem a convensão é 'cls', pois ele se refere a clase
# e não ao objeto(instância da classe)
print(cls.__name__)
my_object = Foo()
# O importante aqui é que o objeto 'my_object' não esta sendo passado como
# argumento por baixo dos panos, e sim a classe(Foo) do objeto.
my_object.hi() # aqui temos a sintaxe no background do python 'class.method()', hi() é chamado de método de classe
# @STATICMETHOD
# Utilizamos frequentemente o @staticmethod quando queremos um método que não
# usa o objeto atual ou a classe, mas algo que de alguma forma se
# relacionada a classe.
# O metodo estatico não precisa obrigatoriamente ter parametros:
class Bar:
@staticmethod
def hi():
print('Hello, I don\'t take parameters.')
another_object = Bar()
another_object.hi() # também tem a notação 'class.object' porém não recebe parametros.
# DIFERENÇAS NO USO
class Classe:
# funciona como um @staticmethod, porém não reconhece objetos como sendo instância da classe
# não é recomendado usar esse tipo de método
def printa_um(): # o certo é colocar o self como argumento
print('1')
# Método padrão no python, um método de instância.
def printa_quatro(self):
print('4')
@classmethod
def printa_dois(cls):
print('2')
@staticmethod
def printa_tres():
print('3')
# Parece que todos se comportam como métodos de classe 'classe.metodo()' menos o método de instacia 'printa_quatro(self)'
Classe.printa_um()
Classe.printa_dois()
Classe.printa_tres()
# Classe.printa_quatro() # Da erro pois precisa de um objeto(instância da classe) para ser usado.
print('\n')
# Testando como método de objeto
objeto = Classe()
# objeto.printa_um() # da erro, ele tenta passar o objeto como argumento e não consegue, pois o método printa_um() não recebe parametros.
objeto.printa_dois() # passa a Classe como argumento(por baixo dos panos), pois esse é um método de classe.
objeto.printa_tres() # não passa nada como parametro, porém se relaciona a classe.
objeto.printa_quatro()
# DIFERENÇA ENTRE OS MÉTODOS printa_um() e printa_tres():
# printa_um() não reconhece o objeto como sendo uma instância da classe. Já o printa_tres() reconhece o objeto como instancia da classe.
# Explicando:
class Printa:
def metodo_de_instancia(self):
print('Método de instância: objeto.metodo')
""" este é tipo padrão de métodos em python, só é possivel utilizá-los
quando instanciamos um objeto da classe
"""
@classmethod
def metodo_de_classe(cls):
print('Método de classe: classe.metodo')
""" este é chamado método de classe, podemos invocar o metodo como:
classe.metodo()
objeto.metodo()
As duas formas vão funcionar, porém é importante entender que por 'baixo dos panos'
o python passa a 'classe' como argumento para o método e não o objeto.
"""
@staticmethod
def metodo_estatico():
print('Método Estático: classe.metodo')
""" este é o chamado método estático, podemos invocar o método como:
classe.metodo()
objeto.metodo()
As duas formas vão funcionar, porém é importante entender que por 'baixo dos panos' o python não passa
argumentos, porém referencia a classe de alguma maneira.
"""
def metodo_estranho():
print('Método que não devemos utilizar nunca =D')
""" este método vai funcionar invocando na forma 'classe.metodo()', porém não funciona na forma 'objeto.metodo()', pois ele não reconhece
não recebe argumento algum. O metodo estático funciona pois mesmo escrevendo 'objeto.metodo()' o python faz 'classe.metodo()', o
que não acontece com esse metodo_estranho().
*** Um especialista me respondeu que não utiliza-se isso pois o @staticmethod é uma forma de padronização essa forma de sintaxe.
"""
objeto = Printa()
objeto.metodo_de_instancia()
# Printa.metodo_de_instancia() # Não funciona pois este é um método de instância
Printa.metodo_de_classe()
Printa.metodo_estatico()
# Resumo:
# Métodos de instância são invocados apenas por um objeto.
# Métodos estáticos e de classe sempre referenciam a classe de alguma forma,
# @classmethod passa cls como argumento e esta totalmente relacionada a classe. E @staticmethod não recebe parametros e é de uso mais geral.
|
#!/usr/bin/env python3.6
# Para criar nossos proprios erros, precisamos herdar de alguma classe de Erro, por exemplo TypeError
# pode ser qualquer uma...
class MyError(TypeError):
"""
Documentação da Classe
"""
# message é um atributo da superclase e code é um atributo que criamos para a classe MyError()
def __init__(self, message, code):
super().__init__(f'Error code {code}: {message}') # Mensagem de erro da superclasse(TypeError), sempre precisamos colocar
self.code = code
""" Aqui estamos criando um objeto do tipo MyError(), e passando os parametros que definimos na nossa
classe acima. A palavra reservada 'raise' faz com que o objeto seja levantado.
"""
# raise MyError('Motivo do erro e explicacao.', 500)
print(MyError.__doc__) # __doc__ é o metodo magico que mostra a documentacao da classe.
# Criando um objeto do tipo MyError
err = MyError('Motivo do erro e explicacao.', 500)
# Útil para desenvolvimento.
print(err.__doc__)
# CRIANDO MEU PROPRIO ERRO:
class MeuErro(Exception):
"""
Herdar de Exception é melhor pois esta é a classe
base para todas as exceções do python.
"""
def __init__(self, message, meu_atributo): # messsage é um atributo herdado da superclasse 'Exception', porém não é um parametro obrigatorio
# Posso escrever super().__init__(message): ou posso escrever tambem coisas mais complexas como abaixo:
super().__init__(f'{message}:{meu_atributo}') # Obs: sempre precisamos colocar o super().__init__()
self.meu_atributo = meu_atributo
# Então posso 'raise' levantar meu erro:
raise MeuErro('Meu Erro', 'Explicação')
|
def count_from_zero_to_n(n):
if n <= 0:
raise ValueError('Valor invalido. A entrada deve ser um numero inteiro.')
for x in range(0, n+1):
print(x)
count_from_zero_to_n(-1)
|
#!/usr/bin/env python3.6
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def __repr__(self):
return f'<Car{self.make} {self.model}'
class Garage:
def __init__(self):
self.cars = list()
def __len__(self):
return len(self.cars)
def add_car(self, car):
""" A exceção abaixo vai acontecer se tentarmos adicionar um carro
dentro da garagem
"""
raise NotImplementedError('Não podemos adicionar carros a garagem ainda.')
def add_car2(self, car):
""" Digamos que queremos adicionar na lista apenas objetos do tipo Car.
Podemos fazer isso graças a uma built-in function no python chamada 'isinstance'.
sintaxe: isinstance(objeto, Classe), verifica se o objeto é do tipo da Classe.
"""
if not isinstance(car, Car):
raise TypeError(f'Você tentou adicionar um `{car.__class__.__name__}` a garagem, mas você só pode adicionar objetos do tipo Car')
self.cars.append(car) # não é necessario usar o else aqui pois não roda se der o TypeError.
ford = Garage()
# ford.add_car('Fiesta') # Acontece NotImplementedError
# ford.add_car2('Fiesta') # Acontece TypeError
car = Car('Ford', 'Fiesta')
ford.add_car2(car)
print(len(ford))
|
#!/usr/bin/env python3
# Create Stored movies with object-oriented programming:
class Movie:
"""
Classe Filmes
Tem os atributos:
titulo, diretor e ano de lançamento.
"""
def __init__(self, new_title, new_director, new_year=1994):
self.title = new_title
self.director = new_director
self.year = new_year
class Agencia:
"""
Classe gerencia os objetos do tipo Movie.
"""
def __init__(self, title, director, year):
self.filme = Movie(title, director, year) # cria um objeto do tipo movie
self.lista_filmes = list()
def armazenar(self):
self.lista_filmes.append(self.filme)
title = str(input('Type the name of the title: '))
director = str(input('Type the name of the director: '))
year = int(input('Type the year: '))
agencia = Agencia(title, director, year)
print(agencia.filme.title)
agencia.armazenar()
print('lista', agencia.lista_filmes) # Printa a lista de objetos
print(f'Filme: {agencia.lista_filmes[0].title}') # lilsta_filmes[0] é um objeto do tipo Movie
|
is_programmer = False
# It's a infinite loop
while not(is_programmer): # It means that: is_programmer == True
print('Leraning Programming')
learning_programming = input('Are you alredy a programmer? ').lower()
is_programmer = learning_programming == 'yes' # is_programmer receives the boolean value of following comparision
# We can use while loop to repeat something a specific number os times:
i = 0 # control variable
while i < 10:
print('{}° repetition'.format(i+1))
i += 1 # Here we have to increment the control variable
# We can also use while loops to control some variable like temperature:
temperature = 15
while temperature < 20:
print('Heating...')
temperature += 1
|
import typing
def repeated_function(aString: str, n: int) -> str:
if n == 1:
return aString
else:
return aString + repeated_function(aString, n-1)
print(repeated_function("Nome", 3))
|
option = 'p'
while option not in 'quit':
option = input('Type an option[p/q]? ').lower()[0]
if option == 'p':
print('Hello')
|
# Return a double of a list
lista = list(range(10))
#=============================
lista_dobro = list()
print(lista_dobro) # It must show a void list
for num in lista:
lista_dobro.append(num*2)
print(lista_dobro)
#=============================
# LIST COMPREHENSION WITH LIST
print([num*2 for num in lista])
# We can format strings into a list comprehension:
frases = ['{} anos de idade'.format(num) for num in lista_dobro]
print(frases)
# We can do the same thing with f strings:
frases2 = [f'{num} anos de idade' for num in lista_dobro]
print(frases2)
# Names list
names_list = ['Lucas', 'João', 'Bruno', 'Otávio']
nomes_minusculas = [name.lower() for name in names_list]
print(nomes_minusculas)
nome1 = 'Lucas_Alberto'
nome2 = 'lucas_alberto'
print(nome1.lower())
print(nome2.capitalize())
print(nome2.upper())
print('_'.join([nome.capitalize() for nome in nome2.split('_')])) # Para fazer o capitalize em nomes separados por
# algum simbolo.
# Creating a list of even numbers(numeros pares)
print([number for number in range(20) if number % 2 == 0])
# Com as listas 'frinds' e 'guests' construir uma lista com os amigos que vao a festa(que estao entre os convidados)
friends = ['rolf', 'anna', 'charlie']
guests = ['Jose', 'Rolf', 'Charlie', 'michael']
# Meu jeito
guests_friends = [friend for friend in friends if friend.capitalize() in guests]
print(guests_friends)
# Jeito do Professor
present_friends = [friend for friend in guests if friend.lower() in friends]
print(present_friends)
# LIST COMPREHENSION WITH SETS
friends = {'rolf', 'anna', 'charlie'}
guests = {'jose', 'rolf', 'charlie', 'michael'}
present_friends = {name.capitalize() for name in friends if name in guests}
print(present_friends)
# existe uma maneira melhor de fazer isso:
# utilizando interseção:
friends_intersection = friends & guests
# tambem podemos fazer:
friends_intersection2 = {name.capitalize() for name in friends & guests}
print(friends_intersection) # pode vir fora de ordem
print(friends_intersection2) # pode vir fora de ordem
# LIST COMPREHENSION WITH DICTIONARIES
names = ['Rolf', 'Anna', 'Charlie']
time_last_seen = [10, 15, 8]
# Constuir com as listas acima, o seguinte dicionario: {'Rolf':10, 'Anna':15, 'Charlie':8}
# Com list comprehension
print({names[i]:time_last_seen[i] for i in range(len(names))})
# Com zip()
print(dict(zip(names, time_last_seen)))
|
print ("Moi, mikä sun nimi on?")
nimi = input()
print ("Moi," + nimi)
if nimi == "k":
print("Outo nimi mut, ok.")
else:
print("Hauska nimi!") |
import os
import csv
dirname = os.path.dirname(__file__)
csvpath = os.path.join(dirname,'Resources', 'budget_data.csv')
print (csvpath)
# def sum_of_budget_data(date):
# total = 0
# for val in date:
# total = total + val
# return total
# budget_data = [Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec]
# print "The total is", sum_of_budget_data(budget_data)
total_net = 0
total_months = 0
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
print(csvreader)
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
for row in csvreader:
# Track total
total_months += 1
total_net = total_net + int(row[1])
# Track net change
list_a= [total_net,total_months]
list_b= [net_change,]
for row in csvreader:
...
list_a.append(total_net)
list_b.append(row[0])
net_change = int(row[1]) - previous_net
avg = sum(net_changes)/len(net_changes)
# Calculate the greatest increase
# Calculate the greatest decrease
# Calculate the average net change
print(total_months)
print(total_net)
print(net_change)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.