text
stringlengths 37
1.41M
|
---|
#!/usr/bin/python3
"""changing the int class"""
class MyInt(int):
"""New version of int"""
def __eq__(self, other):
"""check if equal to other"""
return int.__ne__(self, other)
def __ne__(self, other):
"""check if not equal to other"""
return int.__eq__(self, other)
|
#!/usr/bin/python3
"""Read File"""
def read_file(filename=""):
"""This function reads and prints out text from file"""
with open(filename) as f:
for line in f:
print(line, end="")
|
'''
@Author: Firefly
@Date: 2019-09-06 15:08:03
@Descripttion:
@LastEditTime : 2019-12-19 16:15:59
'''
# -*- encoding: utf-8 -*-
"""
@file: thread01.py
@time: 2019/9/6 15:08
@author: Firefly
@version: 0.1
"""
import _thread
import time
def print_time(name, delay, lock):
print(name)
count = 0
while count < 5:
print("name :" + name + " delay :" + str(delay))
time.sleep(delay)
count += 1
lock.release()
def main():
pass
try:
#! _thread 模块没有进程的控制, 主进程结束, 子进程就结束了, 要等待子线程结束, ,,,,,
#! 可以使用跟强大的threading 模块
print("thread1")
_thread.start_new_thread(print_time, ("first", 2, _thread.allocate_lock()))
print("thread2")
_thread.start_new_thread(print_time, ("second", 3, _thread.allocate_lock()))
except Exception as e:
print(e)
print("start error")
# print("start ---------------")
# main()
# print("end------------------")
if __name__ == "__main__":
main()
|
message="a custom-crafted wetsuit helped Pierre,the African penguin,recover from a bout of baldness"
if message.find('the')==-1:
print('not present')
else:
print('present')
l=message.count('the')
print(l)
o=message.capitalize()
print(o)
p=message.split(',')
print(p)
if message.isupper():
print(message.lower())
else:
print(message.upper())
|
"""
Write a documentation for the simple function below. Your partner will have to
implement the function, without knowing the code. Send your partner the
documentation and see if he can work with it.
No cheating! Don't show or tell hem the code directly
"""
def function_2b(string_1, string_2):
"""
Argument:
string1 -- text you want to turn into lower case
string2 -- text you want to turn into upper case
Returns:
dict -- dictionary with:
1. lower case version of string1
2. upper case version of string2
3. combination of string1 and string2
"""
lower = string_1.lower()
upper = string_2.upper()
combined = string_1 + string_2
dict = {"L": lower,
"U": upper,
"C": combined}
return dict
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 15 12:42:39 2017
@author: KarimM
"""
"""
This code includes different pieces of building a neural network:
- init_net: initializes a network with the given number of layers and nodes
- forward_prop: passes an input through the network and returns the outputs of the network
- back_prop: performs back propoagation on the passed network for a given input and expected output and updates the weights of the network accordingly
- train: train a given network for on a given dataset through back propagation
- saveNet & loadNet: saves and loads a given network to the hard disk
- testingNetwork: evaluates the performance of the network on a given testset and return the accuracy
An example of a typical network training would be:
network = init_net(5,3,2) # Initialize a network with one hidden layer of size 3. Input of length 5 and output of length 2
train(network,TrainData,1000,4,0.3,TestData,5) # Train the network using TrainData (your dataset formated as:
# rows are observations, columns are features and last column is label)
# output size is 4 and learning rate is 0.3. The TestData is used to test the performance of your network
# after each iteration. Finally, print the loss after every 5 iterations.
saveNet(network,"network.txt") # Save your network for later usage.
"""
import numpy as np
from numpy import genfromtxt
import pickle
import copy
import matplotlib.pyplot as plt
import math
import sys
"""
Activation Funcations
"""
# Sigmoid Activation Function
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
# ReLu derivative
def sigmoid_diff(z):
return z * (1.0 - z)
# Softmax Activation function [Stable version, does not produce NAN]
def softmax(x):
"""Compute the softmax of vector x in a numerically stable way."""
shiftx = x - np.max(x)
exps = np.exp(shiftx)
return exps / np.sum(exps)
# ReLu Activation Function
def relu(z):
return np.maximum(z, 0.0)
# ReLu derivative
def relu_diff(x):
z = copy.deepcopy(x)
z[z<=0] = 0.0
z [z > 0] = 1.0
return z
"""
Initializing the network
"""
def init_net(*args):
network = list()
for layer_number in range(1,len(args)):
network.append(math.sqrt(2.0 / args[layer_number-1]) * np.random.rand(args[layer_number],args[layer_number-1])) # adding 1 for the bias term
return network
"""
forward propagation
"""
def forward_prop(net,inputs):
Nodes_state = []
for counter in range(0,len(net)-1):
if (counter == 0):
H_hidden = relu(np.dot(net[counter],inputs))
else:
H_hidden = relu(np.dot(net[counter],H_hidden))
Nodes_state.append(H_hidden)
Outputs = softmax(np.dot(net[-1],H_hidden))
Nodes_state.append(Outputs)
return Nodes_state
"""
back propagation
"""
def back_prop(network,expected,inputs,dE_dW,l_rate = 0.3):
Nodes_state = forward_prop(network,inputs)
dE_dZ = Nodes_state[-1] - expected
for counter in range(len(network)-1,0,-1):
hidden_output = Nodes_state[counter-1]
dE_dW[counter] += np.dot(np.reshape(dE_dZ,[len(dE_dZ),1]),np.reshape(hidden_output,[1,len(hidden_output)]))
dE_dZ = np.dot(dE_dZ,network[counter]) * relu_diff(hidden_output)
dE_dW[0] += np.dot(np.reshape(dE_dZ,[len(dE_dZ),1]),np.reshape(inputs,[1,len(inputs)]))
def updateWeights(network, dE_dW, l_rate = 0.3):
for counter in range(len(network)):
network[counter] -= l_rate * dE_dW[counter]
"""
Training the network
"""
def train(network,dataset,iterations,n_outputs,l_rate, testDataset, batchSize = 100, printAfter = 100):
# Initialize a list to store gradiends for batch updates, simply the network is copied so gradients would have the same structure as network
dE_dW = copy.deepcopy(network)
dE_dW = [aa*0 for i,aa in enumerate(dE_dW)]
# Main loop for training (no batch gradient decent is implemented, weights are updated after each point)
for i in range(iterations):
Train_sum_error = 0.0
Test_sum_error = 0.0
for counter in range(len(dataset)):
row = dataset[counter]
expected = [0 for k in range(n_outputs)]
expected[row[-1]] = 1
#Train_sum_error += sum((expected - forward_prop(network,row[:-1])[-1])**2)
Train_sum_error += sum(-1 * (expected * np.log(forward_prop(network,row[:-1])[-1] + sys.float_info.epsilon)))
back_prop(network,expected,row[:-1],dE_dW,l_rate)
if (counter % batchSize == 0):
dE_dW = [aa/batchSize for j,aa in enumerate(dE_dW)]
updateWeights(network,dE_dW,l_rate)
dE_dW = [aa*0 for j,aa in enumerate(dE_dW)]
# Cost for Test set
for row in testDataset:
expected = [0 for k in range(n_outputs)]
expected[row[-1]] = 1
#Test_sum_error += sum((expected - forward_prop(network,row[:-1])[-1])**2)
Test_sum_error += sum(-1 * (expected * np.log(forward_prop(network,row[:-1])[-1]+ sys.float_info.epsilon)))
# Testing classification accuracy on train and test datasets
TrainAccuracy = testingNetwork(dataset,network)
TestAccuracy = testingNetwork(testDataset,network)
# printing errors every "printAfter" (100 default) iterations
if (i % printAfter == 0):
print 'Epoch', i, 'Train error:',"%0.20f" %Train_sum_error, 'Test error:', Test_sum_error
print 'Train Accuracy', "%0.20f" % TrainAccuracy,'Test Accuracy', TestAccuracy, '\n'
# Saving errors in files
with open("TrainError.txt", 'a') as file_handler:
file_handler.write("{0}\n".format(Train_sum_error))
with open("TestError.txt", 'a') as file_handler:
file_handler.write("{0}\n".format(Test_sum_error))
with open("TrainAccuracy.txt", 'a') as file_handler:
file_handler.write("{0}\n".format(TrainAccuracy))
with open("TestAccuracy.txt", 'a') as file_handler:
file_handler.write("{0}\n".format(TestAccuracy))
"""
Saving and Loading the net
"""
def saveNet(net,fileName):
with open(fileName, "wb") as fp: #Pickling
pickle.dump(net, fp)
def loadNet(fileName):
with open(fileName, "rb") as fp: # Unpickling
net = pickle.load(fp)
return net
"""
Evaluation Section
"""
def predict(network, row):
outputs = forward_prop(network, row)[-1]
return np.argmax(outputs)
# Calculate accuracy percentage
def accuracy_metric(actual, predicted):
correct = 0
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / float(len(actual)) * 100.0
def testingNetwork(dataSet,network):
predictions = []
for i in range(len(dataSet)):
predictions.append(predict(network,dataSet[i][:-1]))
actual = [row[-1] for row in dataSet]
return accuracy_metric(actual,predictions)
"""
Plotting the errors and accuracies
Directory must include (TrainAccuracy.txt, TestAccuracy.txt, TrainError.txt, TestError.txt)
"""
def plotResults(Traindirectory = '/Users/KarimM/Desktop/CloudOutputs/100_40/', TestDirectory = '/Users/KarimM/Desktop/CloudOutputs/100_40/'):
TrainAccuracies = list()
TestAccuracies = list()
with open(Traindirectory + "TrainAccuracy.txt") as f:
for line in f:
TrainAccuracies.append(float(line))
with open(TestDirectory + "TestAccuracy.txt") as f:
for line in f:
TestAccuracies.append(float(line))
#plt.figure(figsize=(70, 70))
plt.plot(TrainAccuracies[-3000:],'b', label = "Training")
plt.plot(TestAccuracies[-3000:],'r', label = "Testing")
plt.xlabel('Iteration')
plt.ylabel('Classification Accuracy')
plt.title('Classification Accuracy through iterations')
#plt.yticks(np.arange(40, 101.0, 5.0))
plt.grid(True)
plt.legend()
#plt.show()
plt.savefig(Traindirectory + 'Accuracies.png',dpi = 1080)
TrainError = list()
TestError = list()
with open(Traindirectory + "TrainError.txt") as f:
for line in f:
TrainError.append(float(line))
with open(TestDirectory + "TestError.txt") as f:
for line in f:
TestError.append(float(line))
plt.figure()
plt.plot(TrainError[-3000:],'b', label = "Training")
plt.plot(TestError[-3000:],'r', label = "Testing")
plt.xlabel('Iteration')
plt.ylabel('Cost')
plt.title('Sum of Cost across iterations')
#plt.yticks(np.arange(40, 101.0, 5.0))
plt.grid(True)
plt.legend()
#plt.show()
plt.savefig(Traindirectory + 'Errors.png',dpi = 1080)
"""
########################################################
The following part in purely for the CS5242 assignment tasks and is not
a reusable code for training neural networks. In case you are using this
code outside the context of CS5242, deleting the following part will not
affect the usability of the code.
[NOTE:] Biases were removed from previous code, so rerunning the following code
will produce an error. To rerurn it, biases have to be added again.
########################################################
"""
def readTrainData(dir = "/Users/KarimM/Google Drive/PhD/Courses/Deep Learning/assignment1/Question2_123/"):
x_training = genfromtxt(dir + "x_train.csv",delimiter = ",")
y_training = genfromtxt(dir + "y_train.csv",delimiter = ",")
x_training = x_training.astype(int)
y_training = y_training.astype(int)
y_training = y_training.reshape([len(y_training),1])
return np.append(x_training, y_training, axis=1)
def readTestData(dir = "/Users/KarimM/Google Drive/PhD/Courses/Deep Learning/assignment1/Question2_123/"):
x_test = genfromtxt(dir + "x_test.csv",delimiter = ",")
y_test = genfromtxt(dir + "y_test.csv",delimiter = ",")
x_test = x_test.astype(int)
y_test = y_test.astype(int)
y_test = y_test.reshape([len(y_test),1])
return np.append(x_test, y_test, axis=1)
def GenerateGradientsFor14_100_40_4(weightsDir = "/Users/KarimM/Google Drive/PhD/Courses/Deep Learning/assignment1/Question2_4/b/"):
# Loading the weights and initializing outputs
layers = genfromtxt(weightsDir + "w-100-40-4nonames.csv",delimiter = ",")
biases = genfromtxt(weightsDir + "b-100-40-4nonames.csv",delimiter = ",")
network = init_net(14,100,40,4)
dW = init_net(14,100,40,4)
dB = list()
# Reading weights
network[0] = layers[0:14].T
network[1] = layers[14:114,0:40].T
network[2] = layers[114:154,0:4].T
# Reading biases
network[0] = np.hstack((network[0],np.reshape(biases[0],[len(biases[0]),1])))
network[1] = np.hstack((network[1],np.reshape(biases[1][0:40],[len(biases[1][0:40]),1])))
network[2] = np.hstack((network[2],np.reshape(biases[2][0:4],[len(biases[2][0:4]),1])))
#providing the data point and ground truth
row =[-1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 3]
expected = [0 for k in range(4)]
expected[row[-1]] = 1
# Back propagating the error
inputs = row[:-1]
Nodes_state = forward_prop(network,inputs)
inputs = np.append(inputs,1)
dE_dO = Nodes_state[-1] - expected
dE_dZ = dE_dO
for counter in range(len(network)-1,0,-1):
hidden_output = Nodes_state[counter-1]
dW[counter] = np.dot(np.reshape(dE_dZ,[len(dE_dZ),1]),np.reshape(hidden_output,[1,len(hidden_output)]))
dE_dZ = np.dot(dE_dZ,network[counter][:,:-1]) * relu_diff(hidden_output[:-1])
dW[0] = np.dot(np.reshape(dE_dZ,[len(dE_dZ),1]),np.reshape(inputs,[1,len(inputs)]))
# Reformating the output to match the grading script
for counter in range(len(dW)):
dB.append(dW[counter].T[-1])
dW[counter] = dW[counter].T[:-1]
# Saving the outputs
import csv
with open("dw-100-40-4.csv",'wb') as file_handler:
writer = csv.writer(file_handler, delimiter=',')
for layer in dW:
for row in layer:
writer.writerow(row)
with open("db-100-40-4.csv",'wb') as file_handler:
writer = csv.writer(file_handler, delimiter=',')
for row in dB:
writer.writerow(row)
def GenerateGradientsFor14_28_6_4(weightsDir = "/Users/KarimM/Google Drive/PhD/Courses/Deep Learning/assignment1/Question2_4/b/"):
# Loading the weights and initializing outputs
layers = genfromtxt(weightsDir + "w-28-6-4nonames.csv",delimiter = ",")
biases = genfromtxt(weightsDir + "b-28-6-4nonames.csv",delimiter = ",")
network = init_net(14,28,28,28,28,28,28,4)
dW = init_net(14,28,28,28,28,28,28,4)
dB = list()
# Reading weights
network[0] = layers[0:14].T
for counter in range(1,6):
network[counter] = layers[14+(28 * (counter -1)):14 + (28 * counter),].T
network[6] = layers[154:,0:4].T
# Reading biases
for counter in range(6):
network[counter] = np.hstack((network[counter],np.reshape(biases[counter],[len(biases[counter]),1])))
network[6] = np.hstack((network[6],np.reshape(biases[6][0:4],[len(biases[6][0:4]),1])))
#providing the data point and ground truth
row =[-1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 3]
expected = [0 for k in range(4)]
expected[row[-1]] = 1
# Back propagating the error
inputs = row[:-1]
Nodes_state = forward_prop(network,inputs)
inputs = np.append(inputs,1)
dE_dO = Nodes_state[-1] - expected
dE_dZ = dE_dO
for counter in range(len(network)-1,0,-1):
hidden_output = Nodes_state[counter-1]
dW[counter] = np.dot(np.reshape(dE_dZ,[len(dE_dZ),1]),np.reshape(hidden_output,[1,len(hidden_output)]))
dE_dZ = np.dot(dE_dZ,network[counter][:,:-1]) * relu_diff(hidden_output[:-1])
dW[0] = np.dot(np.reshape(dE_dZ,[len(dE_dZ),1]),np.reshape(inputs,[1,len(inputs)]))
# Reformating the output to match the grading script
for counter in range(len(dW)):
dB.append(dW[counter].T[-1])
dW[counter] = dW[counter].T[:-1]
# Saving outputs
import csv
with open("dw-28-6-4.csv",'wb') as file_handler:
writer = csv.writer(file_handler, delimiter=',')
for layer in dW:
for row in layer:
writer.writerow(row)
with open("db-28-6-4.csv",'wb') as file_handler:
writer = csv.writer(file_handler, delimiter=',')
for row in dB:
writer.writerow(row)
def GenerateGradientsFor14_28_4(weightsDir = "/Users/KarimM/Google Drive/PhD/Courses/Deep Learning/assignment1/Question2_4/b/"):
# Loading the weights and initializing outputs
layers = genfromtxt(weightsDir + "w-14-28-4nonames.csv",delimiter = ",")
biases = genfromtxt(weightsDir + "b-14-28-4nonames.csv",delimiter = ",")
network = init_net(14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,4)
dW = init_net(14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,4)
dB = list()
for counter in range(28):
network[counter] = layers[(14 * (counter)): (14 * (counter+1)),].T
network[28] = layers[392:,0:4].T
for counter in range(28):
network[counter] = np.hstack((network[counter],np.reshape(biases[counter],[len(biases[counter]),1])))
network[28] = np.hstack((network[28],np.reshape(biases[28][0:4],[len(biases[28][0:4]),1])))
row =[-1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 3]
expected = [0 for k in range(4)]
expected[row[-1]] = 1
inputs = row[:-1]
Nodes_state = forward_prop(network,inputs)
inputs = np.append(inputs,1)
dE_dO = Nodes_state[-1] - expected
dE_dZ = dE_dO
for counter in range(len(network)-1,0,-1):
hidden_output = Nodes_state[counter-1]
dW[counter] = np.dot(np.reshape(dE_dZ,[len(dE_dZ),1]),np.reshape(hidden_output,[1,len(hidden_output)]))
dE_dZ = np.dot(dE_dZ,network[counter][:,:-1]) * relu_diff(hidden_output[:-1])
dW[0] = np.dot(np.reshape(dE_dZ,[len(dE_dZ),1]),np.reshape(inputs,[1,len(inputs)]))
for counter in range(len(dW)):
dB.append(dW[counter].T[-1])
dW[counter] = dW[counter].T[:-1]
import csv
with open("dw-14-28-4.csv",'wb') as file_handler:
writer = csv.writer(file_handler, delimiter=',')
for layer in dW:
for row in layer:
writer.writerow(row)
with open("db-14-28-4.csv",'wb') as file_handler:
writer = csv.writer(file_handler, delimiter=',')
for row in dB:
writer.writerow(row) |
# <Ping-Pong>
# by Team 2 …
# Copyright: You can play but you must have permission to use code.
import random
import pygame
import time
import math
from timeit import default_timer as timer
import sys
global mode
time.sleep(0.5)
screen_coord = (800, 600)
screen = pygame.display.set_mode(screen_coord)
pygame.init()
font = pygame.font.SysFont("comicsansms", 21)
paddleheight = 100 # 100
paddlewidth = 20 # 20
updateSpeed = 50 # 50 times per sec
lscore, rscore, totalhits = 0, 0, 0
black = (20, 20, 20)
red = (240, 40, 40)
green = (0, 220, 0)
blue = (30, 144, 255)
white = (250, 250, 250)
pink = (255, 180, 180)
yellow = (238, 238, 0)
orange = (255, 150, 0)
purple = (138, 43, 226)
brown = (139, 76, 57)
colors = [red, green, blue, white, pink, yellow, orange, purple, brown]
paddlecolor = random.choice(colors)
def instructions():
global mode
print()
print('NOTE:')
print('If you see a pygame message but no window, you may have to find the window on your computer.')
dist = 25
fonts = pygame.font.SysFont("comicsansms", 19)
ins = ['Welcome to Team 2\'s Python Ping-Pong Game! ',
'This code was created using object-oriented programming and pygame. ',
'Use W and S keys to move left paddle, Up/Down arrows for right paddle. ',
'You can see scores and total hits of the current round at the top. ',
'Use space to reset',
'{c: computer vs computer, p: person vs person',
'person (right) vs computer (left): e=easy, m=medium, h=hard, v=very hard}',
'Press the corresponding key from above to play!']
for i in range(0, len(ins)):
text = fonts.render(ins[i], True, (250, 250, 250))
screen.blit(text, (50, 100 + dist * i))
pygame.display.update()
while True:
pygame.init()
# print('hi')
pygame.event.pump()
keys = pygame.key.get_pressed()
if keys[pygame.K_c]:
mode = 'c'
break
if keys[pygame.K_h]:
mode = 'h'
break
if keys[pygame.K_p]:
mode = 'p'
break
if keys[pygame.K_e]:
mode = 'e'
break
if keys[pygame.K_m]:
mode = 'm'
break
if keys[pygame.K_v]:
mode = 'v'
break
if keys[pygame.K_ESCAPE]:
pygame.quit()
def printscore(totalhits, lscore, rscore, x, y, scoredist):
text = font.render('Score:', True, (250, 250, 250))
screen.blit(text, (x - text.get_width() // 2, y - text.get_height() // 2 - scoredist))
screen.blit(text, (screen_coord[0] - x - text.get_width() // 2, y - text.get_height() // 2 - scoredist))
text = font.render(str(lscore), True, (250, 250, 250))
screen.blit(text, (x - text.get_width() // 2, y - text.get_height() // 2))
text = font.render(str(rscore), True, (250, 250, 250))
screen.blit(text, (screen_coord[0] - x - text.get_width() // 2, y - text.get_height() // 2))
text = font.render('Total hits:', True, (250, 250, 250))
screen.blit(text, (screen_coord[0] // 2 - text.get_width() // 2, y - text.get_height() // 2 - scoredist))
text = font.render(str(totalhits), True, (250, 250, 250))
screen.blit(text, (screen_coord[0] // 2 - text.get_width() // 2, y - text.get_height() // 2))
def three21():
for i in [3,2,1]:
screen.fill(black)
bigfont = pygame.font.SysFont("comicsansms", 100)
text=bigfont.render(str(i), True, (250,250,250))
screen.blit(text,((screen_coord[0]-text.get_width())//2,(screen_coord[1]-text.get_height())//2))
pygame.display.update()
time.sleep(1)
class Ball:
def __init__(self):
self.x = screen_coord[0] / 2
self.y = screen_coord[1] / 2
self.radius = 13 # 13
self.color = colors[random.randint(0, 8)]
self.dirchange = 5 # 5
self.sidedirchange = 60 # 60
self.defaultSpeed = {'e':200,'m':250,'h':300,'v':350,'p':300,'c':600}[mode] # pixels per sec
self.speed = self.defaultSpeed
self.speedIncrease = 15 # 15
if random.random() < .5:
self.dir = random.randint(-self.sidedirchange, self.sidedirchange)
else:
self.dir = random.randint(180 - self.sidedirchange, 180 + self.sidedirchange)
def draw(self):
pygame.draw.circle(screen, self.color, (round(self.x), round(self.y)), self.radius, 0)
# Calculate the point the ball will be in the next frame
def updatePoint(self, updateSpeed):
newx = self.x + (self.speed * math.cos(math.radians(self.dir)) / updateSpeed)
newy = self.y + (self.speed * math.sin(math.radians(self.dir)) / updateSpeed)
return newx, newy
# Check if the ball should be reflected the next frame
def invalid(self, newx, newy, leftPaddle, rightPaddle):
if newy + self.radius >= screen_coord[1]:
return 'bottomWall'
if newy <= self.radius:
return 'topWall'
rpaddlecontacty = newy - (math.sin(math.radians(self.dir)) * (newx - screen_coord[0] + rightPaddle.width))
if newx + self.radius > rightPaddle.x and rightPaddle.y - 15 <= rpaddlecontacty <= \
rightPaddle.y + rightPaddle.height + 15:
return 'rightPaddle'
lpaddlecontacty = newy - (math.sin(math.radians(self.dir)) * (leftPaddle.width - newx))
if newx - self.radius < leftPaddle.width and leftPaddle.y - 15 <= lpaddlecontacty <= \
leftPaddle.y + leftPaddle.height + 15:
return 'leftPaddle'
return 'valid'
#Reflect the ball off a given object
def reflect(self, newx, newy, object, leftPaddle, rightPaddle):
global totalhits
newdir = self.dir
if object == 'rightPaddle':
newx = self.x - 2 * (self.x - (rightPaddle.x - self.radius))
newy = self.y
newdir = 180 - (self.dir - 0) + random.randint(-self.dirchange, self.dirchange)
totalhits += 1
if object == 'leftPaddle':
newx = self.x + 2 * (self.x - (leftPaddle.x + leftPaddle.width + self.radius))
newy = self.y
newdir = 0 - (self.dir - 180) + random.randint(-self.dirchange, self.dirchange)
totalhits += 1
if object == 'bottomWall':
newx = self.x
newy = self.y - 2 * (self.y - (screen_coord[1] - self.radius))
newdir = 270 - (self.dir - 90) + random.randint(-self.dirchange, self.dirchange)
if object == 'topWall':
newx = self.x
newy = self.y - 2 * (self.y + (0 - self.radius))
newdir = 90 - (self.dir - 270) + random.randint(-self.dirchange, self.dirchange)
return newx, newy, newdir
#Update the ball for the next frame
def updateBall(self, updateSpeed, leftPaddle, rightPaddle, reset):
global rscore
global lscore
global totalhits
newx, newy = self.updatePoint(updateSpeed)
v = self.invalid(newx, newy, leftPaddle, rightPaddle)
newx, newy, newdir = self.reflect(newx, newy, v, leftPaddle, rightPaddle)
self.x, self.y, self.dir = newx, newy, newdir
if self.x < 0 and v!='leftpaddle' or self.x > screen_coord[0] and v!='rightpaddle' or reset:
three21()
leftPaddle.y=screen_coord[1] / 2 - paddleheight / 2
rightPaddle.y=screen_coord[1] / 2 - paddleheight / 2
if self.x < 0:
rscore += 1
if self.x > screen_coord[0]:
lscore += 1
self.speed = self.defaultSpeed
self.x = screen_coord[0] / 2
self.y = screen_coord[1] / 2
side = random.randint(1, 2)
if side == 1:
self.dir = random.randint(-self.sidedirchange, self.sidedirchange)
else:
self.dir = random.randint(180 - self.sidedirchange, 180 + self.sidedirchange)
totalhits = 0
self.speed = self.speed + self.speedIncrease / updateSpeed
self.draw()
if 90-self.dirchange-5 < (self.dir % 180) < 90:
self.dir -= 10
if 90+self.dirchange+5 > (self.dir % 180) > 90:
self.dir += 10
# ===========================================
class Paddle:
# set the paddle up
def __init__(self, x, upkey, downkey):
self.upkey = upkey
self.downkey = downkey
self.x = x
self.y = screen_coord[1] / 2 - paddleheight / 2
self.height = paddleheight
self.width = paddlewidth
self.color = paddlecolor
self.speed = 600 # 600
if mode == 'c':
self.speed = 1000
def spot(self):
dir = ball1.dir % 360
if 90 < dir < 270:
if self.upkey == 'w':
xchange = ball1.x - (self.x + self.width)
else:
xchange = screen_coord[0] + ball1.x - 3 * self.width
else:
if self.upkey == 'w':
xchange = -(2 * screen_coord[0] - 3 * self.width - ball1.x)
else:
xchange = self.x - ball1.x
if self.upkey == 'w' or 90 < dir < 270:
now = -(math.tan(math.radians(dir))) * xchange + ball1.y
else:
now = (math.tan(math.radians(dir))) * xchange + ball1.y
while now > screen_coord[1] or now < 0:
if now < 0:
now = -now
else:
now = 2 * screen_coord[1] - now
return now
# draw the paddle
def draw(self):
pygame.draw.rect(screen, self.color, (round(self.x), round(self.y), self.width, self.height))
# check input, change coordinates, and draw
def keyspressed(self):
global mode
pygame.event.pump()
keys = pygame.key.get_pressed()
if self.downkey == 'downarrow':
# downkey = keys[pygame.K_DOWN]
if mode in ['p', 'h', 'm', 'e', 'v']:
downkey = keys[pygame.K_DOWN]
if mode in ['c']:
if self.spot() > self.y + self.height / 2:
downkey = 1
else:
downkey = 0
if self.upkey == 'uparrow':
# upkey = keys[pygame.K_UP]
if mode in ['p', 'h', 'm', 'e', 'v']:
upkey = keys[pygame.K_UP]
if mode in ['c']:
if self.spot() < self.y + self.height / 2:
upkey = 1
else:
upkey = 0
if self.downkey == 's':
if mode in ['p']:
downkey = keys[pygame.K_s]
if mode in ['c', 'v']:
downkey = self.spot() > self.y + self.height / 2
if mode in ['h']:
downkey = ball1.y > self.y + self.height / 2
if mode in ['e']:
downkey = ball1.y > self.y + self.height / 2 and random.randint(1, 4) == 1
if mode in ['m']:
downkey = ball1.y > self.y + self.height / 2 and random.randint(1, 2) == 1
if self.upkey == 'w':
if mode in ['p']:
upkey = keys[pygame.K_w]
if mode in ['c', 'v']:
upkey = self.spot() < self.y + self.height / 2
if mode in ['h']:
upkey = ball1.y < self.y + self.height / 2
if mode in ['e']:
upkey = ball1.y < self.y + self.height / 2 and random.randint(1, 4) == 1
if mode in ['m']:
upkey = ball1.y < self.y + self.height / 2 and random.randint(1, 2) == 1
if downkey == True and upkey == False:
return 'down'
if downkey == False and upkey == True:
return 'up'
if downkey == True and upkey == True:
return 'both'
if downkey == False and upkey == False:
return 'none'
def updatePaddle(self):
if self.keyspressed() == 'down' and self.y <= screen_coord[1] - self.height:
self.y = self.y + self.speed / updateSpeed
if self.keyspressed() == 'up' and self.y >= 0:
self.y = self.y - self.speed / updateSpeed
self.draw()
instructions()
ball1 = Ball()
leftPaddle = Paddle(0, 'w', 's')
rightPaddle = Paddle(screen_coord[0] - paddlewidth, 'uparrow', 'downarrow')
prevtime, resettime, reset = 0, 0, 0
three21()
while True:
curtime = timer()
sleeptime = 1 / updateSpeed + prevtime - curtime
prevtime = timer()
if sleeptime < 0:
sleeptime = 0
time.sleep(sleeptime)
screen.fill(black)
leftPaddle.updatePaddle()
rightPaddle.updatePaddle()
ball1.updateBall(updateSpeed, leftPaddle, rightPaddle, reset)
printscore(totalhits, lscore, rscore, 50, 50, 20)
pygame.display.update()
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
lscore, rscore, totalhits = 0, 0, 0
reset = True
else:
reset = False
if keys[pygame.K_ESCAPE] or keys[pygame.K_q]:
lscore, rscore, totalhits = 0, 0, 0
reset=True
instructions()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.QUIT()
sys.exit() |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 11:14:35 2017
@author: tpp05624
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false
"""
class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
R=0
L=0
U=0
D=0
for digit in moves:
if digit=='R':
R=R+1
L=L-1
elif digit=='L':
L=L+1
R=R-1
elif digit=='D':
D=D+1
U=U-1
elif digit=='U':
U=U+1
D=D-1
if R==L==U==D==0:
return True
else:
return False |
# 生成器 迭代器 三元表达式
list1 = ('第%d个元素' % i for i in range(20) if i % 3 == 0) # 生成器表达式
list2 = ['第%d个元素' % i for i in range(20) if i % 3 == 0] # 列表解析
print(list1)
print(list2)
print(next(list1))
print(list1.__next__())
|
class Test:
def __init__(self, foo):
self.__foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
class Person(object):
# 限定Person对象只能绑定_name, _age和_gender属性
__slots__ = ('_name', '_age', '_gender')
def __init__(self, name, age):
self._name = name
self._age = age
# 访问器 - getter 方法
@property
def name(self):
return self._name
# 访问器 - getter 方法
@property
def age(self):
return self._age
# 修改器 - setter方法
@age.setter
def age(self, age):
self._age = age
def play(self):
if self._age < 18:
print('%s正在玩飞行棋.' % self._name)
else:
print('%s正在玩斗地主' % self._name)
def main():
test = Test('hello')
# test.__bar() # 不可访问
# print(test.__foo) # 不可访问
test._Test__bar() # 可以访问
print(test._Test__foo) # 可以访问
John = Person('John', 16)
John_name = John.name
print(John_name)
John.age = 18
# John.name = 'John-117' # can't set attribute
John.play()
if __name__ == '__main__':
main()
|
# 返回给定文件名的后缀名
def get_suffix(file_name, has_dot=False):
dot_pos = file_name.rfind('.')
if 0 < dot_pos < len(file_name):
index = dot_pos if has_dot else dot_pos + 1
return file_name[index:]
else:
return ''
if __name__ == '__main__':
print(get_suffix('xxx.avi'))
print(get_suffix('xxx.avi', True))
print(get_suffix('..aviu'))
|
import random
secretnumber = random.randint(1,20)
print('I am choosing a number!!!')
for i in range(1,4):
print('Try to guess number')
guess = int(input('enter a number between 1 to 20: '))
if guess < secretnumber:
print('selected number is too small')
elif guess > secretnumber:
print('selected number is too large)
else:
break
if guess == secretnumber:
print('congo right guess')
else:
print(str(secretnumber))
|
# Python 3
# Hint:
# Use "print type(<variable>)" to figure out data type for a variable,
# like shown in the previous task
'''
Description: Write a Python 3 script that divides both x and y together. Make sure to get a data type of both int and float as the quotient.
Sample Output:
x/y data type (as int): <type 'int'>
x/y data type (as float): <type 'float'>
1
1.0
'''
x = 9
y = 5
# CODE HERE
|
password = 'a123456'
i = 3
while i >= 0:
pwd = input('請輸入你的密碼: ')
if pwd == password:
print('登入成功')
break
else:
if i > 0:
print('密碼錯誤.你還有', i ,'次機會')
i = i - 1
else:
print('密碼錯誤.沒機會了可憐哪')
break
|
import abc
from abc import abstractmethod
from logging import Logger
class InvalidValidator(Exception): ...
class BaseValidator(metaclass=abc.ABCMeta):
log: Logger
def __init__(self) -> None: ...
@abstractmethod
def validate(self, input_string: str) -> bool: ...
|
def compute_grade(score):
if score > 1:
return 'It is not possible.'
if score>0.9:
grade = 'A'
elif score > 0.8:
grade = 'B'
else:
grade = 'F'
return grade
res = compute_grade(0.5)
|
import itertools, collections
from functools import partial
def opposite(A):
return tuple([-1*a for a in A])
def forSome(conditional, set, arg0):
for element in set:
if conditional(arg0, element):
return True
return False
def forAll(conditional, set, arg0):
for element in set:
if not conditional(arg0, element):
return False
return True
def alignCheck(A, B, level='line'):
"""Are A and B on the same row or column?"""
diff = 0
for a, b in zip(A, B):
if a != b: diff += 1
if A == B:
return False
elif diff == 1 and level == 'line':
return True
elif diff == 2 and level == 'plane':
return True
else:
return False
def diagonalCheck(A, B):
"""Are A and B on a diagonal together?"""
# trivial case
if A == B:
return False
else:
dim = len(B)
center = tuple([0 for i in range(dim)])
non_center = set([A, B]).difference([center])
non_center = list(non_center)[0]
# one is center one is corner
if center in (A, B) and 0 not in non_center:
return True
# the squares are across the grid from each other
elif opposite(A) == B:
return True
else:
return False
def rowDiff(A, B):
"""If there are 2/3 in a row, where is the empty square?"""
loc = 0
for a, b in zip(A, B):
if a == b:
loc += 1
else:
break
diff = set([-1, 0, 1]).difference([A[loc], B[loc]])
C = list(A)
C[loc] = list(diff)[0]
return tuple(C)
def diagonalDiff(A, B):
"""If there are 2/3 in a diagonal, where is the empty square?"""
center = tuple([0 for i in range(len(A))])
if A == center:
return opposite(B)
elif B == center:
return opposite(A)
else:
return center
def findDiff(A, B):
"""Where is the empty square?"""
if alignCheck(A, B):
return rowDiff(A, B)
elif diagonalCheck(A, B):
return diagonalDiff(A, B)
else:
return None
class square:
"""A single 'square' or unit of the grid."""
def __init__(self, neighbors, mark):
"""
Parameters:
mark: string
indicates whether the square is empty, "X" or "O"
neighbors: list
coordinates for surrounding squares
"""
self.mark = mark
self.neighbors = neighbors
self.empties = len(neighbors)
self.X_count = 0
class grid:
"""The grid for the tic tac toe environment."""
def near(self, X, positions):
"""
Find all squares in line with X.
Parameters:
X : tuple
position of mark
positions : list of tuples
all possible positions
"""
neighbors = []
for pos in positions:
if alignCheck(X, pos) or diagonalCheck(X, pos):
neighbors.append(pos)
else:
pass
return neighbors
def __init__(self, dim=2):
"""
Parameters:
dim : int
The number of dimensions of the tic tac toe game. For example
dim = 3 gives you a cube for the tic tac toe grid.
"""
if dim < 2:
raise ValueError("Invalid dimension given." + \
"It must be an integer greater than one.")
iter = itertools.product([-1,0,1], repeat=dim)
all = [x for x in iter]
self.positions = {x : square(self.near(x, all), '') for x in all}
self.marked = []
self.dim = dim
def viewPos(self, loc):
if self.positions[loc].mark == '':
pos = str(loc)
pos = pos.replace('(1', '( 1').replace(',1)', ', 1)')
pos = pos.replace('(0', '( 0').replace(',0)', ', 0)')
pos = pos.replace(', -1)', ',-1)')
return pos
else:
return ' ' + self.positions[loc].mark + ' '
def showGrid(self, dim1=0, dim2=1):
"""
Produces a view of the grid with all the marks.
Parameters (ignore if normal 2D tic tac toe:
dim1 : int
first dimension of slice view
dim2 : int
second dimension of slice view
"""
if dim1 < dim2:
d1 = dim1
d2 = dim2
else:
d1 = dim2
d2 = dim1
div1 = "\n | | \n"
div2 = "-----------------------"
if self.dim > 2:
iter = itertools.product([-1,0,1], repeat=(self.dim - 2))
for x_other in iter:
print 'Level:'
print list(x_other).insert(d1, 'Dim 1').insert(d2, 'Dim 2')
view = ""
for y in [1, 'div', 0, 'div', -1]:
if y == 'div':
view += div2
else:
x1 = list(x_other).insert(d1, -1).insert(d2, y)
x2 = list(x_other).insert(d1, 0).insert(d2, y)
x3 = list(x_other).insert(d1, 1).insert(d2, y)
m1 = self.viewPos((-1, y))
m2 = self.viewPos((0, y))
m3 = self.viewPos((1, y))
view += div1
view += "{0}|{1}|{2}".format(m1, m2, m3)
view += div1
print view
else:
view = ""
for y in [1, 'div', 0, 'div', -1]:
if y == 'div':
view += div2
else:
m1 = self.viewPos((-1, y))
m2 = self.viewPos((0, y))
m3 = self.viewPos((1, y))
view += div1
view += "{0}|{1}|{2}".format(m1, m2, m3)
view += div1
print view
def checkStatus(self):
"""
Check if someone has won the game.
Parameters:
loc : tuple
location of last mark
"""
loc = self.marked[-1]
sq1 = self.positions[loc]
sq3 = None
loc3 = None
for loc2 in sq1.neighbors:
sq2 = self.positions[loc2]
loc3 = findDiff(loc, loc2)
sq3 = self.positions[loc3]
# print loc, loc2, loc3
if sq3 is not None and sq3.mark == sq1.mark:
aligned1 = alignCheck(loc, loc2) and \
alignCheck(loc2, loc3) and \
alignCheck(loc3, loc)
aligned2 = diagonalCheck(loc, loc2) and \
diagonalCheck(loc2, loc3) and \
diagonalCheck(loc3, loc)
aligned = aligned1 or aligned2
matched = sq1.mark == sq2.mark == sq3.mark
if matched and aligned:
if sq1.mark == 'O':
return -1
elif sq1.mark == 'X':
return 1
if len(self.marked) == 3**self.dim:
return 0
return None
def makeMark(self, loc, mark):
"""
Mark a single square in the grid.
Parameters:
loc : tuple
where the mark will be located
mark : string
the string for the mark ('X' or 'O')
"""
self.marked.append(loc)
self.positions[loc].mark = mark
for pos in self.positions:
if pos in self.positions[loc].neighbors:
self.positions[pos].empties -= 1
if mark == 'X':
self.positions[pos].X_count += 1
# print self.checkStatus()
def findLastMark(self, mark):
if self.marked:
for i in range(1, len(self.marked)):
pos = self.marked[-i]
if self.positions[pos].mark == mark:
return pos
else:
return None
def findPotential(self):
"""Which empty square in the grid has the most empty neighborhood?
For ties, the first one that matches the conditions is returned"""
bestPos = None
currEmpties = 0
X_pos = [x for x in self.positions if self.positions[x].mark == 'X']
O_pos = [x for x in self.positions if self.positions[x].mark == 'O']
def distCheck(A, B):
for a,b in zip(A, B):
if abs(a - b) >= 2:
return False
return True
def openCheck(A, B):
openPos = findDiff(A, B)
if openPos and self.positions[openPos].mark == '':
return True
else:
return False
for pos in self.positions:
sq = self.positions[pos]
if sq.empties >= currEmpties and sq.mark == '':
min_X = len(X_pos) >= 2
closeToX = forSome(distCheck, X_pos, pos)
open = forSome(openCheck, O_pos, pos)
if min_X and closeToX and open:
currEmpties = sq.empties
bestPos = pos
elif not min_X or not open:
currEmpties = sq.empties
bestPos = pos
return bestPos
def findMatch(self, mark):
"""Where is there 2/3 in a row marked?"""
for pos0, pos1 in itertools.combinations(self.marked, 2):
mark0 = self.positions[pos0].mark
mark1 = self.positions[pos1].mark
if mark0 == mark1 == mark:
sq = self.positions[pos1]
trivial = pos1 == pos0
matched = sq.mark == mark
candidate = findDiff(pos0, pos1)
exists = candidate != None
if not trivial and matched and exists:
empty = self.positions[candidate].mark == ''
if empty:
return candidate
return None
def parseInput(self, input):
"""
Parses input into a usable tuple.
Parameters:
input : str
input mark location string to be parsed into a tuple
Return:
parsed : tuple
the tuple of parsed player's input
"""
if isinstance(input, str):
parsed = input.replace('\n','').replace(' ','')
parsed = parsed.strip(' ()')
parsed = parsed.split(',')
parsed = [int(a) for a in parsed]
elif isinstance(input, tuple):
parsed = input
else:
raise ValueError("Input needs to be either string or tuple.")
return tuple(parsed)
def playerMove(self, input):
"""
Parameters:
input_func : function
function the produces a tuple of player's input for next move
"""
playerInput = self.parseInput(input)
sq = self.positions[playerInput]
if sq.mark != '':
print 'Invalid location.'
self.makeMark(playerInput, 'X')
def computerMove(self):
computer_win_move = self.findMatch('O')
player_win_move = self.findMatch('X')
if computer_win_move:
self.makeMark(computer_win_move, 'O')
elif player_win_move:
self.makeMark(player_win_move, 'O')
else:
self.makeMark(self.findPotential(), 'O')
def checkValid(self, input):
for x in input:
if isinstance(x, int) and abs(x) <= 1:
return True
else:
return False
def getInput(self):
self.showGrid()
print "Where do you want your \'X\'?"
message = "Please enter the coordinates of the location:\n"
test_input = None
while True:
self.showGrid()
test_input = self.parseInput(raw_input(message))
valid = self.checkValid(test_input)
if valid and self.positions[test_input].mark == '':
break
else:
print 'Invalid location, please choose another.'
return test_input
def step(self, move='player'):
if move == 'player':
self.playerMove(self.getInput())
elif move == 'computer':
self.computerMove()
else:
error = "'move' parameter must be either 'player' or 'computer'."
raise ValueError(error) |
"""
By GTDT
11/19/2020
51 Challange: Random Number Generator
7 points
Make a basic program that generate a number between 1-10 and the input should say 'enter a number'
when you enter the number the bot should also select a random number between 1-10 if your number
luckily is the same as the program, the program answers You won! i select <number> and you selected
<number> if your number doesen't matches the program. It should answer with well looks like you lost try again
"""
import random
R = random.randint(1, 10)
EnterN = int(input("Enter a number: "))
if EnterN == R:
print("You won!")
else:
print("Well looks like you lost try again")
print(f"The number was {R}")
|
import requests
import os
from datetime import datetime
key = os.environ.get('WEATHER_KEY')
def get_input(question):
return input(question)
def make_api_call(city, country):
query = {'q': city + ',' + country, 'units': 'imperial', 'appid': key} #searches openweathermap by city & country
url = 'https://api.openweathermap.org/data/2.5/forecast'
try:
data = requests.get(url, params=query).json()
forecast = data['list'] #list of weather data
except KeyError:
print(f'KeyError: Please check city name and country code in {query}')
return 'Error! Please check city name and country code.', 0, 0, 0
weather = forecast[0] #returns current day
description = weather['weather'][0]['description']
temp = weather['main']['temp']
cloudy = weather['clouds']['all']
humidity = weather['main']['humidity']
description = description.capitalize()
return description, temp, cloudy, humidity
|
# The re.sub() tool (sub stands for substitution) evaluates a pattern and, for each valid match, it calls a method (or lambda).
# The method is called for all matches and can be used to modify strings in different ways.
# The re.sub() method returns the modified string as an output.
# Learn more about re.sub().
import re
#Squaring numbers
def square(match):
number = int(match.group(0))
return str(number**2)
print re.sub(r "\d+", square, "1 2 3 4 5 6 7 8 9") |
name = input("Input your name here: ")
print(f"Hello, {name}") |
from random import choice
from Word import *
from Experts.Expert import *
from Experts.PoemMakingExperts.PoemMakingExpert import *
class OxymoronExpert(PoemMakingExpert):
"""Making oxymoron (words with opposite meaning, antonyms) by enumarating antonyms or adding antonym epithet"""
def __init__(self, blackboard):
super(OxymoronExpert, self).__init__(blackboard, "Oxymoron Expert", 2)
def generate_phrase(self, pool):
try:
word = choice(list(pool.antonyms))
antonym = choice(list(pool.antonyms[word]))
phrase = []
phrase.append(word)
phrase.append(Word(choice(["and", "or", "but"])))
phrase.append(antonym)
return phrase
except:
return
|
# dataframes are bunch of series objects put together to share the same index
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)
df = pd.DataFrame(randn(5,4),index='A B C D E'.split(),columns='W X Y Z'.split())
print(f'dataframe:\n{df}')
# selection and indexing
print(df['W'])
print(f"type of df['W']: {type(df['W'])}")
print(f"not recommended to use sql syntax:\n{df.W}")
print(f"get W and Z columns:\n {df[['W', 'Z']]}")
# create new column
df['new'] = df['W'] + df['Y']
print(f"with new column:\n{df}")
# remove column, explicitly say inplace so don't accidentally affect the dataframe
df.drop('new', axis=1, inplace=True)
print(f"dropped new column:\n{df}")
# remove a row, axis=0 is the default
print(f"dropped E row:\n{df.drop('E')}")
# because I didn't do inplace, is not permanently dropped from dataframe
print(f'rows,columns:{df.shape}')
# selecting rows
# by label
print(f"select row A: {df.loc['A']}")
# by index
print(f"select row 3 by index:\n{df.iloc[2]}")
# select subset of rows and columns
print(f"one element at B Y: {df.loc['B', 'Y']}")
print(f"slice of elements rows AB, columns WY: {df.loc[['A','B'],['W','Y']]}")
# conditional selection of dataframes similar to numpy
print(f'dataframe is :\n{df}')
print(f'dataframe > 0:\n{df > 0}')
booldf = df > 0
print(f'value with null where condition not true df > 0:\n{df[booldf]}')
print(f'one step apply condition:\n{df[df>0]}')
print(f"{df[df['W']>0]}")
# two step is:
resultdf = df[df['W']>0]
print(f"{resultdf['Y']}")
# one step is:
print(f"{df[df['W']>0]['Y']}")
print(f"{df[df['Z']<0]}")
print(f"{df[df['W']>0]}")
print(f"{df[df['W']>0]['Y']}")
# mult steps:
boolser = df['W']>0
result = df[boolser]
mycols = ['Y', 'X']
print(f"{result[mycols]}")
# one step
print(f"{df[df['W']>0][['Y','X']]}")
# multiple conditions with and (&)
print(f"{df[(df['W']>0) & (df['Y'] > 1)]}")
# multiple conditions with or (|)
print(f"{df[(df['W']>0) | (df['Y'] > 1)]}")
# reset index
print(f"reset index:\n{df.reset_index()}")
# to do permanently:
# print(f"reset index:\n{df.reset_index(inplace=True)}")
newindex = 'CA NY WY OR CO'.split()
print(f"index list is: {newindex}")
df['States'] = newindex
print(f"new column added to dataframe called states:\n{df}")
# must do inplace=True for this change to be permanent
print(f"set states to be index:\n{df.set_index('States')}")
# multi-index and index hierarchy
# Index Levels
outside = ['G1','G1','G1','G2','G2','G2']
inside = [1,2,3,1,2,3]
# make list of tuple pairs
hier_index = list(zip(outside,inside))
print(f"tuple pairs:\n{hier_index}")
hier_index = pd.MultiIndex.from_tuples(hier_index)
print(f"multi-level labels:\n{hier_index}")
df = pd.DataFrame(np.random.randn(6,2),index=hier_index,columns=['A','B'])
print(f"dataframe is now:\n{df}")
print(f"get G1 sub-dataframe:\n{df.loc['G1']}")
# do outside to inside index (in order)
print(f"get first row of sub-dataframe:\n{df.loc['G1'].loc[1]}")
# give indexes names
print(f'names of indexes before you name them: {df.index.names}')
df.index.names = ['Groups', 'Num']
print(f'dataframe with index names:\n{df}')
print(f"get G2 row 2 column B element:\n{df.loc['G2'].loc[2]['B']}")
print(f"get G1 row 3 column A element:\n{df.loc['G1'].loc[3]['A']}")
# cross section for selection (alternate way)
print(f"grab G1:\n{df.xs('G1')}")
print(f"grab row 1 in G1:\n{df.xs('G1', 1)}")
print(f"grab all Num=1 rows:\n{df.xs(1,level='Num')}") |
''' PROGRAM :Create a RESTFul API server in Python Flask. To achieve your target
kindly go through the following process:-
1) You have to hit the URL https://api.thedogapi.com/v1/breeds into a
local JSON file into your localhost.
2) From the JSON file scrap the data of the breed of dog, country of
origin, bred for which purpose and the image of the dog.
3) Display the data in a tabular format into a HTML page.
4) Send the extracted data into a MongoDB database with basic CRUD
operations associated with it
'''
#PROGRAMMED BY : Badam Jwala Sri Hari
#MAIL ID : [email protected]
#DATE : 28-09-2021
#PYTHON VERSION: 3.9.7
#FLASK VERSION : 2.0.1
#CAVEATS : None
#LICENSE : None
from flask import Flask
from flask import render_template
from flask import request
import json
from pymongo import MongoClient
import requests
import json
# PYTHON REQUESTS & API
def create_json(data,file):
with open(file, "w") as file:
return json.dump(data, file,indent=4)
def read_json(file):
with open(file)as file:
return json.load(file)
def check_url(url):
try:
url = requests.get(url)
return True
except:
return False
def read_url(url):
url = requests.get(url)
return url.json()
# Mongo
connection = MongoClient("mongodb://localhost:27017")
def mongo_connection():
if connection:
return True
else:
return False
def mongodb_list():
if mongo_connection() == True:
return connection.list_database_names()
def db_exists( db_name):
if db_name in mongodb_list():
return True
else:
return False
def create_new_collection(db_name, new_collection):
if connection:
db_name = connection[db_name]
new_collection = db_name[new_collection]
return new_collection
else:
return("error")
# Inserting data into mongodb
def insert_data(db_name,collection_name,data):
if connection:
connection[db_name][collection_name].insert_one(data)
return "success"
else:
return "error"
def display(db_name,collection_name):
a=[]
if connection:
for i in connection[db_name][collection_name].find():
a.append(i)
for i in a:
print(i)
print("-----------------------------------------------")
# Data is extracted from these URL
url = "https://api.thedogapi.com/v1/breeds"
# temp and headings will be used in result.html
temp=[] # temp is to store the list of all extracted elements
headings=["Image","Name","Bred_for","Country"]
# Checking whether URL is exists or not
if check_url(url)==True:
# Reading data from url and storing into json
d=read_url(url)
file="dog_breed.json"
create_json(d,file)
dic=read_json("dog_breed.json")
# Extracting the name,origin(country), bred_for,image
for i in dic:
one={'name':i['name']}
if 'origin' in i and len(i['origin'])!=0:
one['origin']=i['origin']
else:
one['origin']="-"
if 'bred_for' in i and len(i['bred_for'])!=0:
one['bred_for']=i['bred_for']
else:
one['bred_for']="-"
if 'url' in i['image']:
one['url']=i['image']['url']
temp.append([one['url'], [one['name'],one['bred_for'],one['origin']] ])
# Inserting data into mongodb
insert_data("mongo_python","dog_breed",one)
app = Flask(__name__)
@app.route('/')
def index():
# Heading and temp are kept as an arguments render template
# So,that we can use them in result.html file to display
return render_template('result.html',headings=headings,temp=temp)
app.run(debug=True, port=5000)
|
#PROGRAM : Find the possible largest and smallest number with given numbers
#PROGRAMMED BY : Badam Jwala Sri Hari
#MAIL ID : [email protected]
#DATE : 17-09-2021
#PYTHON VERSION: 3.9.7
#CAVEATS : None
#LICENSE : None
n=list(map(int,list(input())))
#Sorting the list
#converting every element to string because join method accepts only string object
n=list(map(str,sorted(n)))
#joining the sorted elements
s="".join(n)
#As the sorted method sorts in ascending order we have to reverse the string to get greatest number
print("Greatest number:",s[::-1])
#joined string is directly printed
print("Smallest number:",s)
|
from bank_account import Account
class Saving_Account(Account):
def __init__(self, initial_balance):
super().__init__(initial_balance)
def deposit(self, amount):
self._balance += amount
if amount < 500:
return f"You would like to deposit {amount}. Your overall balance is {self._balance}."
else:
print("Deposit unsuccessful - For amounts over £500 Please speak to the bank")
self._balance = amount |
# -*- coding: utf-8 -*-
import random
class Player(object):
def __init__(self):
self.cards = []
self.a_11 = 0
self.a_1 = 0
self.other = 0
@property
def points(self):
# 真正分數
return self.a_11 * 11 + self.a_1 * 1 + self.other
@property
def min_points(self):
# A 都換成 1 不代表真正分數,只是決定是否 < 17 再拿牌
return (self.a_11 + self.a_1) * 1 + self.other
def add_card(self, card):
self.cards += [card]
if card == "A":
self.a_11 += 1
elif card in ["J", "Q", "K"]:
self.other += 10
else:
self.other += int(card)
self._balance()
def _balance(self):
if self.points > 21 and self.a_11 != 0:
# 你只需改變數量,呼叫 points 時會去計算現在的分數,遞迴直到 分數低於 21 或是 全部的 A 都換成 1
self.a_11 -= 1
self.a_1 += 1
# 遞迴
self._balance()
# 自己設定發牌順序的發牌機
class CardGenerator(object):
def __init__(self, my_card_list):
self.cards = my_card_list
def get_card(self):
return self.cards.pop(0)
# 隨機發牌機
class RandomCardGenerator(object):
def __init__(self):
self.cards = list("A23456789JQK" * 4) + ["10", "10", "10", "10"] # '10' 有兩個字元不能用前面方法轉陣列
def get_card(self):
random_index = random.randint(1, len(self.cards))
return self.cards.pop(random_index - 1) # index 從 0 開始
def play(players, card_generator):
# 我們會同時發給所有人到兩張,檢查第一人即可
if len(players[0].cards) <= 2:
for player in players:
player.add_card(card_generator.get_card())
else:
if all([player.min_points >= 17 for player in players]):
# 遊戲結束條件,所有玩家都大於 17 不用再發牌,也可以設計成某一位穩贏就結束(寫出來會很醜)
return
else:
for player in players:
if player.min_points < 17:
player.add_card(card_generator.get_card())
# 繼續下一輪 遞迴
return play(players, card_generator)
if __name__ == '__main__':
# Test game
test_card_lists = [
["A", "A", "A", "A", "K", "8", "6", "5"],
["A", "5", "A", "J"],
["5", "A", "A", "J"],
["A", "A", "5", "J"],
["A", "A", "K", "2", "6"],
["K", "A", "A", "2", "6"],
["A", "K", "A", "2", "6"],
]
for card_list in test_card_lists:
print "發牌順序 {}".format(card_list)
p1 = Player()
card_generator = CardGenerator(card_list)
play([p1], card_generator)
print "Player 1 拿著牌 {}, 點數是 {}".format(p1.cards, p1.points)
print "-" * 60
print "=" * 60
# Real game, you can add player
p1 = Player()
p2 = Player()
players = [p1, p2]
card_generator = RandomCardGenerator()
play(players, card_generator)
for i, player in enumerate(players):
print "Player {} 拿著牌 {}, 點數是 {}".format(i, player.cards, player.points)
|
# SQL
<hr style="height:1px;border:none;color:#666;background-color:#666;" />
**SQL** (Structured Query Language) is a programming language that has operations to define, logically organize, manipulate, and perform calculations on data stored in a relational database management system (RDBMS).
SQL is a declarative language. This means that the user only needs to specify *what* kind of data they want, not *how* to obtain it. An example is shown below, with an imperative example for comparison:
- **Declarative**: Compute the table with columns "x" and "y" from table "A" where the values in "y" are greater than 100.00.
- **Imperative**: For each record in table "A", check if the record contains a value of "y" greater than 100. If so, then store the record's "x" and "y" attributes in a new table. Return the new table.
In this tutorial, we will write SQL queries as Python strings, then use `pandas` to execute the SQL query and read the result into a `pandas` DataFrame. As we walk through the basics of SQL syntax, we'll also occasionally show `pandas` equivalents for comparison purposes.
## Executing SQL Queries through `pandas`
<hr>
To execute SQL queries from Python, we will connect to a database using the [sqlalchemy](http://docs.sqlalchemy.org/en/latest/core/tutorial.html) library. Then we can use the `pandas` function [pd.read_sql](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html) to execute SQL queries through this connection.
import pandas as pd
import sqlalchemy
sqlite_uri = "sqlite:///sql_basics.db"
sqlite_engine = sqlalchemy.create_engine(sqlite_uri)
This database contains one relation: `prices`. To display the relation we run a SQL query. Calling `read_sql` will execute the SQL query on the RDBMS, then return the results in a `pandas` DataFrame.
# pd.read_sql takes in a parameter for a SQLite engine, which we create below
sql_expr = """
SELECT *
FROM Prices
"""
prices = pd.read_sql(sql_expr, sqlite_engine)
prices.head()
## SQL Syntax
<hr>
All SQL queries take the general form below:
```SQL
SELECT [DISTINCT] <column expression list>
FROM <relation>
[WHERE <predicate>]
[GROUP BY <column list>]
[HAVING <predicate>]
[ORDER BY <column list>]
[LIMIT <number>]
```
```{note}
1. **Everything in \[square brackets\] is optional.** A valid SQL query only needs a `SELECT` and a `FROM` statement.
2. **SQL SYNTAX IS GENERALLY WRITTEN IN CAPITAL LETTERS.** Although capitalization isn't required, it is common practice to write SQL syntax in capital letters. It also helps to visually structure your query for others to read.
3. `FROM` query blocks can reference one or more tables, although in this section we will only look at one table at a time for simplicity.
```
### SELECT and FROM
The two mandatory statements in a SQL query are:
* `SELECT` indicates the columns that we want to view.
* `FROM` indicates the tables from which we are selecting these columns.
To display the entire `prices` table, we run:
sql_expr = """
SELECT *
FROM prices
"""
pd.read_sql(sql_expr, sqlite_engine).head()
`SELECT *` returns every column in the original relation. To display only the retailers that are represented in `prices`, we add the `retailer` column to the `SELECT` statement.
sql_expr = """
SELECT retailer
FROM prices
"""
pd.read_sql(sql_expr, sqlite_engine).head()
If we want a list of unique retailers, we can call the `DISTINCT` function to omit repeated values.
sql_expr = """
SELECT DISTINCT(retailer)
FROM prices
"""
pd.read_sql(sql_expr, sqlite_engine).head()
This would be the functional equivalent of the following `pandas` code:
prices['retailer'].unique()
Each RDBMS comes with its own set of functions that can be applied to attributes in the `SELECT` list, such as comparison operators, mathematical functions and operators, and string functions and operators. Here we use PostgreSQL, a mature RDBMS that comes with hundreds of such functions, the complete list is available [here](https://www.postgresql.org/docs/9.2/static/functions.html). Keep in mind that each RDBMS has a different set of functions for use in `SELECT`.
The following code converts all retailer names to uppercase and halves the product prices.
sql_expr = """
SELECT
UPPER(retailer) AS retailer_caps,
product,
price / 2 AS half_price
FROM prices
"""
pd.read_sql(sql_expr, sqlite_engine).head(10)
```{note}
Notice that we can **alias** the columns (assign another name) with `AS` so that the columns appear with this new name in the output table. This does not modify the names of the columns in the source relation.
```
### WHERE
The `WHERE` clause allows us to specify certain constraints for the returned data; these constraints are often referred to as **predicates**. For example, to retrieve only gadgets that are under $500:
sql_expr = """
SELECT *
FROM prices
WHERE price < 500
"""
pd.read_sql(sql_expr, sqlite_engine).head(10)
We can also use the operators `AND`, `OR`, and `NOT` to further constrain our SQL query. To find an item on Amazon without a battery pack under $300, we write:
sql_expr = """
SELECT *
FROM prices
WHERE retailer = 'Amazon'
AND NOT product = 'Battery pack'
AND price < 300
"""
pd.read_sql(sql_expr, sqlite_engine)
The equivalent operation in `pandas` is:
prices[(prices['retailer'] == 'Amazon')
& ~(prices['product'] == 'Battery pack')
& (prices['price'] <= 300)]
```{note}
There's a subtle difference that's worth noting: the index of the Chromebook in the SQL query is 0, whereas the corresponding index in the DataFrame is 4. This is because SQL queries always return a new table with indices counting up from 0, whereas `pandas` subsets a portion of the DataFrame `prices` and returns it with the original indices. We can use [pd.DataFrame.reset_index](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html) to reset the indices in `pandas`.
```
### Aggregate Functions
So far, we've only worked with data from the existing rows in the table; that is, all of our returned tables have been some subset of the entries found in the table. But to conduct data analysis, we'll want to compute aggregate values over our data. In SQL, these are called **aggregate functions**.
If we want to find the average price of all gadgets in the `prices` relation:
sql_expr = """
SELECT AVG(price) AS avg_price
FROM prices
"""
pd.read_sql(sql_expr, sqlite_engine)
Equivalently, in `pandas`:
prices['price'].mean()
A complete list of PostgreSQL aggregate functions can be found [here](https://www.postgresql.org/docs/9.2/static/functions.html). Though we're using PostgreSQL as our primary version of SQL, keep in mind that there are many other variations of SQL (MySQL, SQLite, etc.) that use different function names and have different functions available.
### GROUP BY and HAVING
With aggregate functions, we can execute more complicated SQL queries. To operate on more granular aggregate data, we can use the following two clauses:
- `GROUP BY` takes a list of columns and groups the table like the [pd.DataFrame.groupby](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) function in `pandas`.
- `HAVING` is functionally similar to `WHERE`, but is used exclusively to apply conditions to aggregated data. (Note that in order to use `HAVING`, it must be preceded by a `GROUP BY` clause.)
**Important**: When using `GROUP BY`, all columns in the `SELECT` clause must be either listed in the `GROUP BY` clause or have an aggregate function applied to them.
We can use these statements to find the maximum price at each retailer.
sql_expr = """
SELECT retailer, MAX(price) as max_price
FROM prices
GROUP BY retailer
"""
pd.read_sql(sql_expr, sqlite_engine)
Let's say we have a client with expensive taste and only want to find retailers that sell gadgets over $700. Note that we must use `HAVING` to define conditions on aggregated columns; we can't use `WHERE` to filter an aggregated column. To compute a list of retailers and accompanying prices that satisfy our needs, we run:
sql_expr = """
SELECT retailer, MAX(price) as max_price
FROM prices
GROUP BY retailer
HAVING max_price > 700
"""
pd.read_sql(sql_expr, sqlite_engine)
For comparison, we recreate the same table in `pandas`:
max_prices = prices.groupby('retailer').max()
max_prices.loc[max_prices['price'] > 700, ['price']]
### ORDER BY and LIMIT
These clauses allow us to control the presentation of the data:
- `ORDER BY` lets us present the data in alphabetical order of column values. By default, ORDER BY uses ascending order (`ASC`) but we can specify descending order using `DESC`.
- `LIMIT` controls how many tuples are displayed.
Let's display the three cheapest items in our `prices` table:
sql_expr = """
SELECT *
FROM prices
ORDER BY price ASC
LIMIT 3
"""
pd.read_sql(sql_expr, sqlite_engine)
Note that we didn't have to include the `ASC` keyword since `ORDER BY` returns data in ascending order by default.
For comparison, in `pandas`:
prices.sort_values('price').head(3)
(Again, we see that the indices are out of order in the `pandas` DataFrame. As before, `pandas` returns a view on our DataFrame `prices`, whereas SQL is displaying a new table each time that we execute a query.)
### Conceptual SQL Evaluation
Clauses in a SQL query are executed in a specific order. Unfortunately, this order differs from the order that the clauses are written in a SQL query. From first executed to last:
1. `FROM`: One or more source tables
2. `WHERE`: Apply selection qualifications (eliminate rows)
3. `GROUP BY`: Form groups and aggregate
4. `HAVING`: Eliminate groups
5. `SELECT`: Select columns
**Note on `WHERE` vs. `HAVING`**: Since the `WHERE` clause is processed before applying `GROUP BY`, the `WHERE` clause cannot make use of aggregated values. To define predicates based on aggregated values, we must use the `HAVING` clause.
## Summary
<hr>
We have introduced SQL syntax and the most important SQL statements needed to conduct data analysis using a relational database management system. |
# Applying Functions and Plotting in Pandas
<hr style="height:1px;border:none;color:#666;background-color:#666;" />
In this section, we will answer the question:
**Can we use the last letter of a name to predict the sex of the baby?**
Here's the Baby Names dataset once again:
import pandas as pd
baby = pd.read_csv('babynames.csv')
baby.head()
# the .head() method outputs the first five rows of the DataFrame
**Breaking the Problem Down**
Although there are many ways to see whether prediction is possible, we will use plotting in this section. We can decompose this question into two steps:
1. Compute the last letter of each name.
1. Group by the last letter and sex, aggregating on Count.
1. Plot the counts for each sex and letter.
## Apply
<hr>
`pandas` Series contain an `.apply()` method that takes in a function and applies it to each value in the Series.
names = baby['Name']
names.apply(len)
To extract the last letter of each name, we can define our own function to pass into `.apply()`:
def last_letter(string):
return string[-1]
names.apply(last_letter)
## String Manipulation
<hr>
Although `.apply()` is flexible, it is often faster to use the built-in string manipulation functions in `pandas` when dealing with text data.
`pandas` provides access to string manipulation functions using the `.str` attribute of Series.
names = baby['Name']
names.str.len()
We can directly slice out the last letter of each name in a similar way.
names.str[-1]
We suggest looking at the docs for the full list of string methods ([link](https://pandas.pydata.org/pandas-docs/stable/text.html)).
We can now add this column of last letters to our `baby` DataFrame.
baby['Last'] = names.str[-1]
baby
## Grouping
<hr>
To compute the sex distribution for each last letter, we need to group by both Last and Sex.
# Shorthand for baby.groupby(['Last', 'Sex']).agg(np.sum)
baby.groupby(['Last', 'Sex']).sum().head()
Notice that `Year` is also summed up since each non-grouped column is passed into the aggregation function. To avoid this, we can select out the desired columns before calling `.groupby()`.
# When lines get long, you can wrap the entire expression in parentheses
# and insert newlines before each method call
letter_dist = (
baby[['Last', 'Sex', 'Count']]
.groupby(['Last', 'Sex'])
.sum()
)
letter_dist.head()
## Plotting
<hr>
`pandas` provides built-in plotting functionality for most basic plots, including bar charts, histograms, line charts, and scatterplots. To make a plot from a DataFrame, use the `.plot` attribute:
# We use the figsize option to make the plot larger
letter_dist.plot.barh(figsize=(10, 10))
Although this plot shows the distribution of letters and sexes, the male and female bars are difficult to tell apart. By looking at the `pandas` docs on plotting ([link](https://pandas.pydata.org/pandas-docs/stable/visualization.html)) we learn that `pandas` plots one group of bars for row column in the DataFrame, showing one differently colored bar for each column. This means that a pivoted version of the `letter_dist` table will have the right format.
letter_pivot = pd.pivot_table(
baby, index='Last', columns='Sex', values='Count', aggfunc='sum'
)
letter_pivot.head()
letter_pivot.plot.barh(figsize=(10, 10))
Notice that `pandas` conveniently generates a legend for us as well. However, this is still difficult to interpret. We plot the counts for each letter and sex which causes some bars to appear very long and others to be almost invisible. We should instead plot the proportion of male and female babies within each last letter.
total_for_each_letter = letter_pivot['F'] + letter_pivot['M']
letter_pivot['F prop'] = letter_pivot['F'] / total_for_each_letter
letter_pivot['M prop'] = letter_pivot['M'] / total_for_each_letter
letter_pivot.head()
(letter_pivot[['F prop', 'M prop']]
.sort_values('M prop') # Sorting orders the plotted bars
.plot.barh(figsize=(10, 10))
)
## Summary
<hr>
We can see that almost all first names that end in 'p' are male and names that end in 'a' are female! In general, the difference between bar lengths for many letters implies that we can often make a good guess to a person's sex if we just know the last letter of their first name.
We've learned to express the following operations in `pandas`:
| Operation | `pandas` |
| --------- | ------- |
| Applying a function elementwise | `series.apply(func)` |
| String manipulation | `series.str.func()` |
| Plotting | `df.plot.func()` | |
# Exceptions
<hr style="height:1px;border:none;color:#666;background-color:#666;" />
So far we have made programs that ask the user to enter a string, and
we also know how to convert that to an integer.
text = input("Enter something: ")
number = int(text)
print("Your number doubled:", number*2)
This code seems to work fine when a number is given as an input but doesn't work when the given input is a non-numeric type like a string or list
text = input("Enter something: ")
number = int(text)
print("Your number doubled:", number*2)
In this section we will look at how to fix that?
## What are exceptions?
In the previous example we got a ValueError (first line of our error message). ValueError is an example of a **exception** which gets raised whenever a program execution hits an unexpected condition. The interactive prompt will display an error message and keep going.
There are different types of exceptions like..
# index error
mylist = [1, 2, 5, 7]
mylist[4]
# type error
int(mylist)
**Some common error types include:**
- `SyntaxError`: Python can’t parse program
- `NameError`: local or global name not found
- `AttributeError`: attribute reference fails "
- `TypeError`: operand doesn’t have correct type
- `ValueError`: operand type okay, but value is illegal
- `IOError`: IO system reports malfunction (e.g. file not found)
If an exception occurs, the program will stop and we get an error message.
## Catching exceptions
If we need to try to do something and see if we get an exception, we
can use `try` and `except`. This is also known as **catching** the
exception.
try:
a = int(input("Give me a number:"))
b = int(input("Give me another number:"))
print(a/b)
print ("Okay")
except:
print("Bug in user input.")
print("Outside")
The except part doesn't run if the try part succeeds.
try:
a = int(input("Give me a number:"))
b = int(input("Give me another number:"))
print(a/b)
print ("Okay")
except:
print("Bug in user input.")
print("Outside")
Python tries to execute the code in the `try` block. If an error is encountered, we "catch" this in the `except` block (also called `try`/`catch` in other languages). |
# 5. Introduction to Numpy
<hr style="height:1px;border:none;color:#666;background-color:#666;" />

NumPy stands for "Numerical Python" and it is the standard Python library used for working with arrays (i.e., vectors & matrices), linear algerba, and other numerical computations. NumPy is written in C, making NumPy arrays faster and more memory efficient than Python lists or arrays, read more: ([link 1](https://www.datadiscuss.com/proof-that-numpy-is-much-faster-than-normal-python-array/), [link 2](https://www.jessicayung.com/numpy-arrays-memory-and-strides/), [link 3](https://www.labri.fr/perso/nrougier/from-python-to-numpy/)).
NumPy can be installed using `conda` (if not already):
```
conda install numpy
```
Knowing how to use Numpy is *essential* in domains such as machine learning, image analysis, and image processing.
## Contents
1. The ndarray
2. Indexing
3. Array math
4. Broadcasting
Let's start by importing numpy, which is commonly done as follows:
import numpy as np
## 2. NumPy Arrays
<hr>
### What are Arrays?
Arrays are "n-dimensional" data structures that can contain all the basic Python data types, e.g., floats, integers, strings etc, but work best with numeric data. `ndarrays` (which stands for *n*-*d*imensional array) are homogenous, which means that items in the array should be of the same type. ndarrays are also compatible with numpy's vast collection of in-built functions!

Source: [Medium.com](https://medium.com/hackernoon/10-machine-learning-data-science-and-deep-learning-courses-for-programmers-7edc56078cde)
### Python lists vs. numpy arrays
Basically, numpy arrays are a lot like Python lists. The major difference, however, is that *numpy arrays may contain only a single data-type*, while Python lists may contain different data-types within the same list.
Let check this out:
# Python lists may contain mixed data-types: an integer, a float, a string, a list
python_list = [1, 2.5, "whatever", [3, 4, 5]]
for value in python_list:
print(f"{str(value)} is a: {type(value)}")
Unlike Python lists, numpy only allows entries of the same data-type. In fact, if you try to make a numpy array with different data-types, numpy will force the entries into the same data-type (in a smart way), as is shown in the example below:
# Importantly, you often specify your arrays as Python lists first, and then convert them to numpy
to_convert_to_numpy = [1, 2, 3.5] # specify python list ...
numpy_array = np.array(to_convert_to_numpy) # ... and convert ('cast') it to numpy
for entry in numpy_array:
print(entry)
print(f'this is a: {type(entry)} \n')
As you can see, Numpy converted our original list (to_convert_to_numpy), which contained both integers and floats, to an array with only floats! You might think that such a data structure that only allows one single data type is not ideal. However, the very fact that it only contains a single data-type makes operations on numpy arrays extremely fast. For example, loops over numpy arrays are often way faster than loops over python lists. This is because, internally, Python has to check the data-type of each loop entry before doing something with that entry. Because numpy arrays one allow a single data-type, it only has to check for the entries' data type **once**. If you imagine looping over an array or list of length 100,000, you probably understand that the numpy loop is way faster.
### Creating numpy arrays
As shown an earlier example, numpy arrays can be created as follows:
1. Define a Python list, e.g. `my_list = [0, 1, 2]`
2. Convert the list to a numpy array, e.g. `numpy_array = np.array(my_list)`
Importantly, a simple Python list will be converted to a 1D numpy array, but a nested Python list will be converted to a 2D (or even higher-dimensional array). Nesting is simply combining different lists, separated by commans, as is shown here:
my_list = [1, 2, 3]
my_array = np.array(my_list)
print("A 1D (or 'flat') array:")
print(my_array, '\n')
my_nested_list = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
my_2D_array = np.array(my_nested_list)
print("A 2D array:")
print(my_2D_array)
<div class='alert alert-warning'>
<b>ToDo</b>: Create the following 1D array:
\begin{align}
\begin{bmatrix}
5 & 3 & 2 & 8 & 9
\end{bmatrix}
\end{align}
and store it in a variable named <tt>vec</tt>.
</div>
# YOUR CODE HERE
<div class='alert alert-warning'>
<b>ToDo</b>:
Create the following matrix (2D array):
\begin{align}
\begin{bmatrix}
5 & 2 & 8 \\
8 & 2 & 1 \\
4 & 4 & 4 \\
1 & 2 & 3
\end{bmatrix}
\end{align}
and store it in a variable named <tt>arr_2d</tt>. Hint: start by creating a nested python list (like we did with the <tt>my_nested_list</tt> variable) and then convert it to numpy.
</div>
# YOUR CODE HERE
As you can imagine, creating numpy arrays from nested lists becomes cumbersome if you want to create (large) arrays with more than 2 dimensions. There are, fortunately, a lot of other ways to create ('initialize') large, high-dimensional numpy arrays. One often-used method is to create an array with zeros using the numpy function `np.zeros`. This function takes one (mandatory) argument, which is a tuple with the dimensions of your desired array:
my_desired_dimensions = (2, 5) # suppose I want to create a matrix with zeros of size 2 by 5
my_array = np.zeros(my_desired_dimensions)
print(my_array)
Using arrays with zeros is often used in what is called 'pre-allocation', in which we create an 'empty' array with only zeros and for example, 'fill' that array in a loop. Below, we can see an example where we pre-allocate an array with 5 zeros, and fill that in a for-loop with the squares of 1 - 5.
my_array = np.zeros(5)
print('Original zeros-array')
print(my_array)
for i in range(5): # notice the range function here! This loop now iterates over [0, 1, 2, 3, 4]
number_to_calculate_the_square_of = i + 1
my_array[i] = number_to_calculate_the_square_of ** 2
print('\nFilled array')
print(my_array)
In addition to `np.zeros`, you can create numpy arrays using other functions, like `np.ones` and `random` from the `np.random` module:
ones = np.ones((5, 10)) # create an array with ones
print(ones, '\n')
rndom = np.random.random((5, 10)) # Create an array filled with random values (0 - 1 uniform)
print(rndom)
## Numpy indexing
<hr>
Indexing (extracting a single value of an array) and slicing (extracting multiple values - a subset - from an array) of numpy arrays is largely the same as with regular Python lists. Let's check out a couple of examples of a 1D array:
my_array = np.arange(10, 21) # numpy equivalent of list(range(10, 21))
print('Full array:')
print(my_array, '\n')
print("Index the first element:")
print(my_array[0])
print("Index the second-to-last element:")
print(my_array[-2])
print("Slice from 5 until (not including!) 8")
print(my_array[5:8])
print("Slice from beginning until 4")
print(my_array[:4])
Setting values in numpy arrays works the same way as lists:
my_array = np.arange(10, 21)
my_array[0] = 10000
print(my_array)
my_array[5:7] = 0
print(my_array)
### Multidimensional indexing
Often, instead of working on and indexing 1D array, we'll work with multi-dimensional (>1D) arrays. Indexing multi-dimensional arrays is, again, quite similar to indexing and slicing list.
Like indexing Python lists, indexing multidimensional numpy arrays is done with square brackets `[]`, in which you can put as many comma-delimited numbers as there are dimensions in your array.
For example, suppose you have a 2D array of shape $3 \times 3$ and you want to index the value in the first row and first column. You would do this as follows:
my_array = np.zeros((3, 3)) # 3 by 3 array with zeros
indexed_value = my_array[0, 0]
print("Value of first row and first column: %.1f" % indexed_value)
We can also extract sub-arrays using slicing/indexing. An important construct here is that we use a single colon `:` to select all values from a particular dimension. For example, if we want to select all column-values (second dimension) from only the first row (first dimension), do this:
```
some_2d_arr[0, :]
```
Let's look at an examples below:
my_array = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(my_array, '\n')
all_column_values_from_first_row = my_array[0, :]
print('First row')
print(all_column_values_from_first_row, '\n')
all_row_values_from_first_col = my_array[:, 0]
print('First column')
print(all_row_values_from_first_col)
## Methods vs. functions
<hr>
In the previous tutorials, we learned that, in addition to functions, 'methods' exist that are like functions of an object. We've seen examples of list methods, e.g. `my_list.append(1)`, and string methods, e.g. `my_string.replace('a', 'b')`.
Like lists and strings, numpy arrays have a lot of convenient methods that you can call (like the `astype` method). Again, this is just like a function, but then applied to itself. Often, numpy provides both a function and method for simple operations.
Let's look at an example:
my_array = np.arange(10) # creates a numpy array from 0 until (excluding!) 10
print(my_array, '\n')
mean_array = np.mean(my_array)
print(f'The mean of the array is: {mean_array}')
mean_array2 = my_array.mean()
print(f'The mean of the array (computed by its corresponding method) is: {mean_array2}')
print('Is the results from the numpy function the same as '
f'the corresponding method? Answer: {str(mean_array == mean_array2)}')
If there is both a function and a method for the operation we want to apply to the array, it really doesn't matter what we choose! Let's look at some more (often used) methods of numpy ndarrays:
my_array = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
std_my_array = my_array.std() # same as np.std(array)
print(f"Standard deviation of my_array: {std_my_array}", '\n')
transpose_my_array = my_array.T # same as np.transpose(array)
print(f"Transpose of my_array:\n{transpose_my_array}", '\n')
min_my_array = my_array.min() # same as np.min(array)
print(f"Minimum of my_array: {my_array.min()}", '\n')
max_my_array = my_array.max() # same as np.max(array)
print(f"Maximum of my_array: {max_my_array}", '\n')
sum_my_array = my_array.sum() # same as np.sum(array)
print(f"Sum of my_array: {sum_my_array}", '\n')
Importantly, a method may or may not take arguments (input).
If no arguments are given, it just looks like "object.method()", i.e. two enclosing brackets with nothing in between.
However, a method may take one or more arguments (like the my_list.append(1) method)!
This argument may be named or unnamed - doesn't matter. An example:
my_array2 = np.random.random((3, 3))
print('Original array:')
print(my_array2, '\n')
print('Use the round() method with the argument 3:')
print(my_array2.round(3), '\n')
print('Use the round() method with the named argument 5:')
print(my_array2.round(decimals=5), '\n')
In addition to the methods listed above, you'll probably see the following methods a lot in the code of others.
Reshaping arrays:
my_array = np.arange(10)
print(my_array.reshape((5, 2))) # reshape to desired shape
Ravel ("flatten") an array:
temporary = my_array.reshape((5, 2))
print("Initial shape: %s" % (temporary.shape,))
print(temporary.ravel()) # unroll multi-dimensional array to single 1D array
print("Shape after ravel(): %s" % (temporary.ravel().shape,)) |
import time
import turtle
shelly = turtle.Turtle()
turtle.bgcolor('red')
for i in range(36):
shelly.circle(100)
shelly.right(10)
shelly.penup()
shelly.color('white')
for n in range(36):
shelly.forward(220)
shelly.pendown()
shelly.circle(5)
shelly.penup()
shelly.backward(220)
shelly.right(10)
shelly.hideturtle()
while True:
a = input('Press "e" to exit.')
if a == 'e':
break |
total = input('What is the total on the bill?: ')
tip = input('What % tip would you like to give?: ')
people = input('How many people are sharing the bill?: ')
people = int(people)
tip = int(tip)
total = int(total)
tip_amount = total * tip / 100
print('Tip amount = ', tip_amount)
total_bill = tip_amount + total
print('Total bill = ', total_bill)
print('---------------------------------------')
print('Tip amount per person: ', tip_amount / people)
print('Total amount per person: ', total_bill / people) |
##### Inputs
# name = input("What's your name? ")
# ans = "Hello " + name.title() + ". "
# print(ans)
# # need to wrap in int() or float() if you want a number
# num = int(float(input("Give a number: ")))
# print(ans * num)
print("===================================")
##### Their Sample
# names = input("Enter names separated by commas: ").title().split(",")
# assignments = input("Enter assignment counts separated by commas (integer): ").split(",")
# grades = input("Enter grades separated by commas (integer): ").split(",")
# message = "Hi {},\n\nThis is a reminder that you have {} assignments left to \
# submit before you can graduate. You're current grade is {} and can increase \
# to {} if you submit all assignments before the due date.\n\n"
# for name, assignment, grade in zip(names, assignments, grades):
# print(message.format(name, assignment, grade, int(grade) + int(assignment)*2))
print("===================================")
##### Error handling with Try/Except
# try:
# x = int(input("Enter your lucky integer: "))
# except (ValueError, KeyboardInterrupt): # can have more than one exception in a line
# print("Need a valid integer!")
# except KeyboardInterrupt: # or different line
# print("Why are you leaving?!")
# else:
# print("Your lucky number is: ", x)
# finally:
# # finally will run in any condition of the try statement (such as ctrl+C to exit program)
# # useful if you are calling packages and need to close out some resource
# print("Attempts have been made.")
print("===================================")
##### Sample Problem
def party_planner(cookies, people):
leftovers = None
num_each = None
# try/except practice, make sure no ZeroDivisionError occurs.
try:
num_each = cookies // people
leftovers = cookies % people
except Exception as e: ## can be generic "Exception" and print out error message as "e"
print("Must be greater than 0 people! \nError occurred: {}".format(e))
return(num_each, leftovers)
# The main code block is below; do not edit this
lets_party = 'y'
while lets_party == 'y':
cookies = int(input("How many cookies are you baking? "))
people = int(input("How many people are attending? "))
cookies_each, leftovers = party_planner(cookies, people)
if cookies_each: # if cookies_each is not None
message = "\nLet's party! We'll have {} people attending, they'll each get to eat {} cookies, and we'll have {} left over."
print(message.format(people, cookies_each, leftovers))
lets_party = input("\nWould you like to party more? (y or n) ")
print("===================================")
##### Sample Problem 2
# initiate empty list to hold user input and sum value of zero
user_list = []
list_sum = 0
# seek user input for ten numbers
for i in range(10):
userInput = int(input("Enter any 2-digit number: "))
# check to see if number is even and if yes, add to list_sum
# print incorrect value warning when ValueError exception occurs
try:
number = userInput
user_list.append(number)
if number % 2 == 0:
list_sum += number
except ValueError:
print("Incorrect value. That's not an int!")
print("user_list: {}".format(user_list))
print("The sum of the even numbers in user_list is: {}.".format(list_sum)) |
from Citizen import Citizen
from TouristTypes import Tourist_Types
touristTypes = Tourist_Types()
print("What characteristics does the citizen have?")
ans = input("Hair (bald, brown, red, blue, green):\n")
hair = ans.lower()
ans = input("Skin (white, beige, red, blue, turqoise):\n")
skin = ans.lower()
ans = input("Eyes (black, blue, yellow, green):\n")
eyes = ans.lower()
ans = input("Headshape(square, round, triangular):\n")
headshape = ans.lower()
ans = input("Height(short, medium, tall):\n")
height = ans.lower()
ans = input("Language spoken(lunar, terrestric, mercuristic, intergalactic, ringlish): ")
language = ans.lower()
randomCitizen = Citizen(hair, skin, eyes, headshape, height, language)
bestComplianceValue = 0
bestComplianceType = None
for touristType in touristTypes.touristTypes:
complianceDegree = touristType.compliance_degree(randomCitizen)
if complianceDegree > bestComplianceValue:
bestComplianceValue = complianceDegree
bestComplianceType = touristType
print("The citizen is " + bestComplianceType.return_type())
|
MIN_HEIGHT= 6
BOARD_WIDTH = 7
BOARD_HEIGHT= 6
class Disc:
def __init__(self, x, y, color):
self._x = x
self._y = y
self._color = color
def getX(self):
'''Get x position of a disc'''
return self._x
def getY(self):
'''Get y position of a disc'''
return self._y
def getColor(self):
'''Get color of a disc'''
return self._color
def __str__(self):
return 'Disc: x=' + str(self._x) + ', y=' + str(self._y) + ', color='\
+ self._color
def __repr__(self):
return 'Disc(' + str(self._x) + ', ' + str(self._y) + ', '\
+ self._color + ')'
class Game:
def __init__(self):
pass
def nextTurn(self):
'''Change the current player'''
if self._current_player == 'red':
self._current_player = 'yellow'
else:
self._current_player = 'red'
self._too_high = False
def southConnect(self, new_disc, distance):
'''Check if there's a disc of the same color at given distance to the
south'''
for old_disc in self._discs:
if new_disc.getColor() == old_disc.getColor():
if new_disc.getX() == old_disc.getX() \
and new_disc.getY()+distance == old_disc.getY():
return True
def westConnect(self, new_disc, distance):
'''Check if there's a disc of the same color at given distance to the
west'''
for old_disc in self._discs:
if new_disc.getColor() == old_disc.getColor():
if new_disc.getY() == old_disc.getY() \
and new_disc.getX()-distance == old_disc.getX():
return True
def eastConnect(self, new_disc, distance):
'''Check if there's a disc of the same color at given distance to the
east'''
for old_disc in self._discs:
if new_disc.getColor() == old_disc.getColor():
if new_disc.getY() == old_disc.getY() \
and new_disc.getX()+distance == old_disc.getX():
return True
def northWestConnect(self, new_disc, distance):
'''Check if there's a disc of the same color at given distance to the
north-west'''
for old_disc in self._discs:
if new_disc.getColor() == old_disc.getColor():
if new_disc.getY()+distance == old_disc.getY() \
and new_disc.getX()+distance == old_disc.getX():
return True
def northEastConnect(self, new_disc, distance):
'''Check if there's a disc of the same color at given distance to the
nort-east'''
for old_disc in self._discs:
if new_disc.getColor() == old_disc.getColor():
if new_disc.getY()+distance == old_disc.getY() \
and new_disc.getX()-distance == old_disc.getX():
return True
# There's no need to check for any other direction because the disc rise
# upward
def isTied(self):
'''Check if the board is filled with discs which mean tie'''
if len(self._discs) == self._height * self._width:
return True
else:
return False
def isWon(self):
pass
def getBottomFreeHoleInColumn(self, column):
'''Get the y position of the first free hole, counting up, in given
column'''
lowest = self._height
for disc in self._discs:
if disc.getX() == column:
if disc.getY() <= lowest:
lowest = disc.getY()-1
return lowest
def addDisc(self, column):
'''Put a disc in given column'''
row = self.getBottomFreeHoleInColumn(column)
if row == 0:
self._too_high = True
return
else:
self._discs.append(Disc(column, row, self._current_player))
self.nextTurn()
def getCurrentPlayer(self):
'''Get the color of the player whose turn is now to play'''
return self._current_player
def tooHigh(self):
'''Check if some player tried to add a disc to a full column'''
return self._too_high
def getDiscs(self):
'''Return a list of all discs objects on the board'''
return self._discs
def whoWon(self):
pass
def getHeight(self):
'''Return the height of a board in this game'''
return self._height
def getWidth(self):
'''Return the width of a board in this game'''
return self._width
class fourInARow(Game):
def __init__(self):
self._discs = []
self._current_player = 'red'
self._too_high = False
self._width = 7
self._height = 6
def isWon(self):
'''Check for every disc if it has 3 connecting disc of the same color
in any direction which means a win for the player having this color'''
for disc in self._discs:
if self.southConnect(disc, 1):
if self.southConnect(disc, 2):
if self.southConnect(disc, 3):
return True
if self.westConnect(disc, 1):
if self.westConnect(disc, 2):
if self.westConnect(disc, 3):
return True
if self.eastConnect(disc, 1):
if self.eastConnect(disc, 2):
if self.eastConnect(disc, 3):
return True
if self.northWestConnect(disc, 1):
if self.northWestConnect(disc, 2):
if self.northWestConnect(disc, 3):
return True
if self.northEastConnect(disc, 1):
if self.northEastConnect(disc, 2):
if self.northEastConnect(disc, 3):
return True
return False
class fiveInARow(Game):
def __init__(self):
self._discs = [Disc(0, 1, 'red'),
Disc(0, 2, 'yellow'),
Disc(0, 3, 'red'),
Disc(0, 4, 'yellow'),
Disc(0, 5, 'red'),
Disc(0, 6, 'yellow'),
Disc(8, 1, 'yellow'),
Disc(8, 2, 'red'),
Disc(8, 3, 'yellow'),
Disc(8, 4, 'red'),
Disc(8, 5, 'yellow'),
Disc(8, 6, 'red')]
self._current_player = 'red'
self._too_high = False
self._width = 9
self._height = 6
def isWon(self):
'''Check for every disc if it has 4 connecting disc of the same color
in any direction which means a win for the player having this color'''
for disc in self._discs:
if self.southConnect(disc, 1):
if self.southConnect(disc, 2):
if self.southConnect(disc, 3):
if self.southConnect(disc, 4):
return True
if self.westConnect(disc, 1):
if self.westConnect(disc, 2):
if self.westConnect(disc, 3):
if self.westConnect(disc, 4):
return True
if self.eastConnect(disc, 1):
if self.eastConnect(disc, 2):
if self.eastConnect(disc, 3):
if self.eastConnect(disc, 4):
return True
if self.northWestConnect(disc, 1):
if self.northWestConnect(disc, 2):
if self.northWestConnect(disc, 3):
if self.northWestConnect(disc, 4):
return True
if self.northEastConnect(disc, 1):
if self.northEastConnect(disc, 2):
if self.northEastConnect(disc, 3):
if self.northEastConnect(disc, 4):
return True
return False
|
import sqlite3
# Definition that create database and place data into tables
def create_database():
#connection with database
conn = sqlite3.connect('bear.db')
#create tables
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS clients;")
cur.execute("""
CREATE TABLE IF NOT EXISTS clients (
id INTEGER PRIMARY KEY ASC,
name varchar(250) NOT NULL,
surname varchar(250) NOT NULL,
city varchar(250) NOT NULL,
post_code varchar(250) NOT NULL,
street_home_number varchar(250) NOT NULL,
pesel BIGINT NOT NULL
)""")
cur.execute("DROP TABLE IF EXISTS products;")
cur.execute("""
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY ASC,
product_name varchar(250) NOT NULL,
price varchar(250) NOT NULL,
in_magazine varchar(250) NOT NULL
)""")
cur.execute("DROP TABLE IF EXISTS orders;")
cur.execute("""
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY ASC,
client_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
FOREIGN KEY(client_id) REFERENCES clients(id)
FOREIGN KEY(product_id) REFERENCES products(id)
)""")
#tuple containing data about products
clients_data = (
(None, 'Tomasz', 'Nowak', 'Poznań', '60-320', 'Bukowska 1/2', '53515564843'),
(None, 'Alfred', 'Szymczak', 'Gorzów Wlkp.', '66-400', 'Stilonowa 13/8', '74300625537'),
(None, 'Jan', 'Kowalski', 'Warszawa', '01-020', 'Marszałowska 121/12', '38300020761')
)
#insert into table clients
cur.executemany('INSERT INTO clients VALUES(?, ?, ?, ?, ?, ?, ?);', clients_data)
#tuple containing data about products
products_data = (
(None, 'Komputer', '2099.99', '2'),
(None, 'Kabel HDMI', '49.99', '8'),
(None, 'Monitor Full HD', '599.99', '4'),
(None, 'Klawiatura Logitech', '99.99', '2'),
(None, 'Trackball', '156.99', '1'),
(None, 'Gra', '89.99', '7')
)
#insert into table products
cur.executemany('INSERT INTO products VALUES(?,?,?,?)', products_data)
#tuple containing data about orders
orders_data = (
(None, '1', '1'),
(None, '1', '2'),
(None, '1', '3'),
(None, '2', '4'),
(None, '3', '1'),
)
#insert into table orders
cur.executemany('INSERT INTO orders VALUES(?,?,?)', orders_data)
#commit data to database
conn.commit()
conn.close()
#Function to read data from products table
def read_products():
#connection with database
conn = sqlite3.connect('bear.db')
#select data from table
cur = conn.cursor()
cur.execute("SELECT * from products;")
products_data = cur.fetchall()
'''
for x in products_data:
print('\n')
print('id: ', x[0], )
print('product_name: ', x[1], )
print('price: ', x[2], )
print('in_magazine: ', x[3], )
'''
conn.close()
return products_data
#Function to read data from orders table
def read_orders():
#connection with database
conn = sqlite3.connect('bear.db')
# select data from table
cur = conn.cursor()
cur.execute("SELECT orders.id, clients.name, clients.surname, clients.city, clients.post_code, clients.street_home_number, products.product_name, products.price from orders INNER JOIN clients ON orders.client_id = clients.id INNER JOIN products ON orders.product_id = products.id;")
orders_data = cur.fetchall()
'''
for x in orders_data:
print('\n')
print('id_zamówienia: ', x[0], )
print('Imię: ', x[1], )
print('Nazwisko: ', x[2], )
print('Miasto: ', x[3], )
print('Kod pocztowy: ', x[4], )
print('Ulica i nr domu: ', x[5], )
print('Nazwa produktu: ', x[6], )
print('Cena: ', x[7], )
'''
conn.close()
return orders_data
#Fucntion thanks to which user can add products to table products.
def add_products(name, price, quantity):
# connection with database
conn = sqlite3.connect('bear.db')
name = str(name)
price = str(price)
quantity = str(quantity)
cur = conn.cursor()
# tuple containing data about products
products_data = [
(None, name, price, quantity)
]
# insert into table products
cur.executemany('INSERT INTO products VALUES(?,?,?,?)', products_data)
# commit data to database
conn.commit()
conn.close()
def edit_existing(id, name, price, quantity):
# connection with database
conn = sqlite3.connect('bear.db')
id = int(id)
name = str(name)
price = str(price)
quantity = str(quantity)
products_data = [(name, price, quantity, id)]
cur = conn.cursor()
# insert into table products
cur.executemany("""UPDATE products SET product_name = ?, price = ?, in_magazine = ? WHERE id = ?""", products_data)
# commit data to database
conn.commit()
conn.close()
def delete_existing(id):
# connection with database
conn = sqlite3.connect('bear.db')
id = int(id)
products_data = [(id)]
cur = conn.cursor()
# insert into table products
cur.execute('DELETE FROM products WHERE id = ?', products_data)
# commit data to database
conn.commit()
conn.close()
create_database()
|
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
# defining a blank mask to start with
mask = np.zeros_like(img)
# defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
# filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
# returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def draw_lines(img, lines, color=[255, 0, 0], thickness=2):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that shown in P1_example.mp4).
Think about things like separating line segments by their
slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
line vs. the right line. Then, you can average the position of each of
the lines and extrapolate to the top and bottom of the lane.
This function draws `lines` with `color` and `thickness`.
Lines are drawn on the image inplace (mutates the image).
If you want to make the lines semi-transparent, think about combining
this function with the weighted_img() function below
"""
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn.
"""
lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len,
maxLineGap=max_line_gap)
line_img = np.zeros((*img.shape, 3), dtype=np.uint8)
draw_lines(line_img, lines)
return line_img
# Python 3 has support for cool math symbols.
def weighted_img(img, initial_img, α=0.8, β=1., λ=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * α + img * β + λ
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, α, img, β, λ)
### My code starts here
### helper wrappers around cv2 methods
def read_image_from_path(img_file_path):
return mpimg.imread(img_file_path)
def write_image_to_path(img, target_file_path):
mpimg.imsave(target_file_path, img)
def get_hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns detected hough lines
"""
return cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len,
maxLineGap=max_line_gap)
### Code to fit a line using segments
from scipy.optimize import curve_fit
def linear_fit_func(x, m, b):
return m * x + b
def fit_line(points):
x = [p[0] for p in points]
y = [p[1] for p in points]
params = curve_fit(linear_fit_func, x, y)
[m, b] = params[0]
return [m, b]
def fit_line_from_segments(segments):
points = []
for line in segments:
for x1, y1, x2, y2 in line:
points.append([x1, y1])
points.append([x2, y2])
return fit_line(points)
### computing mask to apply to image
def get_polygon_mask(shape):
maxY, maxX = shape
leftBottom = (int(0.1 * maxX), maxY)
leftTop = (int(0.45 * maxX), int(0.6 * maxY))
rightTop = (int(0.55 * maxX), int(0.6 * maxY))
rightBottom = (int(0.9 * maxX), maxY)
return np.array([[leftBottom, leftTop, rightTop, rightBottom]], dtype=np.int32)
### color mask to extract white and yellow lines from image
def apply_white_yellow_hsv_mask(image):
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# define range of white color in HSV
lower_white = np.array([0, 0, 220])
# lower_white = np.array([0, 0, 80])
upper_white = np.array([130, 130, 255])
# Threshold the HSV image to get only white colors
mask_white = cv2.inRange(hsv, lower_white, upper_white)
# define range of yellow color in HSV
lower_yellow = np.array([20, 80, 200])
upper_yellow = np.array([120, 200, 255])
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
# this didn't work out well
# define range of white color in shadow in HSV
lower_white_shadow = np.array([80, 0, 80])
upper_white_shadow = np.array([180, 50, 200])
mask_white_shadow = cv2.inRange(hsv, lower_white_shadow, upper_white_shadow)
mask = mask_yellow | mask_white
# Bitwise-AND mask and original image
return cv2.bitwise_and(image, image, mask=mask)
def gray_and_normalize_hist(img):
# tried equalizing histogram over gray image for challenge
# this gave worse results than color mask
gray = grayscale(img)
return cv2.equalizeHist(gray)
### split segments to left and right lanes
### filter bad segments
def filter_lane_segments_and_split(lines, image_shape):
"""
This method takes in hough lines identified using cvs.HoughLinesP method
Computes slope for each segment
For both left and right lane segments, we have a range of acceptable slopes
Split segments into left and right lane segments
When slope doesnt fall in these ranges, filter out the line
"""
left_lane_slope_limits = [0.5, 2.5]
right_lane_slope_limits = [-2.5, -0.5]
midx = int(image_shape[1] / 2)
left_lane_lines = []
right_lane_lines = []
for line in lines:
for x1, y1, x2, y2 in line:
slope = (y1 - y2) / (x2 - x1) # y goes 0 - N top down
if slope > left_lane_slope_limits[0] and slope < left_lane_slope_limits[1] and x1 <= midx and x2 <= midx:
left_lane_lines.append(line)
elif slope > right_lane_slope_limits[0] and slope < right_lane_slope_limits[1] and x1 > midx and x2 > midx:
right_lane_lines.append(line)
return [left_lane_lines, right_lane_lines]
def extrapolate_lane_segments_and_merge(left_lane_lines, right_lane_lines, shape_of_original_image):
"""
method to merge different segments of left and right lanes
step 1: curve fit all left lane points to get best line that describes all left lane segments.
this gives us (m_left, b_left)
step 2: curve fit all right lane points to get best line that describes all right lane segments.
this gives us (m_right, b_right)
step 4: we have bottom of image (ybot) and middle (ymid) (using mask). get xbot, xmid
- by using (m_left and b_left) for left lane
- by using (m_right and b_right) for left lane
Now, we have 2 points that represent left lane and 2 points represent right lane
step 5: return 2 lines computed in step 4
"""
[m_left, b_left] = fit_line_from_segments(left_lane_lines)
[m_right, b_right] = fit_line_from_segments(right_lane_lines)
maxY = shape_of_original_image[0]
bottom_of_mask = maxY
top_of_mask = int(0.6 * maxY)
left_lane_bottom = [int((bottom_of_mask - b_left) / m_left), bottom_of_mask]
left_lane_top = [int((top_of_mask - b_left) / m_left), top_of_mask]
right_lane_bottom = [int((bottom_of_mask - b_right) / m_right), bottom_of_mask]
right_lane_top = [int((top_of_mask - b_right) / m_right), top_of_mask]
out_lines = np.ndarray(shape=(2, 1, 4), dtype=np.int32)
out_lines[0] = (left_lane_bottom[0], left_lane_bottom[1], left_lane_top[0], left_lane_top[1])
out_lines[1] = (right_lane_bottom[0], right_lane_bottom[1], right_lane_top[0], right_lane_top[1])
return out_lines
def get_filtered_hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
lines = get_hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap)
return filter_lane_segments_and_split(lines, img.shape)
def identify_lane_segments_filter_by_slope_and_split(img, convert_to_hsv_or_gray_scale_function):
# convert to gray scale
gray = convert_to_hsv_or_gray_scale_function(img)
# canny edge detection
# blur image
blurred_gray = gaussian_blur(gray, 5)
# run canny
lines_in_img = canny(blurred_gray, 50, 150)
# compute region mask
mask_vertices = get_polygon_mask(lines_in_img.shape)
# apply mask
lines_in_roi = region_of_interest(lines_in_img, mask_vertices)
# hough transform
rho = 1
theta = np.pi / 180
threshold = 15
min_line_length = 10
max_line_gap = 5
lines_segments = get_hough_lines(lines_in_roi, rho, theta, threshold, min_line_length, max_line_gap)
# filter lane segments and split into left, right lane segments
return filter_lane_segments_and_split(lines_segments, img.shape)
### main function to compute lanes
def get_lanes(img):
"""
1. Use color mask first to identify lane segments.
2. If that doesnt return left and right lane segments like expected, use gray scale transformation
and extract left, right lane segments
3. extrapolate [left, right] lane segments and build lane geometry
"""
lane_segments = identify_lane_segments_filter_by_slope_and_split(img, apply_white_yellow_hsv_mask)
if (not lane_segments[0]) or (not lane_segments[1]):
# if either left or right segments are empty
lane_segments = identify_lane_segments_filter_by_slope_and_split(img, grayscale)
merged_lane_lines = extrapolate_lane_segments_and_merge(lane_segments[0], lane_segments[1], img.shape)
return merged_lane_lines
### draw lane geometry layer as an image and return that
def generate_lane_lines_image(img, merged_lane_lines):
line_img = np.zeros((*img[:, :, 0].shape, 3), dtype=np.uint8)
draw_lines(line_img, merged_lane_lines, thickness=5)
return line_img
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
def process_image(image):
# NOTE: The output you return should be a color image (3 channel) for processing video below
# TODO: put your pipeline here,
# you should return the final output (image with lines are drawn on lanes)
merged_lane_lines = get_lanes(image)
lane_lines_layer = generate_lane_lines_image(image, merged_lane_lines)
img_with_lanes = weighted_img(lane_lines_layer, image)
return img_with_lanes
white_output = 'white.mp4'
clip1 = VideoFileClip("solidWhiteRight.mp4")
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
white_clip.write_videofile(white_output, audio=False)
yellow_output = 'yellow.mp4'
clip2 = VideoFileClip('solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
yellow_clip.write_videofile(yellow_output, audio=False)
challenge_output = 'extra.mp4'
clip2 = VideoFileClip('challenge.mp4')
challenge_clip = clip2.fl_image(process_image)
challenge_clip.write_videofile(challenge_output, audio=False)
# import os
# for f in os.listdir("challenge_debug/frames/"):
# img = read_image_from_path("challenge_debug/frames/" + f)
# img_with_lanes = process_image(img)
# write_image_to_path(img_with_lanes, "challenge_debug/output/" + f)
#
#
# one_frame = read_image_from_path("challenge_debug/frames/output_0176.jpg")
# # masked_frame = apply_white_yellow_hsv_mask(one_frame)
# gray = grayscale(one_frame)
# plt.figure(1)
# plt.imshow(gray, cmap='gray')
#
# eqim = cv2.equalizeHist(gray)
# plt.figure(2)
# plt.imshow(eqim, cmap='gray')
# plt.show() |
nomes = []
for i in range(5):
nomes.append(input("Digite o nome: "))
print("\n Lista de convidados \n")
for i in range(5):
print("Convidado número {}: {} ".format((i+1),nomes[i]))
|
#==========
# Comparison of booleans
print(True == False)
# Comparison of integers
print((-5 * 15) != 75)
# Comparison of strings
print("pyscript" == "PyScript")
# Compare a boolean with an integer
print(True == 1)
#==========
# Comparison of integers
x = -3 * 6
print(x >= -10)
# Comparison of strings
y = "test"
print("test" <= y)
# Comparison of booleans
print(True > False)
#==========
# Define variables
my_kitchen = 18.0
your_kitchen = 14.0
# my_kitchen bigger than 10 and smaller than 18?
print(my_kitchen > 10 and my_kitchen < 18)
# my_kitchen smaller than 14 or bigger than 17?
print(my_kitchen < 14 or my_kitchen > 17)
# Double my_kitchen smaller than triple your_kitchen?
print((my_kitchen * 2) < (your_kitchen * 3))
#==========
# Define variables
room = "kit"
area = 14.0
# if statement for room
if room == "kit" :
print("looking around in the kitchen.")
# if statement for area
if area > 15:
print("big place!")
#==========
# Define variables
room = "kit"
area = 14.0
# if-else construct for room
if room == "kit" :
print("looking around in the kitchen.")
else :
print("looking around elsewhere.")
# if-else construct for area
if area > 15 :
print("big place!")
else :
print("pretty small.")
#==========
# Define variables
room = "bed"
area = 14.0
# if-elif-else construct for room
if room == "kit" :
print("looking around in the kitchen.")
elif room == "bed":
print("looking around in the bedroom.")
else :
print("looking around elsewhere.")
# if-elif-else construct for area
if area > 15 :
print("big place!")
elif area > 10 :
print("medium size, nice!")
else :
print("pretty small.")
#==========
#==========
#========== |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 4 19:46:05 2018
@author: Daniel Maher
"""
"""
N-gram Building
All algorithms for parsing text files, web pages, etc. and building n-gram tables will be located here
"""
from bs4 import BeautifulSoup
import nltk, codecs
from nltk import word_tokenize
from urllib import request
import re
def get_all_text_in_folder(folder_path):
"""
Returns all rawtext in text files within the given folder
---------------------------
Input: folder_path <string> - the path of the folder containing text files
Output: rawtext <string> - the raw text of all text files in folder
"""
import os
import glob
file_names = folder_path + "*.txt"
files = glob.glob(file_names)
rawtext = ""
for file in files:
with codecs.open(file, 'r', 'utf8') as f:
rawtext += f.read()
return rawtext
def strip_html_tokenize_and_postag(url):
"""
Strips html tags from the input webpage url, then tokenizes the remaining
raw text into a list of part-of-speech tagged tokens in order of occurrence
--------------------------------------------------------------------
Inputs:
url list of <string> : the url address of the webpage to be stripped of html tags
Outputs:
tokens <list of strings> : tokens of the raw text data contained at the url
"""
# get html page text from <url>
html = request.urlopen(url).read().decode('utf8')
# parse the html for raw text using BeautifulSoup
rawtext = BeautifulSoup(html, 'html.parser').get_text()
tokens = word_tokenize(rawtext)
tokens = nltk.pos_tag(word_tokenize(rawtext))
return tokens
def open_file_tokenize_and_postag(filenames):
"""
takes list of file names
"""
all_tokens = []
for filename in filenames:
with codecs.open(filename, 'r', 'utf8') as myfile:
rawtext = myfile.read()
tokens = nltk.pos_tag(word_tokenize(rawtext))
all_tokens += tokens
return all_tokens
def generate_booksummary_tokens(total=16600):
rawtext = ""
path = "./Book_Summaries/booksummaries.txt"
with codecs.open(path, 'r', 'utf8') as myfile:
i = 0
for line in myfile:
if i < total:
summary_text = line.split("\t")
rawtext += summary_text[-1]
else:
break
i += 1
myfile.close()
rawtext = re.sub("[()]", "", rawtext)
tokens = nltk.pos_tag(word_tokenize(rawtext))
return tokens, rawtext
def build_ngram_tables(tokens, n_grams=2):
"""
Takes a list of part-of-speech tagged tokens and produces 2 di
--------------------------------------------------------------------
Inputs:
tokens <list of tuples> : a list of pairs of strings of the form (token, part-of-speech),
ordered by order of occurrence in a text corpus
n_grams <integer> : an integer representing the ngram value used for this table
Outputs:
word_table : a dictionary of the form {<list<string>>:{<string>:<list<tuple(<string>,<int>)>>}}
e.g. for n_grams = 3:
{('firstword', 'secondword') : {'NOUN' : ['dog', 'cat', ...
'VERB' : ['ran', 'ate', ...
pos_table : a dictionary of
"""
# get pos tags from tokens
# real_punctuation = []
# for token in tokens:
# if token[1] != ".":
# real_punctuation.append(token)
# else:
# real_punctuation.append((token[0], token[0]))
# tokens = real_punctuation
tags = nltk.FreqDist([t[1] for t in tokens])
word_table = {}
grammar_table = {}
word_pos_map = {}
pos_word_map = {}
value_base = {}
# initialize parts-of-speech keys for table
for i in tags:
value_base[i] = []
key_size = n_grams - 1
stop_index = len(tokens) - key_size
import copy
from collections import defaultdict
i = 0
while i < stop_index:
word_key = []
grammar_key = []
pos_keys = copy.deepcopy(value_base)
for j in range(key_size):
word_key.append(tokens[i+j][0])
grammar_key.append(tokens[i+j][1])
next_word = tokens[i + key_size]
# skip words in parenthesis
left_bracket_count = 0
right_bracket_count = 0
# if next_word[0] == "(":
# first_bracket_index = i + key_size
# left_bracket_count += 1
#
# while left_bracket_count != right_bracket_count:
# if tokens[i][0] == "(" and i != first_bracket_index:
# left_bracket_count += 1
# if tokens[i][0] == ")":
# right_bracket_count += 1
# i += 1
# next_word = tokens[i]
word_key = tuple(word_key)
grammar_key = tuple(grammar_key)
if word_key not in word_table:
word_table[word_key] = pos_keys
if grammar_key not in grammar_table:
grammar_table[grammar_key] = []
if tokens[i][0] not in word_pos_map:
word_pos_map[tokens[i][0]] = set()
if tokens[i][1] not in pos_word_map:
pos_word_map[tokens[i][1]] = set()
word_table[word_key][next_word[1]].append(next_word[0])
grammar_table[grammar_key].append(next_word[1])
word_pos_map[tokens[i][0]].add(tokens[i][1])
pos_word_map[tokens[i][1]].add(tokens[i][0])
i += 1
return word_table, grammar_table, word_pos_map, pos_word_map
def from_path_to_ngram_tables(paths, url_or_local, n_grams):
if url_or_local == 'url':
tokens = strip_html_tokenize_and_postag(paths)
if url_or_local == 'local':
tokens = open_file_tokenize_and_postag(paths)
word_table, grammar_table, word_pos_map, pos_word_map = build_ngram_tables(tokens, n_grams)
return word_table, grammar_table, word_pos_map, pos_word_map
"""
-----------------------sentence structures---------------------
"""
"""
Get raw text from a HTML
"""
def generate_html_rawtext(urls):
all_rawtext = ""
for url in urls:
html = request.urlopen(url).read().decode('utf8')
rawtext = BeautifulSoup(html, "lxml").get_text()
all_rawtext += "\n" + rawtext
return all_rawtext
"""
Get raw text from a local text file
"""
def generate_local_rawtext(paths):
all_rawtext = ""
for path in paths:
with codecs.open(path, 'r', 'utf8') as myfile:
rawtext=myfile.read()
all_rawtext += "\n" + rawtext
return all_rawtext
"""
Get all sentences from the raw text
"""
def generate_all_sentences(rawtext):
segment = rawtext.splitlines()
segment = list(filter(None, segment))
all_sentences = []
temp=[]
braket_check = 0;
quotation_check = 0;
termination_check = False;
for index, obj in enumerate(segment):
tokens = tokenize(obj)
for jndex, word in enumerate(tokens):
if word == "(" or word == "[" or word == "{" or word == "<":
braket_check += 1
continue
if word == ")" or word == "]" or word == "}" or word == ">":
braket_check -= 1
continue
if word == "``":
temp.append(word)
quotation_check += 1
continue
if word == "." or word == ";" or word == "?" or word == "!":
termination_check = True;
if quotation_check == 0 and termination_check == True:
temp.append(word)
all_sentences.append(temp)
temp=[]
termination_check = False
continue
else:
temp.append(word)
continue
if word == "''":
quotation_check -= 1
if quotation_check == 0 and termination_check == True:
temp.append(word)
all_sentences.append(temp)
temp=[]
termination_check = False
continue
else:
temp.append(word)
continue
if braket_check == 0:
temp.append(word)
return all_sentences
"""
Tokenize a raw text
"""
def tokenize(rawtext):
tokens = word_tokenize(rawtext)
return tokens
"""
Part-of-Speech Tagging for every word
"""
def universal_tagging(tokens):
tokens_and_tags = nltk.pos_tag(tokens)
tags = list(tag[1] for tag in tokens_and_tags)
return (tokens_and_tags, tags)
"""
Part-of-Speech Tagging for unique word
"""
def unique_tagging(tokens):
unique_tokens = set(tokens)
tokens_and_tags = nltk.pos_tag(unique_tokens)
tags = list(tag[1] for tag in tokens_and_tags)
return (tokens_and_tags, tags)
"""
Generate sentence structures
"""
def generate_sentence_structures(list_of_sentences, unique_tokens_and_tags):
sentence_structures = {}
for sentence in list_of_sentences:
for index, word in enumerate(sentence):
for x in unique_tokens_and_tags:
if x[0] == word:
if x[1] != ".":
sentence[index] = x[1]
else:
sentence[index] = word
break
for sentence in list_of_sentences:
if len(sentence) in sentence_structures:
sentence_structures[len(sentence)].append(sentence)
else:
sentence_structures[len(sentence)] = list()
sentence_structures[len(sentence)].append(sentence)
return sentence_structures
"""
Generate sentence structures in one procedure
"""
def from_path_to_sentence_structures(paths, url_or_local):
if url_or_local == 'url':
rawtext = generate_html_rawtext(paths)
if url_or_local == 'local':
rawtext = generate_local_rawtext(paths)
tokens = tokenize(rawtext)
all_sentences = generate_all_sentences(rawtext)
unique_tokens_and_tags,unique_tags = unique_tagging(tokens)
sentence_structures = generate_sentence_structures(all_sentences, unique_tokens_and_tags)
return sentence_structures
#alltext = generate_local_rawtext(["./Speech/speech2.txt","./Speech/speech3.txt","./Speech/speech4.txt","./Speech/speech5.txt",
# "./Speech/speech6.txt","./Speech/speech7.txt","./Speech/speech8.txt","./Speech/speech9.txt",
# "./Speech/speech10.txt","./Speech/speech11.txt","./Speech/speech12.txt","./Speech/speech13.txt",
# "./Speech/speech14.txt","./Speech/speech15.txt","./Speech/speech16.txt","./Speech/speech17.txt",
# "./Speech/speech18.txt","obama_speeches.txt"])
#alltext2 = generate_local_rawtext(["./Books/cities.txt","./Books/emma.txt","./Books/frankenstein.txt","./Books/heart.txt",
# "./Books/jungle.txt","./Books/plato_republic.txt","./Books/pride.txt","./Books/robinson.txt",
# "./Books/sherlock.txt"])
#t = tokenize(alltext)
#r = unique_tagging(t)
#t2 = tokenize(alltext2)
#r2 = unique_tagging(t2) |
def merge(l,r):
# O(n)
i_l=0
i_r=0
tab=[]
while i_l<len(l) and i_r<len(r):
if l[i_l]<r[i_r]:
tab.append(l[i_l])
i_l+=1
else:
tab.append(r[i_r])
i_r+=1
while i_l<len(l) and i_r>=len(r):
tab.append(l[i_l])
i_l+=1
while i_l>=len(l) and i_r<len(r):
tab.append(r[i_r])
i_r+=1
return tab
#Wersja pythonowska Merge_sorta
def Merge_sort(tab):
if len(tab)==1:
return tab
if len(tab)>1:
med=len(tab)//2
return merge(Merge_sort(tab[:med]),Merge_sort(tab[med:]))
print(Merge_sort([4,2,1,0,0,0,5]))
|
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1):
"""
Utility function for computing output of convolutions
takes a tuple of (h,w) and returns a tuple of (h,w)
"""
from math import floor
if type(h_w) is not tuple:
h_w = (h_w, h_w)
if type(kernel_size) is not tuple:
kernel_size = (kernel_size, kernel_size)
if type(stride) is not tuple:
stride = (stride, stride)
if type(pad) is not tuple:
pad = (pad, pad)
h = floor(((h_w[0] + (2 * pad[0]) - (dilation * (kernel_size[0] - 1)) - 1) / stride[0]) + 1)
w = floor(((h_w[1] + (2 * pad[1]) - (dilation * (kernel_size[1] - 1)) - 1) / stride[1]) + 1)
return h, w
|
# -*- coding : utf-8 -*-
# gra wisielec
# można dodać kategorie
import time
import random
import os
def begin():
print(u"\n\t\t*** GRA WISIELEC ***\n")
time.sleep(1)
print("Witaj!")
time.sleep(1)
print(u"\nZagrajmy w wisielca.")
time.sleep(2)
print(u"Ja wymyślam słowo, a Ty próbujesz je odgadnąć, podając litery.")
time.sleep(2)
print(u"Za każde dobrze odgadnięte słowo otrzymujesz jeden punkt.")
time.sleep(2)
print(u"Jesteś gotowy?")
time.sleep(2)
print(u"Aby rozpocząć grę, wciśnij dowolny klawisz.")
print(u"Aby się poddać lub zrezygnować, wciśnij q.")
key = input(u"Twoja decyzja: ")
if key.lower() == "q":
end_game()
return key
WORDS = ("interdyscyplinarny", "protodeklaratywy", "kompot", "przypadek", "pies", "chmurka", "programowanie", "python", "anagram", "łatwy", "skomplikowany", "odpowiedź", "ksylofon", "klamerka", "ziemniaki", "szampon")
used_words = [] # lista wylowowanych już w grze słów, żeby nie losowało tych samych ponownie do odgadnięcia
points = 0 # liczba zdobytych punktów w całej grze
amount = 0 # liczba wszystkich wyświetlonych słów do odgadnięcia
def end_game():
os.system('cls')
time.sleep(1)
print(u"\nGra została zakończona.")
print(u"Liczba wszystkich słów do odgadnięcia: " + str(amount))
print(u"Liczba zdobytych punktów: " + str(points))
print(u"Dziękujemy za udział w grze.")
input("Aby wyjść z programu, wciśnij Enter.")
def next_exmpl(): # przejście do następnego przykładu + podsumowanie
print(u"\nCzy chcesz przejść do następnego przykładu? Jeśli tak, wciśnij dowolny klawisz. Jeśli chcesz zakończyć grę, wciśnij q.")
print(u"Liczba wszystkich słów do odgadnięcia: " + str(amount))
print(u"Dotychczas zdobyte punkty: " + str(points))
key = input()
if key.lower() == "q":
end_game()
return key
def bad_answer(tries, word):
if tries < 8:
if tries == 1:
print("""
|
|
|
|
|
|
""")
elif tries == 2:
print("""
______
|
|
|
|
|
|
""")
elif tries == 3:
print("""
______
| |
| O
|
|
|
|
""")
elif tries == 4:
print("""
______
| |
| O
| |
|
|
|
""")
elif tries == 5:
print("""
______
| |
| O
| /|
|
|
|
""")
elif tries == 6:
print("""
______
| |
| O
| /|>
|
|
|
""")
elif tries == 7:
print("""
______
| |
| O
| /|>
| /
|
|
""")
if tries == 8:
print("""
______
| |
| O
| /|>
| / \
|
|
""")
print(u"\nPRZEGRAŁEŚ!")
print("To było słowo '" + str(word.upper()) +"'.")
def main():
key = begin()
global used_words
global points
global amount
while key.lower() != 'q':
if len(used_words) == len(WORDS): # wszystkie słowa z puli sa w liście wykorzystanych
os.system('cls')
time.sleep(1)
print(u"\aWygląda na to, że zaprezentowaliśmy Ci wszystkie słowa z naszej puli.")
time.sleep(1)
end_game()
break
while True:
word = random.choice(WORDS)
if word in used_words:
continue
else:
used_words.append(word)
break
amount += 1
mod_word = [] # zamiana wylosowanego słowa na ciąg znaków, który będzie się aktualizował
word_letters = [] # zbiór wyodrębnionych liter wylosowanego słowa
used_letters = [] # litery wprowadzone już przez użytkownika
correct_mod_w = [] # kompletny zbiór liter odgadniętego słowa
for i in word:
mod_word.append('_')
correct_mod_w.append('_')
word_letters.append(i)
mod_word[0] = word[0]
mod_word[-1] = word[-1]
correct_mod_w = ""
for i in word_letters:
correct_mod_w += " " + i
disp_word= ""
for i in mod_word:
disp_word += " " + i # to, co zostanie wyświetlone użytkownikowi
disp_word.upper()
os.system('cls')
time.sleep(1)
print(u"\nOdgadnij słowo: \n\n")
print("\t\t" + str(disp_word.upper()))
answer = input("\nPodaj literę: ")
tries = 0
while True:
try:
while answer.lower() in word_letters:
for i in range(len(word_letters)): # zamiana kresek na litery
if word_letters[i] == answer.lower():
mod_word[i] = answer.lower()
disp_word = ""
for i in mod_word:
disp_word += " " + i
print(u"\n\n\nTa litera znajduje się w słowie! Podaj następną.\n")
used_letters.append(answer)
bad_answer(tries, word)
print("\n\t\t" + str(disp_word.upper()))
if disp_word == correct_mod_w:
print(u"\n\nBRAWO! Odgadłeś słowo! To właśnie '" + str(word.upper()) +"'.")
points += 1
word_letters = None
key = next_exmpl()
break
print(u"\nWykorzystane litery: " + str(used_letters))
answer = input(u"\nPodaj literę: ")
while answer in used_letters:
print(u"Już podawałeś tę literę. Podaj inną.")
answer = input("Podaj literę: ")
while answer.lower() not in word_letters:
tries += 1
print(u"\a\n\n\nNiestety, ale taka litera nie występuje w słowie. Spróbuj jeszcze raz!\n")
bad_answer(tries, word)
if tries == 8:
word_letters = None
key = next_exmpl()
break
used_letters.append(answer)
print("\n\t\t" + str(disp_word.upper()))
print(u"\nWykorzystane litery: " + str(used_letters))
answer = input(u"\nPodaj literę: ")
while answer in used_letters:
print(u"Już podawałeś tę literę. Podaj inną.")
answer = input("Podaj literę: ")
except TypeError:
break
main()
|
"""
@author: Ian Huang
This script implements the lower level API for sending and recving commands
from the raspberry pi to the arduino through serial communication
"""
import numpy as np
import scipy as sp
import time
WAIT_MILLIS = 10
def angle_string_maker(angle_list):
return ','.join([str(element) for element in angle_list])
def angle_string_parser(angle_line):
assert isinstance(angle_line, str), 'input must be string, currently {}.'.\
format(type(angle_line))
data = [int(element.strip()) for element in angle_line.split(',')]
return data
def send(angle_vec, serial_port, ang_str_encoder=angle_string_maker):
""" Function to send a vector of angles to the arduino
Args:
angle_vec: list or numpy array of the joint angles
serial_port: the port that you would like to send data to.
Returns:
True if the communication was successful, false if it wasn't
"""
if not isinstance(angle_vec, list) and \
not isinstance(angle_vec, np.ndarray) and \
not isinstance(angle_vec, tuple):
raise ValueError("Sent angles not formatted in the correct way")
# sending the angle to serial_port
send_string = ang_str_encoder(angle_vec)
try:
serial_port.write(send_string)
except:
raise IOError('Unable to write string to serial port.')
# wait a little for the arduino to send stuff back
time.sleep(WAIT_MILLIS/float(1000))
return_angle = recv(serial_port)
if validate(angle_vec, return_angle):
return True
else:
return False
def recv(serial_port, verbose=False, delimiter=',', ang_str_decoder=angle_string_parser):
""" Function to receive a string of comma separated angles
args:
serial_port: the serial port
verbose: True if you'd like the received data to be printed. False by
default.
delimiter: The delimter used to separate different angle values
Returns:
recv_angles: the list/tuple/array of serial_received
"""
data_line = serial_port.readline()
# parsing the data_line
try:
data = ang_str_decoder(data_line)
except:
raise ValueError('Unable to convert to list of angles.')
if verbose:
# get time
t = time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime())
print('Received angles at {}: {}'.format(t, data_line))
return data
def validate(sent_angles, recv_angles):
""" Function to validate that the recv and angles match
Args:
sent_angles: list of angles sent
recv_angles: list of angles received
Returns:
True if they match, false otherwise.
"""
if not isinstance(sent_angles, list) and \
not isinstance(sent_angles, np.ndarray) and \
not isinstance(sent_angles, tuple):
raise ValueError("Sent angles not formatted in the correct way")
if not isinstance(recv_angles, list) and \
not isinstance(recv_angles, np.ndarray) and \
not isinstance(recv_angles, tuple):
raise ValueError("received angles not formatted in the correct way")
if isinstance(sent_angles, np.ndarray):
# converting to list
sent_angles = sent_angles.tolist()
if isinstance(recv_angles, np.ndarray):
# converting to list
recv_angles = recv_angles.tolist()
return recv_angles == sent_angles
|
#!/usr/bin/env python3
""" Author: Aaron Baumgarner
Created: 12/9/20
Updated: 12/9/20
Notes: Script created to look at user input and check based on various functions. Looks if a username
exists in a plain text file (bad practice but practicing python) and will check a phone number entered
to see if it is formated correctly based on a regex."""
import checkInput
import fileIO
fileName = "users.txt"
""" Displays a menu to the user """
def displayMenu():
print("1) Enter Username")
print("2) Enter Phone Number")
print("3) Add Username")
print("4) Check File")
print("0) Quit")
""" Prompts the user for a menu option and verifies it is a valid option """
def promptOption():
checkOption = False
while checkOption != True:
option = input("Option: ")
checkOption = checkInput.checkOption(option)
if checkOption == False:
print("Option " + option + " is not in the menu. Please try again.\n")
displayMenu()
return option
""" Prompts the user to enter a username """
def promptUsername():
userCheck = False
while userCheck != True:
username = input("Enter username: ")
userCheck = checkInput.checkUsername(username)
if userCheck == False:
print("Username " + username + " does not exist. Please try again or create a new account.")
else:
return "User " + username + " is allowed to login."
""" Prompts the user for a phone number """
def promptPhoneNumber():
phoneCheck = False
while phoneCheck != True:
phoneNumber = input("Enter Phone Number: ")
phoneCheck = checkInput.checkPhoneNumber(phoneNumber)
if phoneCheck == False:
print("Phone number entered is not in the standard US phone format. Please try again.")
else:
return "Phone Number: " + phoneNumber
""" Prompts for a new user and will check to see if user exists in the file already """
def promptNewUser():
newUserCheck = True
while newUserCheck:
newUser = input("Enter new Username: ")
newUserCheck = checkInput.checkUsername(newUser)
if newUserCheck:
print(newUser + " already exists. Please enter a new username.")
fileIO.saveNewLine(newUser, fileName)
return newUser + " has been entered"
""" Prompts the user for a file name """
def promptFileName():
exist = False
while exist != True:
fileName = input("File Name: ")
exist = fileIO.checkFileExists(fileName)
if exist == False:
print("File " + fileName + " wasn't found. Please try again.\n")
checkInput.checkFile(fileName)
""" Executes the menu option after it has been varified """
def executeOption(option):
if option == 1:
username = promptUsername()
print(username)
elif option == 2:
phoneNumber = promptPhoneNumber()
print(phoneNumber)
elif option == 3:
newUser = promptNewUser()
print(newUser)
elif option == 4:
promptFileName()
elif option == 0:
exit()
else:
print("Not sure how you got here..... o.O")
""" Main section of the code """
displayMenu()
option = int(promptOption())
executeOption(option)
exit() |
class Fruit:
def __init__(self, seeds, flesh, skin):
self._seeds = seeds
self._flesh = flesh
self._skin = skin
@property
def seeds(self):
return self._seeds
@property
def flesh(self):
return self._flesh
@property
def skin(self):
return self._skin
def __str__(self):
return "{name}: I have {skin} skin, {flesh} flesh and {seeds} seeds".format(
name=self.__class__.__name__,
skin=self.skin,
flesh=self.flesh,
seeds=self.seeds
)
class Apple(Fruit):
def __init__(self, colour):
super().__init__(
seeds="small black pips",
flesh="pale and crunchy",
skin="firm yet thin, {}".format(colour)
)
class Braeburn(Apple):
def __init__(self):
super().__init__('red with green patches')
class Bramley(Apple):
def __init__(self):
super().__init__('green')
class Orange(Fruit):
def __init__(self):
super().__init__(
seeds="pale, wrinkly pips",
flesh="juicy, gelatinous, orange",
skin="thick, orange rind"
)
class Tomato(Fruit):
def __init__(self):
super().__init__(
seeds="small and round with a gelatinous case",
flesh="thin and watery",
skin="soft and red"
)
print(Braeburn())
print(Bramley())
print(Orange())
print(Tomato())
|
"""
General drawing methods for graphs using Bokeh.
"""
from random import randint
from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import (GraphRenderer, StaticLayoutProvider, Circle,
LabelSet, ColumnDataSource)
class BokehGraph:
"""Class that takes a graph and exposes drawing methods."""
def __init__(self, graph, height, width):
self.graph = graph
self.width = width
self.height = height
self.node_indices = list(graph.vertices.keys())
self.plot = figure(title='Graph', x_range=(0, width),
y_range=(0, height), tools='',
toolbar_location=None)
self.renderer = GraphRenderer()
def make_graph(self):
self.renderer.node_renderer.data_source.add(self.node_indices, 'index')
self.renderer.node_renderer.glyph = Circle(size=25, fill_color='color')
self.connect_nodes()
self.renderer.edge_renderer.data_source.data = self.graph.get_edges()
self.renderer.node_renderer.data_source.add(list(self.graph.get_colors()),
'color')
# took from here - POS
self.position_nodes()
self.plot.renderers.append(self.renderer)
output_file('graph.html')
show(self.plot)
def connect_nodes(self):
connected = set()
for node in self.graph.vertices:
if self.graph.vertices[node] not in connected:
connected_nodes = self.graph.connect(node)
connected |= connected_nodes
def position_nodes(self):
data = {'x': [], 'y': [], 'names': [], 'text_color': []}
used_pos = set()
for node in self.graph.vertices:
while True:
width = randint(2, self.width - 5)
height = randint(2, self.height - 5)
p = (width, height)
if p not in used_pos:
data['x'].append(width)
data['y'].append(height)
# used_pos.add(p)
padded_xs = (x for x in range(p[0] - 2, p[0] + 2))
padded_ys = (y for y in range(p[1] - 2, p[1] + 2))
# bad complexity, but trying things out
for w in padded_xs:
for h in padded_ys:
used_pos.add((w, h))
data['names'].append(self.graph.vertices[node].label)
data['text_color'].append('#000')
break
layout = dict(
zip(self.node_indices, list(zip(data['x'], data['y']))))
self.renderer.layout_provider = (
StaticLayoutProvider(graph_layout=layout))
nodes = LabelSet(x='x',
y='y',
text='names',
text_color='text_color',
# x_offset=20,
# y_offset=20,
level='overlay',
text_align='center',
text_baseline='middle',
source=ColumnDataSource(data),
render_mode='canvas')
self.plot.add_layout(nodes)
|
# You are given:
# 1. A source text (input)
# 2. Alphabet (alpha = "abcdefgh....xyz")
# 3. Key (key = "qwertzuioplkjhgfdsayxcvbnm")
# len(key) == len(alpha)
# no repeating letters in alpha or key
def encode(text):
encoded_text = ""
# substitute all letters from the alphabet to
# the corresponding letters in the key
return encoded_text
def decode(encoded_text):
text = ""
# substitute all letters from the key to
# the corresponding letters in the alphabet
return text
# input: 0 - encode/1 - decode?
# text
# print(encoded/decoded text)#
# Hello, world! -> Itffk, dksfo!
# git stash
# Encode/decode Cyrillic letters
# Ghbdtn vbh => Привет мир
# Руддщ цщкдв => Hello world
# Optional:
# Привет мир - Privet mir
# Я робот - Ya robot |
from datetime import timedelta, datetime
date = datetime(2021, 5, 10)
date += timedelta(days=1)
l = input("enter subjects list:\n").split(",")
for i in range(len(l)):
for ele in l:
date += timedelta(days=1)
print(date, end ="")
print("\t" + ele)
|
# Gallegos Isaac Homework 3
# September 26th, 2018
# Gavin and Greg helped me with properly using dictionaries
import os
import json
class GradePortfolio:
''' The constructor initializes the data and provides a reference dictionary to aid in quantifying the letter grades of the dataset '''
def __init__(self, FileLocation = '../data/grade-data.json'):
self.data = []
with open(FileLocation) as f:
self.data = json.loads(f.read())
self.grades = {'A':90, 'B':80, 'C':70, 'D':60, 'F':50}
''' Calculates average grade from every students final grade. Achieves this by looping through every student and using the grade dictionary to quantify their letter grade to an integer.'''
def AverageGrade(self):
count = 0
for i in self.data:
count = count + self.grades[i[3]]
average = int(count/len(self.data))
for i in self.grades:
if average == self.grades[i]:
return i
''' Calculates average difference in grades between midterm and final for each student. The result gives a floating point difference that equates to a little more than half a letter grade '''
def AverageGradeDifference(self):
differences = []
for i in self.data:
x = self.grades[i[2]]
y = self.grades[i[3]]
z = abs(y-x)
differences.append(z)
count = 0
for i in differences:
count = count + i
average = count/len(differences)
return average
''' Calculates the number of female students in the dataset '''
def FemaleCount(self):
count = 0
for i in self.data:
if i[1] == 'F':
count = count + 1
return count
''' Calculates the number of male students in the dataset '''
def MaleCount(self):
count = 0
for i in self.data:
if i[1] == 'M':
count = count + 1
return count
if __name__ == '__main__':
''' Here I call all the functions '''
value = GradePortfolio()
print ()
print ('Average Grade:', value.AverageGrade())
print ('Average Change in Grade:', value.AverageGradeDifference(), 'or about half a letter grade')
print ('Number of Females:', value.FemaleCount())
print ('Number of Males:', value.MaleCount()) |
#Draw Roche Lobe graph.
#Written by Daniel Foulds-Holt 17/05/2020
import math
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import ticker, cm
def Roche(x, y, M1, M2, A):
q = M2 / M1
r1 = math.sqrt((x + (A/2))**2.0 + y**2.0)
r2 = math.sqrt((x - (A/2))**2.0 + y**2.0)
if r1 == 0 or r2 == 0:
return 0
a1 = 2 / (1 + q) * 1 / r1
a2 = 2 * q / (1 + q) * 1 / r2
a3 = (x - (q / (q+1)))**2.0 + y**2.0
res = a1 + a2 + a3
# Max = 10000
# if res > Max:
# res = Max
return res
def COM(M1, M2, A):
return ((M2 * A/2) - (M1 * A/2))/(M1+M2), 0
def GenerateData():
plt.rcParams['font.serif'] = "Times New Roman"
plt.rcParams['font.family'] = "serif"
plt.rcParams['font.weight'] = "light"
plt.rcParams['font.size'] = 14
plt.rcParams['mathtext.fontset'] = 'cm'
plt.rcParams['mathtext.rm'] = 'serif'
M1 = 10
M2 = 3
A = 0.75
comx, comy = COM(M1, M2, A)
temp = Roche(comx, comy, M1, M2, A)
print("COM (", comx, ",", comy, ") = ", temp)
cblabel = "Gravitational Potential " r"$\Phi$"
Factor = 1
steps = 1000
bound = 1
#lines = [0, 2, 5, 6,7, 10, 50, 75, 100, 150, 200, 250, 300, 400, 500]
lines = 1000
xlist = np.linspace(-bound, bound, steps)
ylist = np.linspace(-bound, bound, steps)
x, y = np.meshgrid(xlist, ylist)
z = [[0 for k in range(steps)] for l in range(steps)]
i = 0
while i < steps:
j = 0
while j < steps:
z[i][j] = (Factor * Roche(xlist[i],ylist[j],M1,M2,A))
if (z[i][j] - 0)**2 < 3:
print("0 = (", xlist[i], ", ", ylist[j], ") ")
j = j + 1
i = i + 1
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_aspect("equal")
cp = plt.contourf(y, x, z, lines, cmap=plt.cm.bone, locator=ticker.LogLocator(base=10.0, subs="all"), vmax=100)
cb = fig.colorbar(cp, ticks=[1,10,100, 1000], label=cblabel)
ax.text(A/2-0.06, -0.26, r"$\mathbf{M_2}$", color='White', fontsize=14, fontweight='bold')
ax.text(-A/2-0.05, -0.26, r"$\mathbf{M_1}$", color='White', fontsize=14, fontweight='bold')
#cp2 = plt.contour(cp, levels=[5.667865], colors='r')
#cp3 = plt.contour(cp, levels=[5.66555], colors='r')
cp4 = plt.contour(cp, levels=[4.9281], colors='r')
plt.plot([A/2], [0], "o", color="Yellow", markersize=6*(M2/(M1+M2)))
plt.plot([-A/2], [0], "o",color="Yellow", markersize=6*(M1/(M1+M2)))
plt.axis('off')
# plt.legend(loc="best")
plt.savefig("RocheLobe.png", format='png', dpi=1200)
plt.show()
return x, y, z
def Main():
x, y, z = GenerateData()
Main()
|
"""Problem 6: Sum square difference
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square
of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first n natural numbers and the square of
the sum.
"""
def sum_square_difference(n: int) -> int:
"""Return the difference between the sum of the squares of the first n natural numbers and the
square of the sum.
"""
# Sum the squares
sum_squares = sum(map(lambda i: i ** 2, range(1, n + 1)))
# Square the sums
square_sums = sum(range(1, n + 1)) ** 2
# Return the difference between the two
return square_sums - sum_squares
|
def latticePaths(n):
"""
Returns the number of unique paths available when traversing a grid of size n from the top left to bottom right corner,
when only downward or rightwards movement is allowed.
"""
lattice = []
for i in range(1, n + 1):
sub_list = [1]
for j in range(1, i):
sub_list.append(sub_list[-1] + lattice[i - 2][j])
sub_list.append(sub_list[-1] * 2)
lattice.append(sub_list)
return lattice[-1][-1]
|
#!/usr/bin/env python3
# Created by: Jonathan Kene
# Created on: June 8, 2021
# This program uses user defined functions to calculate the volume of a sphere
import math
def calculate(operator, num_int):
result = float(-1)
if operator == "volume":
result = 4/3*math.pi*(num_int**3)
elif operator == "area":
result = 4*math.pi*num_int
else:
result = float(-1)
return result
def main():
while True:
# ask the user whether they wish to have the volume or area
quantity = input("Please type in whether you'd like to calculate the"
" volume or the area (type 'volume' or 'area'): ")
# these two function asks for the radius from the user
if (quantity == "volume"):
print("Today, we will calculate the volume of a sphere")
print("")
while True:
radius_from_user_string = input("Enter the radius"
" of a sphere (cm): ")
# make sure if the user types anything but an integer, it's not valid
try:
radius_from_user_int = float(radius_from_user_string)
print("")
if (radius_from_user_int <= 0):
print("{} is not a"
" positive number". format(radius_from_user_int))
else:
break
except ValueError:
print("Please enter a valid number")
results = calculate(quantity, radius_from_user_int)
print("The volume is {:.2f} cm^3". format(results))
elif (quantity == "area"):
print("Today, we will calculate the area of a sphere")
print("")
while True:
radius_from_user_string = input("Enter the radius"
" of a sphere (cm): ")
# make sure if the user types anything but an integer, it's not valid
try:
radius_from_user_int = float(radius_from_user_string)
print("")
if (radius_from_user_int <= 0):
print("{} is not a"
" positive number". format(radius_from_user_int))
else:
break
except ValueError:
print("Please enter a valid number")
results = calculate(quantity, radius_from_user_int)
print("The area is {:.2f} cm^2". format(results))
else:
print("Invalid Input")
continue
if __name__ == "__main__":
main()
|
# By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do"
# "I have not given or received any unauthorized aid on this assignment"
#
# Name: Hamza Raza
# Section: 415/ 515
# Assignment: Lab 6b
# Date: 29 September 2020
#Make a blank list so I can store the user inputs within the list
user_list = []
pass_list = []
#Ask how many pairs there are
num_pairs = int(input("How many username/password pairs would you like: "))
#Run the code for as many pairs the user wants with the for loop
for x in range(num_pairs):
#Have to ask the user for a username and password which adds into the respective blank list
user = input("Enter a username: ")
user_list.append(user)
password = input("Enter a password: ")
pass_list.append(password)
#Here I zip up the list making it immutable and encrypted
zip_dict = zip(user_list, pass_list)
dict_up = dict(zip_dict)
print(dict_up)
#The official test of trying to log in
user_guess = input("Enter username: ")
pass_guess = input("Enter password: ")
#Have to run the iterator within the dictionary
while user_guess in dict_up and dict_up[user_guess] != pass_guess:
#If the iterator within the dictionary wihch uses the username matches the password then you are logged in
if user_guess in dict_up and dict_up[user_guess] == pass_guess:
#Should end code if you are logged in
break
#If the the iterator which is explained above doesnt equal the password then its an invalid username and same for the else below
elif user_guess in dict_up and dict_up[user_guess] != pass_guess:
print("Invalid password")
else:
print("Invalid password")
user_guess = input("Enter username: ")
pass_guess = input("Enter password: ")
print('Logged in!')
|
import collections
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def addOneRow(root, v, d):
if d == 1:
new_root = TreeNode(v)
new_root.left = root
return new_root
queue = collections.deque()
queue.append(root)
depth = 1
while queue:
for _ in range(len(queue)):
top = queue.popleft()
if depth == d - 1:
left, right = TreeNode(v), TreeNode(v)
if top.left:
left.left = top.left
if top.right:
right.right = top.right
top.left, top.right = left, right
continue
if top.left:
queue.append(top.left)
if top.right:
queue.append(top.right)
depth += 1
return root
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(1)
root.right.left = TreeNode(5)
addOneRow(root, 1, 3) |
# mario.py
#prompt the user & validate the number
while True:
try:
height = int(input("Height of the pyramid: "))
except ValueError:
print("Please enter a number!")
if height > 0:
break
i = 0
for x in range(height):
for y in (range(height- i - 1)):
print(" ",end="")
for z in (range(i +1 )):
print("#",end="")
print(" ",end="")
print(" ",end="")
for a in range(i + 1):
print("#",end="")
print(" ")
i += 1
|
# Fill in the blanks of this code to print out the numbers 1 through 7.
number = 1
while number < 7:
print(number, end=" ")
number += 1
The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen
def show_letters(word):
for letter in word:
print(letter)
show_letters("Hello")
# Should print one line per letter.
# Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits.
# Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.
def digits(n):
count = 0
if n == 0:
count = 1
num = n
while(num > 0):
num = num // 10
count = count + 1
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
# This function prints out a multiplication table (where each number is the result of multiplying the
# first number of its row by the number at the top of its column).
# Fill in the blanks so that calling multiplication_table(1, 3) will print out:
def multiplication_table(start, stop):
for x in range(start,stop+1):
for y in range(start,stop+1):
print(str(x*y), end=" ")
print()
multiplication_table(1, 3)
# Should print the multiplication table shown above
# The counter function counts down from start to stop when start is bigger than stop, and counts up from start to stop otherwise.
# Fill in the blanks to make this work correctly.
def counter(start, stop):
x = start
if start > stop:
return_string = "Counting down: "
while x >= stop:
return_string += str(x)
if x > stop:
return_string += ","
x = x-1
else:
return_string = "Counting up: "
while x <= stop:
return_string += str(x)
if x < stop:
return_string += ","
x = x + 1
return return_string
print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"
def even_numbers(maximum):
return_string = ""
for x in range(2,maximum,2):
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(6)) # Should be 2 4 6
print(even_numbers(10)) # Should be 2 4 6 8 10
print(even_numbers(1)) # No numbers displayed
print(even_numbers(3)) # Should be 2
print(even_numbers(0)) # No numbers displayed
|
answer = 0
prev = ' '
input_string = input()
for i in input_string:
if i != prev:
answer += 1
prev = i
print(answer//2)
|
#converts standard time to military time
#input: hh:mm:ss_M where 0<=hh<=12
#output: hh:mm:ss where 0<=hh<24
import sys
time = input().strip()
mystrs = time.split(sep=':')
aorp = time[-2]
if aorp == 'A':
hh = int(mystrs[0])%12
print(str(hh).rjust(2,'0') + time[2:8])
elif aorp == 'P':
hh = int(mystrs[0])
if hh==12:
print(str(hh).rjust(2,'0') + time[2:8])
else:
print(str( (int(mystrs[0])+12) %24).rjust(2, '0')+":"+mystrs[1] + ":"+mystrs[2][0:2])
else:
print('Not correct time format') |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问
# 变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_score(self, score):
if 0 <= score <= 100:
self.__score = score
else:
raise ValueError('bad score')
bart = Student('黎明', 91)
print(bart.print_score())
|
"""
Modular Exponentiation (Fast Exponentiation) - [https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/]
Examples :
Given three numbers x, y and p, compute (x^y) % p.
Input: x = 2, y = 3, p = 5
Output: 3
Explanation: 2^3 % 5 = 8 % 5 = 3.
Input: x = 2, y = 5, p = 13
Output: 6
Explanation: 2^5 % 13 = 32 % 13 = 6.
"""
def mod_exp(a, n, m):
res = 1
# Update x if it is more than or equal to p
# a = a % m
while(n):
if n%2: # ( n&1 ):
res = (res * a) % m
a = (a * a) % m
n = n // 2 # n >>= 1
return res
a = 7
n = 3
m = 5
res = mod_exp(a, n, m)
print(f'Result: {res}')
|
# This program will take the inputs from two exam scores and calculate the weighted grades
print ("Enter your first exam score ")
grade1=float(input())
print ("Enter your second exam score")
grade2= float(input())
weight1= 0.60
weight2= 0.40
scoretotal= (grade1*weight1)+(grade2*weight2)
print ("Your Total Weighted Score is")
print (scoretotal)
|
__author__ = 'valenc3x'
class Node(object):
"""docstring for Node"""
def __init__(self, value):
self.value = value
self._next = None
self._prev = None
def __str__(self):
return "{}".format(self.value)
@property
def next(self):
return self._next
@next.setter
def next(self, node):
assert isinstance(node, Node) or node is None
self._next = node
@property
def prev(self):
return self._prev
@prev.setter
def prev(self, node):
assert isinstance(node, Node) or node is None
self._prev = node
def node_data(self):
print("value: {} \t\t next: {} \t\t prev: {}".format(self.value, self.next, self.prev))
class SLL(object):
"""Simple Linked List"""
def __init__(self):
self.head = None
@property
def size(self):
aux = self.head
count = 0
while aux:
count += 1
aux = aux.next
return count
def add(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
else:
aux = self.head
while aux.next:
aux = aux.next
aux.next = new_node
return new_node
def remove_duplicates(self):
unique = set()
aux = self.head
prev = None
while aux:
if aux.value in unique:
prev.next = aux.next
else:
unique.add(aux.value)
prev = aux
aux = aux.next
def show_list(self):
result = list()
aux = self.head
while aux:
result.append(str(aux))
aux = aux.next
print(' -> '.join(result))
def sll_data(self):
aux = self.head
while aux:
aux.node_data()
aux = aux.next
|
# 1003
def fibo(n) :
fibonacci = [[1,0],[0,1]]
cnt = 2
while cnt <= n :
fibon = [0,0]
for i in range(0,2) :
fibon[i] = fibonacci[cnt-1][i]+fibonacci[cnt-2][i]
fibonacci.append(fibon)
cnt += 1
print(fibonacci[n][0],fibonacci[n][1])
for i in range(int(input()) ):
fibo(int(input()))
|
def sol(x,y,r,X,Y,R):
distance = pow(pow(abs(X-x),2) + pow(abs(Y-y),2),1/2)
if(x==X and y==Y) :
if(r==R):
return -1
return 0
if(r > distance+R or R > distance+r): return 0
elif(r == distance+R or R == distance+r) : return 1
if (r+R) == distance :
return 1
elif (r+R) > distance :
return 2
elif (r+R) < distance :
return 0
T = int(input())
for x in range(T):
lst = input().split()
x1 = int(lst[0]); y1 = int(lst[1]); r1 = int(lst[2]);
x2 = int(lst[3]); y2 = int(lst[4]); r2 = int(lst[5]);
res = sol(x1,y1,r1,x2,y2,r2)
print(res)
|
#10828 스택
class Stack:
data=[]
def __init__(self):
self.data=[]
def push(self, x):
self.data.append(x)
def pop(self):
if(self.empty()==1):
return -1
return self.data.pop()
def size(self):
return len(self.data)
def empty(self):
if(len(self.data)!=0):return 0
return 1
def top(self):
if(self.empty()==1):
return -1
return self.data[len(self.data)-1]
stack=Stack()
t=int(input())
for x in range(t):
string = input().split()
if(len(string)==2):
stack.push(int(string[1]))
else : # len 1 , pop size empty top
if(string[0].find("pop")==0):
print(stack.pop())
elif(string[0].find("size")==0):
print(stack.size())
elif(string[0].find("empty")==0):
print(stack.empty())
elif(string[0].find("top")==0):
print(stack.top())
|
#10845 큐
#10828 스택
class Queue:
data=[]
def __init__(self):
self.data=[]
def push(self, x):
self.data.insert(0,x)
def pop(self):
if(self.empty()==1):
return -1
return self.data.pop()
def size(self):
return len(self.data)
def empty(self):
if(len(self.data)!=0):return 0
return 1
def front(self):
if(self.empty()==1):
return -1
return self.data[len(self.data)-1]
def back(self):
if(self.empty()==1):
return -1
return self.data[0]
queue=Queue()
t=int(input())
for x in range(t):
string = input().split()
if(len(string)==2):
queue.push(int(string[1]))
else : # len 1 , pop size empty top
if(string[0].find("pop")==0):
print(queue.pop())
elif(string[0].find("size")==0):
print(queue.size())
elif(string[0].find("empty")==0):
print(queue.empty())
elif(string[0].find("front")==0):
print(queue.front())
elif(string[0].find("back")==0):
print(queue.back())
|
def fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
return "fizzbuzz"
elif number % 3 == 0:
return "fizz"
elif number % 5 == 0:
return "buzz"
return number
def fizzbuzz_list(numbers):
n = []
for number in numbers:
n.append(fizzbuzz(number))
return n |
# Solution with extra space
def isPermutation(input_str, next_str):
d = dict()
for letter in input_str:
if letter not in d:
d[letter] = 1
else:
d[letter] += 1
for letter in next_str:
if letter not in d:
return False
else:
d[letter] -= 1
return True
# Another solution is an O(N^2) match which is not ideal
print("Is Permutation: ", isPermutation('sidd', 'dis'))
print("Is Permutation: ", isPermutation('sidd', 'pis')) |
import numpy as np
rows = int(input('Enter the rows in the grid: '))
columns = int(input('Enter the columns in the grid: '))
# ways = [[0]*(columns+1)]*(rows+1)
# ways[1:] = [1]*(columns)
# ways[:1] = [1]*(rows)
ways = np.zeros(shape=(rows+1,columns+1))
ways[1,:] = [0] + [1] * columns
ways[:,1] = [0] + [1] * rows
print('Ways: ', ways)
for i in range(2, rows+1):
for j in range(2, columns+1):
ways[i][j] = ways[i-1][j] + ways[i][j-1]
print('Ways: ', ways)
print('Ways to reach home is: %d' % ways[rows][columns])
|
n = int(input('Enter the number of steps: '))
ways = [0] * n
ways[0] = 1
ways[1] = 2
print('Ways: ', ways)
for i in range(2, n):
ways[i] = ways[i-1] + ways[i-2]
print('Number of ways to reach %d-th step is: %d' % (n, ways[n-1])) |
print("==== Maquina de operacoes ===")
def operacao(soma, sub):
soma = op1 + op2
print()
operacao = input("Qual a op: ")
if operacao == "+":
soma = operando1+operando2
print(soma)
oza
|
print("=== Verifica se uma letra eh diferente de 'a' e de 'z' ===")
letra = input("Digite uma letra: ")
print(letra, "eh diferente de 'b' e de 't'?", (letra != 'b' and letra != 't')) |
print(" == Diferenca pelo maior e menor ==")
n1 = (float) (input("Qual o primeiro valor? "))
n2 = (float) (input("Qual o segundo valor? "))
if n1> n2:
maior = n1 - n2
print("Diferenca entre eles: ", maior)
elif n2>n1:
maior = n2 - n1
print("Diferenca entre eles: ", maior)
else:
print("Operacao invalida")
|
print(" == Numeros em ordem crescente == ")
a = (int) (input("Valor do numero a: "))
b = (int) (input("Valor do numero b: "))
c = (int) (input("Valor do numero c: "))
if (a<b) and (b<c):
print(a, b, c)
elif (b<a) and (a<c):
print(b, a, c)
elif (c<b) and (b<a):
print(c, b, a)
elif (c<a) and (a<b):
print(c, a , b)
elif (a<c) and (c<b):
print(a, c, b)
elif (b<c) and (c<a):
print(b, c, a)
|
print("=== Calculo do quadrado ===")
x = (int) (input("digite um numero: "))
print("O quadrado de", x,"eh: ", x**2 ) |
def divisao(n):
for i in range(10):
print(n*(1+i), "/", n, "=", (i+1))
def tabuada(n):
print("Tabuada do", n)
print("==========")
divisao(n)
valor = (int) (input("Digite um numero inteiro pra tabuada: "))
tabuada(valor) |
'''
Author: mxh970120
Date: 2020.12.21
'''
class Solution:
def minCostClimbingStairs(self, cost) :
# 动态规划
n = len(cost)
dp = [0] * (n + 1) # 这里的dp[0]和[1]均为0
for i in range(2, n + 1):
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
return dp[-1]
if __name__ == '__main__':
cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
solu = Solution()
print(solu.minCostClimbingStairs(cost)) |
'''
Author: mxh970120
Date: 2020.12.17
'''
class Solution:
def addBinary(self, a: str, b: str) -> str:
# python偷懒
# return bin(int(a, 2) + int(b, 2))[2:]
res = ''
i = len(a)-1
j = len(b)-1
carry = 0
while i >= 0 or j >= 0 or carry == 1:
if i >= 0:
carry += int(a[i])
if j >= 0:
carry += int(b[j])
res = str(carry % 2) + res
i, j, carry = i - 1, j - 1, carry//2
return res
if __name__ == '__main__':
a = "1010"
b = "1011"
solu = Solution()
print(solu.addBinary(a, b)) |
'''
Author: mxh970120
Date: 2020.12.16
'''
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
strs = s.split()
if len(pattern) != len(strs):
return False
# 判断plattern是否和s建立映射
d = dict()
for i, p in enumerate(pattern):
if p not in d:
d[p] = strs[i]
else:
if d[p] != strs[i]:
return False
# 判断s和plattern是否建立映射,需要彼此建立映射才一一对应
d = dict()
for i, p in enumerate(strs):
if p not in d:
d[p] = pattern[i]
else:
if d[p] != pattern[i]:
return False
return True
if __name__ == '__main__':
pattern = "abba",
str = "dog cat cat dog"
solu = Solution()
print(solu.wordPattern(pattern, str)) |
#Julia & Nicole's stopwatch timer
import tkinter as tk #we used tkinter instead of kivy because tkinter is used a toolkit that is able to construct wdigets, stopwatch,etc
import tkinter.font as TkFont
from datetime import datetime
def run():
current_time = datetime.now()
diff = current_time - start_time
txt_var.set(' %d.%02d' % (diff.seconds,diff.microseconds//10000)) #converting seconds
if running: #for timelapse
root.after(20, run) #to reschedule after 20ms, refersh display
def start():
global running
global start_time
if not running:
running = True
start_time = datetime.now()
root.after(10, run)
def stop():
global running
running = False
def reset():
global start_time
start_time = datetime.now()
if not running:
txt_var.set(' 0:00 ')
running = False
start_time = None
root = tk.Tk()
root.geometry("600x300") #width x height of the stopwatch
root.title("Stopwatch")
txt_var = tk.StringVar()
txt_var.set(' 0:00 ')
fontstyle = TkFont.Font(size = 50) #to make the '0:00' bigger
tk.Label(root, textvariable=txt_var, font=fontstyle) .pack()
tk.Button(root, text="Start", command=start) .pack(fill = 'x') #start button
tk.Button(root, text='Stop', command=stop) .pack(fill='x') #stop button
tk.Button(root, text='Reset', command=reset) .pack(fill='x') #reset button
tk.Button(root, text='Timelapse', command=run) .pack(fill='x') #timelapse button
root.mainloop() #for looping purposes (multiple times) |
"""
Cracking the coding interview
Practice questions
Part 1. Strings
"""
"""
Helper functions:
"""
# QuickSort O(n log n)
# note python sort is also (n log n).. so, just sayin'
def quickSort(arr):
if len(arr) > 0:
quickSort_worker(arr, 0, len(arr) - 1)
return arr
else:
return None
def quickSort_worker(arr, lo, hi):
if lo < hi: # base condition
p = quickSort_partition(arr, lo, hi) # pivot
quickSort_worker(arr, lo, p - 1) # go left
quickSort_worker(arr, p + 1, hi) # go right
def quickSort_partition(arr, lo, hi):
i = lo # the wall
p = arr[hi] # pivot
for j in range(lo, hi):
if arr[j] <= p: # less than pivot
arr[i], arr[j] = arr[j], arr[i] # swap
i += 1
arr[hi], arr[i] = arr[i], arr[hi] # swap pivot to wall
return i # returning new pivot
def get_permutations(str):
if not str:
return []
stack = list(str)
results = [stack.pop()]
#print "start-results:{}".format(results)
while len(stack) != 0:
c = stack.pop()
new_results = []
for w in results:
for i in range(len(w)+1):
#print "i={} w={} (w[:i]={} c={} w[i:]={}) ({})".format(i, w, w[:i], c, w[i:], w[:i] + c + w[i:])
new_results.append(w[:i] + c + w[i:])
results = new_results
#print results
return results
"""
Unique characters in a string
Note: not using extra space - so no hash table or comparison array etc.
Time is O(n^2) Space is O(1)
"""
def unique_characters_in_string(str):
for i in range(0,len(str)):
# now we'll run through from where we left off comparing
# note: starting @ i + 1 so we don't compare start to start!
for j in range(i + 1, len(str)):
if str[i] == str[j]:
# dup found - get out of here
return False
return True
"""
Unique characters in a string: with extra space tracking
Use additional storage to track which characters have already been used
Should ask what characters are being used, ascii or unicode
In this case using ascii 256
using a dict, no need to know the size ahead of time
Time O(n) with Space O(n)
"""
def unique_character_in_string_tracker(str):
# if using ascii, technically size is max 256
# although if using unicode, size could be 1.4 million - is this helpful at all ?
if len(str) > 256:
return False
# extra space dict
track = {}
for c in str:
if ord(c) in track:
return False
else:
track[ord(c)] = True
return True
# for fun using a bit vector (extra storage) - also (not a standard package of p2.xx)
def unique_character_in_string_bit(str):
checker = 0
checkbit = 0
ascii = None
for i in range(0, len(str)):
"""
bit vector in 32 bit integer
00000000000000000000000000000000
where:
ascii: a(97) to z(122) and A(65) to Z(90)
e.g., if ascii val 97-122, subtract 96
if ascii val 65-90, subtract 64
then store a-z, A-Z in bit vector 1 thru 26
example: if a and C already found in list
10100000000000000000000000000000
"""
ascii = ord(str[i]) # ascii value of char
if (ascii >= 97 and ascii <= 122) or (ascii >= 65 and ascii <= 90):
if (ascii >= 97 and ascii <= 122):
checkbit = ascii - 96
else:
checkbit = ascii - 64
# None of this can happen witout the bit vector library
# being installed: python -c 'import bitarray; bitarray.test()'
if checker and (checkbit << 1):
return False
else:
checker |= (checkbit << 1)
return True
"""
String permutations
check if string 1 is a permutations of string 2
Easiest and fastest would be to sort strings and compare
quicksort time: O(n log n)
"""
def is_permutation(str1, str2):
if str1 is None or str2 is None:
return False
if len(str1) != len(str2):
return False
#sstr1 = quickSort(list(str1))
#sstr2 = quickSort(list(str2))
# Of course, using internal sorted function is also O(n log n)
sstr1 = sorted(str1)
sstr2 = sorted(str2)
if sstr1 == sstr2:
return True
else:
return False
# using a hash table can get time down to O(n)
def is_permutation_hash(str1, str2):
# first, check if strings are same length - then...
# add second array to hash table, collisions build linked list
# lookup time of hash table is O(1) to O(n) if all letters point to same key
# O(n) time to create hash table (walking array)
# O(n) time to walk first array, then O(1) to check hash
# removing elements from hash table as we search and match str1 to str2(hash)
# keeping track of number of elements in hash, when done walking str1
# if hash count is zero at end - we have a permutation
# total time is O(n) - yay!
pass
"""
UrlIfy
Add %20 spaces to "Mr John Smith " size 13
assume that end of string hold enough space for space conversion e.g., ' ' to %20
in place, time: O(n)
Hints: read backwards to modify, count spaces before starting
"""
def urlify_spaces(str, true_len=0):
# since we are given the true lengh, this should be defined
# else return None
if not true_len:
return None
# count spaces
spaces = 0
for i in range(0, true_len):
if str[i] == " ":
spaces += 1
# error if not enough room at end
# note: space is 3 chars - 1 char for space (2)
hi = len(str) - 1
#print "hi:{}, true_len:{} + (spaces:{} * 3))".format(hi, true_len, spaces)
if (true_len + (spaces * 2)) != hi + 1:
return None
# modify
# starting at end move everything to actual lengh
# insert %20 as space
# note: since going backwards, actual end index is (true_len - 1)
# and since range end doesn't include index defined '0' then
# beginning is 0 - 1
str = list(str)
for i in range(true_len - 1, 0 - 1, -1):
if str[i] == " ":
# More Pythonic - however, easier to understand below
# remember looking between values when counting index
# 012345678901234567
# [Mr John SmitSmith]
#str[hi - 2:hi + 1] = "%20"
#hi -= 3
str[hi] = "0"
hi -= 1
str[hi] = "2"
hi -= 1
str[hi] = "%"
hi -= 1
else:
str[hi] = str[i]
hi -= 1
return ''.join(str)
"""
Palindrone finder
Hings: no need to find all letter combinations, use a hash table for O(n) time
find all palindrones in a string and return results
store letters in hash table by count e.g., 'a' = 2, 'b' = 4
note that single letters will be in the center and no more than one single allowed for palindrome
abcccccba
"""
def find_palindrones(str):
checker = {} # dictionary
palindrones = []
# Blank or 1 character - automatically a palindrome
if len(str) <= 1:
return True
# move letters to hash
for c in str:
if c in checker:
checker[c] += 1
else:
checker[c] = 1
# check for singles
singles = 0
for c in checker:
if checker[c] % 2 == 1: # this is a single!
singles += 1
if singles > 1:
return False
# rebuild first half of list
l = []
single = ''
for c in checker:
if checker[c] % 2 == 1:
# single tracked in variable, not added to list
single = c
else:
# add half characters to list
# e.g., if 4 'a', add 2 to list ['a','a']
l.extend([c] * (checker[c] / 2))
# variations
lpre = get_permutations(''.join(l))
for pre in lpre:
palindrones.append(pre + single + pre[::-1])
print "all those palindrones:{}".format(palindrones)
return True # answered the question if this is a palindrone
"""
String One Off
compare str2 (test) to str1 (base)
Note: 3 actions on a string: insert, remove & replace
[a,b,c,d] [a,b,c,d,s]
[a,b,c,d] [b,c,d]
[a,b,c,d] [a,b,c,s]
"""
def string_one_away_same_length(str1, str2):
count_away = 0
for i in range(len(str1)):
if str1[i] != str2[i]:
#print "no match on str1[i]:{} to str2[i]:{}".format(str1[i], str2[i])
count_away += 1
if count_away > 1:
return False
if count_away == 1:
return True
else:
return False
def string_one_away_diff_length(str1, str2):
# compare shorter to longer
# where s1 is scanned to compare to s2
if len(str1) < len(str2):
s1 = list(str1)
s2 = list(str2)
else:
s1 = list(str2)
s2 = list(str1)
i=0
count_away = 0
while i < len(s1):
if s1[i] == s2[i]:
# all is good in the world
# - increment i
i += 1
else:
# bad things happening
# - track buggars
# - pop off bad value for re-comparison
s2.pop(i)
count_away += 1
if count_away > 1:
return False
return True
def string_one_away(str1, str2):
print "test:{} to {}".format(str1, str2)
if not str1 or not str2:
return False
if len(str1) == len(str2):
# str1 same length as str2
return string_one_away_same_length(str1, str2)
if len(str1) + 1 == len(str2) or len(str1) == len(str2) + 1:
# str1 +1 longer or str2 +1 longer
return string_one_away_diff_length(str1, str2)
else:
# strings cannot be +1 different at the point
return False
"""
String compression
aabbbccccddddd -> a2b3c4d5
abcd -> abcd... because it's smaller than a1b1c1d1
beware: concantenating strings over and over ?
"""
def string_compressor_concat(chr, chr_count):
# Returns output integer in front of all letters regardless of size
# e.g. a = a1, aa = a2, bbb = b3
str_out = ""
str_out = "{}{}".format(chr, chr_count)
return str_out
def string_compressor_concat_sized(chr, chr_count):
# returns only when sequence of letters is > 2
# e.g., a = a, aa = aa, bbb = b3
# why? because aa and a2 are the same size
str_out = ""
if chr_count > 2:
str_out = "{}{}".format(chr, chr_count)
else:
str_out = chr * chr_count
return str_out
def string_compressor(str):
print "string_compressor({})".format(str)
if not str:
return None
str_out = ""
chr_count = 1
chr = str[0]
for i in range(1, len(str)):
if str[i] == chr:
chr_count += 1
else:
str_out += string_compressor_concat(chr, chr_count)
chr = str[i]
chr_count = 1
str_out += string_compressor_concat(chr, chr_count)
# return shortest of two strings
if len(str) < len(str_out):
return str
else:
return str_out
"""
NxN Matrix rotator
a d g
b e h
c f i
Rotate edges 90deg - top=right, right=bottom, bottom=left, left=top
Try to do in place without extra space in O(e) Time
"""
nxn = [['a','b','c','d'],['e','f','g','h'],['i','j','k','l'],['m','n','o','p']]
def matrix_create(n):
# create matrix of size n
m = []
count = 0
for i in range(n):
m.append([j for j in range((n*i)+1,(n*(i+1))+1)])
return m
def matrix_print(matrix):
# matrix width and height might be different
# assuming all heights are the same
# print [0][0], [1][0], [2][0]
# Runtime: O(n^2)
str_out = []
i = 0
imax = len(matrix) - 1
j = 0
jmax = len(matrix[0]) - 1
while True:
str_out.append(matrix[i][j])
if i == imax:
i = 0
j += 1
print ' '.join(str(x).rjust(4,' ') for x in str_out)
str_out = []
else:
i += 1
if j >= len(matrix[i]):
return
# First go at this - made sense on paper
# Note: this only does outside edge, not for multi-layers (maybe a future version)
# Runtime O(3n) or O(n)? since it runs n + n-1 + n-2
def matrix_rotate_left(m):
if not m or len(m) != len(m[0]):
return False;
# Original
print "----------------------------------"
matrix_print(m)
print
"""
rotate - swap one by one all edges 90 deg counter-clockwise
"""
levels = len(m) / 2
mmax = len(m) - 1
for l in range(levels):
#print "level:{} mmax:{}".format(l,mmax)
for i in range(l, mmax):
#print "swap [{}][{}] for [{}][{}]".format(l,i,i,mmax)
m[l][i], m[i][mmax] = m[i][mmax], m[l][i]
#print "swap [{}][{}] for [{}][{}]".format(l,i,mmax,mmax-i+l)
m[l][i], m[mmax][mmax - i + l] = m[mmax][mmax - i + l], m[l][i]
#print "swap [{}][{}] for [{}][{}]".format(l,i,mmax-i+l,l)
m[l][i], m[mmax - i + l][l] = m[mmax - i + l][l], m[l][i]
mmax -= 1
matrix_print(m)
def matrix_rotate_right(m):
if not m or len(m) != len(m[0]):
return False;
# Original
print "----------------------------------"
matrix_print(m)
print
"""
rotate - swap one by one all edges 90 deg clockwise
"""
levels = len(m) / 2
mmax = len(m) - 1
for l in range(levels):
for i in range(l, mmax):
m[i][l], m[mmax][i] = m[mmax][i], m[i][l]
m[i][l], m[mmax - i + l][mmax] = m[mmax - i + l][mmax], m[i][l]
m[i][l], m[l][mmax - i + l] = m[l][mmax - i + l], m[i][l]
mmax -= 1
matrix_print(m)
def matrix_zero_col(m,c,i=0):
# columns example: m[i][0] = [1,0],[1,1],[1,2]...
for j in len(i, m[c][0]):
m[c][j] = 0
def matrix_zero_row(m,r,i=0):
# rows example: m[0][i] = [0,1][1,1][2,1]...
for j in len(i, m[0][r]):
m[j][r] = 0
def matrix_zero_out(m):
"""
Zero out rows and columns where zeros found in matrix
x,x,x,x x,x,0,x
x,x,0,x -> 0,0,0,0
x,x,x,x x x,0,x
"""
# defined is nxm matrix
if not m:
return
print "----------------------------------"
matrix_print(m)
trkRowZero = False
trkColZero = False
# set bool for tracking row and column
# column
for i in range(len(m[0])):
if m[0][i] == 0:
trkColZero = True
break
# row
for i in range(len(m)):
if m[i][0] == 0:
trkRowZero = True
break
#print "trkColZero:{} trkRowZero:{}".format(trkColZero, trkRowZero)
# find those zeros
# storing in tracking column and row as zeros
for i in range(1,len(m)):
for j in range(1,len(m[i])):
if m[i][j] == 0:
# found a zero - store at edges
# left edge - [0][j]
# top edge - [i][0]
m[0][j] = 0
m[i][0] = 0
# zero out cols (skip col 0 for now)
for i in range(1,len(m)):
if m[i][0] == 0:
for j in range(len(m[i])):
m[i][j] = 0
# zero out rows
# [0,1][1,1][2,1][3,1]
for i in range(1,len(m[0])):
if m[0][i] == 0:
for j in range(len(m)):
m[j][i] = 0
# zero out tracking column
if trkColZero is True:
for i in range(len(m[0])):
m[0][i] = 0
# zero out tracking row
if trkRowZero is True:
for i in range(len(m)):
m[i][0] = 0
print "----------------------------------"
matrix_print(m)
"""
Is substring
input string 1, string 2
Runtime O(n) assuming python 'in' is O(A+B)
"""
def is_string_rotation(str1, str2):
# concat strings (string 2 is the rotated string)
# example: terwa + terwa = terwaterwa
if not str1 or not str2:
return False
if len(str1) != len(str2):
return False
str_test = str2 + str2
if str1 in str_test:
return True
return False
## Run Tests
# ================================================================================
# Unique Characters
#print unique_characters_in_string('abcdefghijklmnop') # answer:True
#print unique_characters_in_string('abccdefghijklmnop') # answer:False
#print unique_character_in_string_tracker('abcdefghijklmnop') # answer: True
#print unique_character_in_string_tracker('abccdefghijklmnop') # answer: False
##print unique_character_in_string_bit('abcdefghijklmnop') # answer:True
##print unique_character_in_string_bit('abccdefghijklmnop') # answer:False
# String permutation
#print is_permutation('abcde', 'edcba') # answer:True
#print is_permutation('abcde', 'edxba') # answer:False
# URL-ify
#print "'{}'".format(urlify_spaces('Mr John Smith ', 13))
# Palindrones
#print find_palindrones('tacocat')
# One Away
#print string_one_away('abcd','abcd') # answer: False
#print string_one_away('abcd','ebcd') # answer: True
#print string_one_away('abcd','eecd') # answer: False
#print string_one_away('xx','x')
#print string_one_away('abcd','xabcd') # answer: True
#print string_one_away('abcd','axbcd') # answer: True
#print string_one_away('abcd','abcdx') # answer: True
# String Compression
#print string_compressor('')
#print string_compressor('a')
#print string_compressor('ab')
#print string_compressor('abbcccddddeeeee')
#print string_compressor('abbcccddddeeeeeffffffffffffffffffffffffffffffffffffffffffffffffff')
# N Matrix rotator (patater)
#matrix_rotate_left(matrix_create(4))
#matrix_rotate_right(matrix_create(4))
# 0 Matrix - zero out rows/cols with zeros
#zm = [[0,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,0]]
#matrix_zero_out(zm)
# String is substring
print is_string_rotation('waterbottle', 'erbottlewat') # answer: True
print is_string_rotation('shuzbut', 'nanonano') # answer: False
|
"""
Cracking the coding interview
Practice questions
Part 10. Sorting & Searching
"""
import unittest
"""
Helper functions
"""
def binarySearch(arr=[], var=0, lo=0, hi=0):
"""
binary search sorted array
"""
if lo > hi:
return False # base case - didn't find it!
mid = (hi + lo) / 2 # the binary part of binary search
if var == arr[mid]: # base case - found it!
return True
if var < arr[mid]:
return binarySearch(arr, var, lo, mid - 1) # going left
else:
return binarySearch(arr, var, mid + 1, hi) # going right
# testing binary search
#print binarySearch([1,2,3,4,5,6,7,8,9,10], 3, 0, 9)
"""
10.1
With two sorted arrays, merge sorted in fasted time possible
Note: first sorted array has extra blank space at end to accomodate the second array space
probably O(kn) - radix / bucket sort
Hints: start from end and work way to start
Initial thoughts (brute force approach - read through each array and compare ints, insert as we go)
If starting from end, can probably find biggest value and place at end of larger array and work to start
How to handle dups ?
"""
def sortMerge(arr01, arr02):
"""
Iterative approach to combining two sorted arrays into one sorted array
check if arr01 is larger by len(arr02) before proceeding
"""
# base - need array 01, 02
if not arr01 or not arr02:
return []
# base - array 02 can fit into array 01
# [None,None...] == [None,None...]
end_arr01 = arr01[(len(arr01) - len(arr02)):]
end_arr02 = [None] * len(arr02)
if end_arr01 != end_arr02:
return []
j = len(arr02) - 1 # starting end of array 02
k = len(arr01) - 1 # next available spot
s = len(arr01) - len(arr02) - 1 # start comparison index
for i in range(len(arr_01) - 1, -1, -1): # backwards through array 02
if i <= s: # found the int end of arr01
while arr01[i] < arr02[j] and j >= 0:
arr01[k] = arr02[j]
j -= 1
k -= 1
if i != k:
arr01[k] = arr01[i]
k -= 1
if j < 0:
break
print "array 01:", arr01
# arr_01 = [1,3,5,7,9,13,15,20,None,None,None,None]
# arr_02 = [2,8,14,21]
# sortMerge(arr_01, arr_02)
#
# arr_01 = [1,3,5,7,9,13,15,20,None,None,None,None]
# arr_02 = [2,8,21,22]
# sortMerge(arr_01, arr_02)
"""
10.2
"""
def sortAnagram(anagram=[]):
"""
sorting strings of anagrams
place each anagram next to each other, not necessairly in order
anagrams 'cat', 'tac' etc...
"""
if not anagram:
return []
c_hash = {}
o_anagrams = []
for i, s in enumerate(anagram): # each string
c_count = 0
for c in s: # each char in string
c_count += ord(c)
if c_count in c_hash:
c_hash[c_count].append(i) # [1,2,i] - add to list
else:
c_hash[c_count] = [i] # [i] - start new list
for h in c_hash: # all hashes with grouped string counts
for i in c_hash[h]: # list of indexes
# for now just creating a new list of anagrams
o_anagrams.append(anagram[i])
return o_anagrams
# arr_anagrams_t01 = ['cat','dog','hydroxydeoxycorticosterones','ant','god','nat','tac','antler','hydroxydesoxycorticosterone','learnt','rental']
# arr_anagrams_t02 = ['cat','dog','ant','god','nat','tac']
# print sortAnagram(arr_anagrams_t02)
# class sortAnagramTest(unittest.TestCase):
#
# def setUp(self):
# self.anagram = ['cat','dog','ant','god','nat','tac']
# self.result = ['cat','tac','dog','god','ant','nat']
#
# def test_sort_anagram(self):
# self.assertEqual(sortAnagram(self.anagram), self.result)
"""
10.3
Search a rotated array of n integers. sorted in increasing order.
probably use binary search for a large array, could look for min element and then binary search
with start at index ?
[50....100, 1....49]
looking for 70, less than 100 - binary search 0 to index @ 100 etc...
"""
def rotatedSearch(arr=[], val=0):
"""
search a rotated array
need to look for min, track index - do comparison then binary search on correct half
"""
if not arr:
return False
prev_i = None
#for i,v in enumerate(arr):
for i in range(0, len(arr)):
if prev_i and arr[prev_i] > arr[i]:
# stop, we found the min
break
prev_i = i
if val > arr[0]:
return binarySearch(arr, val, 0, prev_i)
else:
return binarySearch(arr, val, prev_i + 1, len(arr) - 1)
# arr_rotated_t01 = [15,16,19,20,25,1,3,4,5,7,10,14]
# arr_rotated_t02 = [15,16,19,20,25]
# print rotatedSearch(arr_rotated_t01, 20)
# class rotatedSearchTest(unittest.TestCase):
#
# def setUp(self):
# self.data = [15,16,19,20,25,1,3,4,5,7,10,14]
#
# def test_search_rotated_found(self):
# self.assertEqual(rotatedSearch(self.data, 3), True)
#
# def test_search_rotated_notfound(self):
# self.assertEqual(rotatedSearch(self.data, 2), False)
"""
10.4
Find a value in a sorted structure 'Listy' with no known length
0(1) lookups, positive ints in order
Initial thoughts:
# binary search requires that an end index (hi bound) be known in order to calculate a mid
# could do random index search by binary searching for index, start at 10k, if -1 then mid that until not -1
if not -1 then square 10K until -1, then back to binary
# could check memory size of table and take a guess at how big the table is
# even just walking through the table would be a worse case of O(n), a billion ints could pose a problem
# table of 2^2
2, 4, 8, 16, 32, 64, 128, 256, 512...... 2^32:1 billion(ish)
Hints:
"""
class theListy(object):
"""
Listy only contains sorted, positive integers
only contains method to get element at i
Use class theListy to find the index where a value occurs in the 'list'
"""
def __init__(self, arr=[]):
self.arr = arr
def elementAt(self, i):
"""
default behavior for listy
can return a value, if outside of bounds return -1
"""
if i < 0:
return None
if i > (len(self.arr) - 1):
return -1
return self.arr[i]
def findEnd(self):
"""
find end of listy
increment end index by powers of 2 that grow very rapidly
binary search will help us narrow down that elusive end
"""
powerof2 = 1
prevIndex = 0
foundIndex = -1
while foundIndex < 0:
nextIndex = 2**powerof2
#print "foundIndex({},{})".format(prevIndex, nextIndex)
foundIndex = self.binarySearchEnd(prevIndex, nextIndex)
prevIndex = nextIndex + 1
powerof2 += 1
# special case - if we don't find the end, prevent infinite looping
if self.elementAt(prevIndex) < 0:
break
# returns index of end of listy, -1 if we didn't find it (should always find it!)
return foundIndex
def binarySearchEnd(self, lo, hi):
"""
binary search until [int,-1] found
"""
if lo > hi:
return -1 # base case - didn't find it!
mid = (hi + lo) / 2 # the binary part of binary search
#print "testing... [{},{}] & [{},{}]".format(self.elementAt(mid-1), self.elementAt(mid), self.elementAt(mid), self.elementAt(mid+1))
if self.elementAt(mid-1) > -1 and self.elementAt(mid) == -1: # base case - found end of list
#print "returning mid-1"
return mid-1
elif self.elementAt(mid) > -1 and self.elementAt(mid+1) == -1:
#print "returning mid"
return mid
if self.elementAt(mid) < 0:
return self.binarySearchEnd(lo, mid - 1) # going left
else:
return self.binarySearchEnd(mid + 1, hi) # going right
def binarySearchVal(self, lo, hi, val=0):
"""
binary search until [int,-1] found
"""
if lo > hi:
return -1 # base case - didn't find it!
mid = (hi + lo) / 2 # the binary part of binary search
#print "testing... [{},{}] & [{},{}]".format(self.elementAt(mid-1), self.elementAt(mid), self.elementAt(mid), self.elementAt(mid+1))
if self.elementAt(mid) == val: # base case - found it!
return mid
if self.elementAt(mid) > val:
return self.binarySearchVal(lo, mid - 1, val) # going left
else:
return self.binarySearchVal(mid + 1, hi, val) # going right
def valIndexListy(arr=[], val=0):
"""
trying out powers of 2 to find the end, then when -1, binary search until [int,-1] found
"""
if not arr or val < 0:
return None
thisListy = theListy(arr)
endIndex = thisListy.findEnd()
if endIndex >= 0:
# not to find the index of the actual value
return thisListy.binarySearchVal(0, endIndex, val)
# arr_long_t01 = [1,2,3,4,6,6,7,8,9,10]
# print valIndexListy(arr_long_t01, 6)
# class valIndexListyTest(unittest.TestCase):
#
# def setUp(self):
# self.data = [1,2,3,4,5,6,7,8,9,10]
#
# def test_val_index_listy(self):
# self.assertEqual(5, valIndexListy(self.data, 6))
"""
10.5
Sparse search - search an array of sorted strings, sprinkled with empty spots
Thoughts:
# probably emphasizing that the array is sorted, why the empty spots ?
# binary search, possible since strings are sorted - although > < on space would impede outcome
# can't get rid of spaces since we need to track index - could store in a hash then search, assuming no dups
this would increase time O(n) in moving to hash, then run binary search @ O(logn)
Example: ball in ("at","","","","ball","","","car","","","dad","","") = 4
Going for the hashed, binary search option - here we go!
"""
def valIndexSparseList(arr=[], val=''):
"""
find value in sparse list of sorted strings
moving all strings to hash, tracking indexes - removing blank spaces
hash is a O(1) search - no need to binary search it, return val will be index!
I'm sure it's got to be harder than this, this a first go
** very much assuming there aren't any duplicate strings
** runtime O(n) - not great
"""
if not arr or not val:
return None
hash_strings = {}
#for i,v in enumerate(arr):
for i in range(0, len(arr)):
hash_strings[arr[i]] = i
# now find the value in hash and return it's index
if val in hash_strings:
return hash_strings[val]
#arr_strings_t01 = ["at","","","","ball","","","car","","","dad","",""]
#print valIndexSparseList(arr_strings_t01, "ball")
# class valIndexSparseListTest(unittest.TestCase):
#
# def setUp(self):
# self.data = ["at","","","","ball","","","car","","","dad","",""]
#
# def test_val_in_sparse_list(self):
# self.assertEqual(4, valIndexSparseList(self.data, 'ball'))
"""
10.6
Sort a 20GB file consisting of one string per line
Explain how to go about sorting
Thoughts: consider how long each string is per line. if smallish then possibly store all
How many list items for 20GB of strings that are
20GB = 21,000,000,000 bytes
1 char is 8 bits (1 byte)
10 chars per line = 2,100,000,000 lines (that's 2.1 BILLION lines ... holy spa-kolee)
Any chance to sort the file in place ? ... like
"""
import os
import random
def create1GBIntFile():
"""
generate file to gb_goal size
"""
file_name = 'file_of_ints.txt'
gb_bytes = 1073741824 # number of bytes (per st_size) in a GB
gb_goal = 1 # number of GB to generate
if not os.path.isfile(file_name): # only create the file once
file_conn = open(file_name, 'w')
file_size = os.stat(file_name).st_size
file_gb = file_size / gb_bytes
while file_gb < gb_goal:
file_size = os.stat(file_name).st_size
file_gb = file_size / gb_bytes
file_conn.write("{}\n".format(random.randint(0, 1000000000)))
import heapq
import contextlib
def mergeFiles(inFiles=[]):
"""
merge multiple sorted files using a pythong heap library
"""
files = [open(fn) for fn in inFiles]
with contextlib.nested(*files):
with open('output', 'w') as f:
f.writelines(heapq.merge(*files))
def externalSort(f=None):
"""
read file in chunks, process with quicksort, write back go on until done
at the end combine all chunks
"""
if not f:
return None
pass
#create1GBIntFile()
"""
10.7
a) find missing int in 4 billion non-negative ints with 1gb ram
Note: pip install bitstring then
'from bitstring import BitArray, BitString'
creating bit vector 'vector = BitArray(2**31)'
then manipulate the array of bits from there
b) find missing int in 1 billion non-negative unique ints with 10mb ram
"""
# part 1, missing in 4 billion random positive ints (not necessairly unique)
import numpy as np
from bitstring import BitArray # need to use a BitArray to store bits as ints to save space
import random
import sys
import time
def gen4BillIntsImports():
"""
going to generate 4 billion random ints and put them directly into the bitstring bit vector
this is a pseudo read from file thing, to save space and time in generating and then reading a very large file
"""
time_start = time.time()
# bit_vector = BitArray(4000000000)
# going to need to loop 4 billion times - this might take a minute or two
# Note: 8 seconds for 1 million
# Speed on a mac - a million rows @ 6 sec * 2000 (to get to 2 billion) = 3.33 hours to complete = no bueno
# how can this be sped up?
# for i in xrange(0, 2**31):
# if i % 1000000 == 0:
# print "{} @ {} seconds".format(i, time.time() - time_start)
# bit_vector[random.randint(0, (2**31 - 1))] = 1
## iterating through bit_vector - even slower
# for i, b in enumerate(bit_vector):
# if i % 1000000 == 0:
# print "{} @ {} seconds".format(i, time.time() - time_start)
# bit_vector[i] = random.randint(0, 1)
# print "size of bit_vector:", sys.getsizeof(bit_vector)
# for i in range(0, 100):
# print bit_vector[i]
## numpy
# numpy_bits = np.random.randint(256, size=(1000000000//8,)).astype(np.uint8)
#
# def get_bools(a, i):
# b = i // 8
# o = i % 8
# mask = 1 << o
# return (a[b] & mask) != 0
#
# for i in range(999999500, 1000000000):
# print get_bools(numpy_bits, i)
#
# time_end = time.time()
# print("--- %s seconds ---" % (time_end - time_start))
def findMissingInt1GB():
"""
using bytes as 32 bit containers
need 4 billion bits as ints (depicted by index // 32) e.g. a[0][1]....[31] is one int storing 32 placeholders
4 billion / 32 = 125000000 ints = 4 bytes * 125 million bytes = .12 GB
Note: not reading in 4 billion ints, not looping 125 million times - this test shows working method
should produce file that is .93 GB when running full steam
"""
#bit_vector = range(125000000) # large enough to hold 4 billion bits
bit_vector = range(31250) # large enough to hold 1 million bits - TESTING
for i in bit_vector:
# assigning random number to each index, this will be random integer by bits
bit_vector[i] = random.randint(2147483647, 2**31) # all positive ints
print "generated 1 billion ints with size:{}... yikes... now look for missing int".format(sys.getsizeof(bit_vector))
for i in range(0, len(bit_vector)):
next_bit = bit_vector[i]
for j in range(0, 32):
if (next_bit >> j == 0):
int_missing = (i * 32) + j
print "missing int {} @ bit_vector[{}]:{} {}... done and done!".format(int_missing, i, next_bit, bin(next_bit))
return
def findMissingInt10MB():
"""
Note:
1 billion non-negative, unique, integers
data:
Need space for bit_bucket, how many bits is that when a bit represents an int
bytes in 1MB is 2**20, in 10MB is 2**20 * 9 (for wiggle room)
1 billion / (2**20 * 9MB * 8bits) = 75 Million bits
1 billion / 75 Million bits = 15 buckets
bit vector
size is 75 million bits / 8 bits per byte / 4 bytes per int = 2.5 million ints (2343750) to be exact
"""
# buckets
bit_bucket = {}
bit_bucket_count = 0
for i in range(0, 15):
bit_bucket_count += 75000000
if bit_bucket_count <= 1000000000:
bit_bucket_size = 75000000
else:
bit_bucket_size = 1000000000 - (bit_bucket_count - 75000000)
bit_bucket[i] = [bit_bucket_size ,0]
if bit_bucket_count >= 1000000000:
break
# open file for reading and read 80 million lines - real, real slow like
# fill those bucket counts bucket [0](0 to 79999999 million), [1](80000000 to 159999999 million) etc...
with open('file_of_14712434_ints.txt', 'r') as f:
for line in f:
up_int = line # integer
up_bucket = int(up_int) // 75000000 # bucket
bit_bucket[up_bucket][1] += 1 # increment bucket count
f.close()
# now find the missing int using bit vector logic with a zero bit
bit_bucket_missing = None
for i in range(0, len(bit_bucket)):
print "comparing bit_bucket {} < {}".format(bit_bucket[i][1], bit_bucket[i][0])
if bit_bucket[i][1] < bit_bucket[i][0]: # counts don't savvy
bit_bucket_missing = i
break
# build then read bits into vector
if bit_bucket_missing is not None:
bit_bucket_range = bit_bucket[i][0] / 32
bit_vector = range(bit_bucket_range)
else:
print "no integers missing!"
return
# read the file again, this time filling in bits in this range
with open('file_of_14712434_ints.txt', 'r') as f:
for line in f:
up_int = int(line)
bit_index = up_int // 75000000
if bit_index == bit_bucket_missing:
bit_block = (up_int - (75000000 * bit_index)) / 32
bit_shift = (up_int - (75000000 * bit_index)) - (32 * bit_block)
bit_vector[bit_block] |= 1 << bit_shift
#print "up_int:", up_int, "bit_index:", bit_index, " bit_block:", bit_block, " bit_shift:", bit_shift
#print "set bit_vector[{}] |= 1 << {}".format(bit_block, bit_shift)
f.close()
# Test view first 100 integers (binary parts)
#for i in range(0, 100):
# print bin(bit_vector[i])
# find first zero in binary parts of bit_vectors
for i in range(0, len(bit_vector)):
next_bit = bit_vector[i]
for j in range(0, 32):
if (next_bit >> j == 0):
bit_integer_missing = bit_bucket_missing * 75000000 + (i * 32) + j
print "missing int {} @ bit_vector[{}]:{} {}... done and done!".format(bit_integer_missing, i, next_bit, bin(next_bit))
return
def fillBits():
"""
Test to OR bits to 1 on command
"""
bit_array = [0]
for i in range(0,32):
bit_array[0] |= 1 << i
print i, bin(bit_array[0]), bit_array
#fillBits()
#findMissingInt1GB()
#findMissingInt10MB()
"""
10.8
Find and print all duplicate ints where n is 1 to max 32,000
This must be done in 4kB
4kB = 2^10 * 4 bytes = 4096 bytes
an int is 4 bytes - 4kB of ints is 4096 / 4 ints = 1024 ints
fudge room - make it 1000 ints at a time
although, using bits as ints could squeeze 4096 bytes * 8 bits = 32768 bits
so... using a bit vector, could store all 32K and check for bit shift that is already set to 1
"""
# exercise: bit_vector class
class BitVector(object):
"""
bit vector class
load read, write and test if already set (isset)
"""
def __init__(self, size=0):
"""
input size of data
size is based on 32 bits per int in 4 bytes, although python uses bit int which is 64 bits in 8 bytes
data will be a list of ints based on input bit size
"""
self.size = size
self.int_index = 0
self.bit_index = 0
if size % 64 != 0:
raise ValueError('input size must be an incremental size of 64')
self.data = range(size // 64)
def bit_r(self, idx):
"""
read a bit, parm: integer in range
"""
self.bit_inrange(idx)
return self.data[self.int_index] >> self.bit_index
def bit_w(self, idx):
"""
write a bit, parm: integer in range
"""
self.bit_inrange(idx)
self.data[self.int_index] |= 1 << self.bit_index
def bit_isset(self, idx):
"""
return True or False if bit might have already been set
"""
self.bit_inrange(idx)
if self.data[self.int_index] >> self.bit_index == 1:
return True
else:
return False
def bit_inrange(self, idx=None):
"""
evaluate if integer is in range of bit vector
int should be in range 0 to 64 * int .. e.g., bit = (32000 / 64) - 1 = 500
"""
if idx is None or type(idx) is not int:
raise ValueError('an integer must be passed in order to execute this bit class. passed in {}'.format(idx))
# idx - 1 because range starts at 1 where bit starts at zero
##
# test: 64. int_index (64 - 1) // 64 = 0 (should be zero)
# bit_index (64 - 1) - (0 * 64) (should be 63)
self.int_index = (idx - 1) // 64
self.bit_index = (idx - 1) - (self.int_index * 64)
# TEST - Errors
# if self.int_index < 0:
# print "error self.int_index:", self.int_index
# if self.bit_index < 0 or self.bit_index > 63:
# print "error: self.bit_index:", self.bit_index
if self.int_index <= self.size:
return True
else:
raise ValueError('integer outside of bounds of bit vector. range should be 0 to {}'.format(64 * self.size))
# part 1 - build the randomized test list 1 to random n up to 32K
def findDupIntGen():
"""
generate list of ints 1 to max 32,000
return list
note: not counting this as part of the memory,
the meat of the program could be reading this as a text file etc...
note: list can be of any length, that wasn't specified
"""
list_ints = []
for i in range(10000):
list_ints.append(random.randint(1, 32000))
return list_ints
# part 2 - find any duplicates in the randomized list
def findDupIntUtil(a=[]):
"""
find duplicate int in a
use a bit vector to store 4kB
bit_vector = 1 int = 4 bytes * 8 bits = 1000 ints
Note: on mac an int is 8 bytes (big int - 64 bits) in size therefore only need 500 ints
"""
if not a:
return []
int_duplicate = []
bits = BitVector(32000)
for i in a:
if bits.bit_isset(i):
int_duplicate.append(i)
else:
bits.bit_w(i)
# bit_vector = range(500) # should be 4072 bytes / 2^10 = 3.97kB .. perfecto!
# for i in a:
#
# int_index = (i // 64) # which int in the vector: e.g., 63 // 64 = 0, 64 // 64 = 2, 128 // 64 = 2 etc...
# bit_index = i - (int_index * 64) # which bit in the int: e.g. 63 - (0 * 64) = 63, 64 - (1 * 64) = 1, 128 - (2 * 64) = 0
#
# if bit_vector[int_index] >> bit_index == 1:
# int_duplicate.append(i)
# else:
# bit_vector[int_index] |= 1 << bit_index
return int_duplicate
def findDupInt():
print "duplicate integers found:", findDupIntUtil(findDupIntGen())
#findDupInt()
# part 3 - take a break, you earned it buddy!
def takeABreak():
coffee = "triple shot americano"
scone = "blueberry"
newspaper_pages = "funnies"
print "I am drinking a {} while eating a {} and reading the {} in the newspaper".format(coffee, scone, newspaper_pages)
"""
10.9
Find a value in an MxN matrix best time complexity
"""
def matrixSectionUtil(m, v=None, p1=[None, None], p2=[None, None]):
"""
Break grid into sections until value found / not found
half grid each time until width or height is 1
assume m, v, p1, p2 passed from caller
m:matrix
v:value
p1:point 1
p2:point 2
example call matrixSection(m, 22, [0,0], [10,10])
0,0
0,1
0,2 10,9
...........10,10
time best O(1), average O(n) n/4 + n/4 ... O(n)
"""
#print "matrixSectionUtil p1:{}:{} p2:{}:{}".format(p1, m[p1[0]][p1[1]], p2, m[p2[0]][p2[1]])
# in range - not necessairly always in this block though
if v >= m[p1[0]][p1[1]] and v <= m[p2[0]][p2[1]]:
# note: matrix stored as [v:down, h:right]
# find mid point - horizontal & vertical
h_mid = (p2[1] - p1[1]) // 2
v_mid = (p2[0] - p1[0]) // 2
h_len = len(m[0]) - 1
v_len = len(m) - 1
# corner(s) check
# could be 2x2, 1x1 square - easier to just check these options first
if p1[0] <= v_len and p1[1] <= h_len:
if v == m[p1[0]][p1[1]]: # upper left pixel
return [p1[0], p1[1]]
if p1[0] <= v_len and p2[1] <= h_len:
if v == m[p1[0]][p2[1]]: # upper right pixel
return [p1[0], p2[1]]
if p2[0] <= v_len and p1[1] <= h_len:
if v == m[p2[0]][p1[1]]: # lower left pixel
return [p2[0], p1[1]]
if p2[0] <= v_len and p2[1] <= h_len:
if v == m[p2[0]][p2[1]]: # lower right pixel
return [p2[0], p2[1]]
# block in 2x2. if value not found, return None to prevent recursion overload
if p2[0] - p1[0] <= 1 and p2[1] - p1[1] <= 1:
return None
# upper left
qp1 = [p1[0], p1[1]]
qp2 = [p2[0] - h_mid, p2[1] - v_mid]
pv = matrixSectionUtil(m, v, qp1, qp2)
if pv is not None:
return pv
# upper right
qp1 = [p1[0], p1[1] + h_mid]
qp2 = [p2[0] - v_mid, p2[1]]
pv = matrixSectionUtil(m, v, qp1, qp2)
if pv is not None:
return pv
# lower left
qp1 = [p1[0] + h_mid, p1[1]]
qp2 = [p2[0], p2[1] - v_mid]
pv = matrixSectionUtil(m, v, qp1, qp2)
if pv is not None:
return pv
# lower right
qp1 = [p1[0] + h_mid, p1[1] + v_mid]
qp2 = [p2[0], p2[1]]
pv = matrixSectionUtil(m, v, qp1, qp2)
if pv is not None:
return pv
else:
return None
def matrixSection(m, v):
"""
Calling matrix section utility
matrixSectionUtil(matrix, value to find, upper left point p1, lower right point p2)
"""
print "matrixSection: found {} @ {}".format(v, matrixSectionUtil(m, v, [0,0], [len(m)-1, len(m[0])-1]))
#mn = [[120]]
# mn = [[118],
# [120]]
mn = [[5,20,70,85],
[20,35,80,95],
[30,55,95,105],
[40,81,100,120],
[50,86,102,125]]
# matrixSection(mn, 5)
# matrixSection(mn, 85)
# matrixSection(mn, 125)
# matrixSection(mn, 50)
# matrixSection(mn, 81)
def matrixStepUtil(m, v):
"""
search matrix using the step method
start upper right
is value larger, go left
if value smaller, go down
time avg less than O(m+n), worst O(m+n)
"""
upper_right_index = len(m[0]) - 1
h_index = 0
v_index = upper_right_index
while h_index >= 0 and v_index <= len(m) - 1:
if v == m[h_index][v_index]:
return [h_index, v_index]
elif m[h_index][v_index] > v:
# go left
v_index -= 1
else:
# go down
h_index += 1
def matrixStep(m, v):
print "matrixStep find:{} result:{}".format(v, matrixStepUtil(m, v))
#matrixStep(mn, 100)
# class matrixStepTest(unittest.TestCase):
#
# def setUp(self):
# self.mn = [[5,20,70,85],
# [20,35,80,95],
# [30,55,95,105],
# [40,81,100,120],
# [50,86,102,125]]
#
# def test_matrix_step(self):
# self.assertEqual(matrixStepUtil(self.mn, 100), [3, 2])
#
# def test_matrix_section(self):
# self.assertEqual(matrixSectionUtil(self.mn, 100, [0,0], [len(self.mn)-1, len(self.mn[0])-1]), [3, 2])
"""
10.10
Stream of integers, find rank of number in stream (number of values less than queried)
stream: 5, 1, 4, 4, 5, 9, 7, 13, 3
order: 1, 3, 4, 4, 5, 5, 7, 9, 13
getRankOfNumber(1) = 0
getRankOfNumber(3) = 1
getRankOfNumber(4) = 3
naive approach: sort (radix) for O(kn) complexity, then return index of last occurance of value
solution: binary search tree. keep track of how many nodes at root in left sub-tree
time complexity of self.bst is O(logn) for insert, find
will need to keep track of the number of nodes inserted under another node
test: won't go into re-creating a BST insert, just assume that all nodes already set
"""
def bstSize(n):
"""
count number of nodes in defined n
breadth first traversal - queue
time complexity O(n) - visits every node
"""
if not n:
return 0
count = 1
queue = []
# not counting root node, queue up left and right from root
if n.left:
queue.append(n.left)
if n.right:
queue.append(n.right)
while queue:
current = queue.pop()
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
count += 1
return count
def bstGetRankOfUtil(n, v):
"""
get rank of v(value)
using bst best practices, value greater go right, else go left
value found: add all left from value to count and return
value left: go left - nothing added to count
value right: go right, add 1 + all lefts passed
"""
count_rank = 0
current = n
while current is not None:
if current.data == v:
# increment rank with skipped left
size_left = bstSize(current.left)
#print "size_left of {} is {}".format(current.data, size_left)
count_rank += size_left
return count_rank
elif v > current.data:
# increment rank with skipped left
size_left = bstSize(current.left)
#print "size_left of {} is {}".format(current.data, size_left)
count_rank += 1 + size_left
# go right
current = current.right
else:
# go left
current = current.left
class node(object):
"""
node object, store data, left, right,
"""
def __init__(self, data=None, right=None, left=None):
self.data = data
self.left = left
self.right = right
# test node v1
# stream: 3,1,2,4,4,5,5
# in ord: 1,2,3,4,4,5,5
bst = node(3)
bst.left = node(1)
bst.left.right = node(2)
bst.right = node(4)
bst.right.left = node(4)
bst.right.right = node(5)
bst.right.right.left = node(5)
# test node v2
# stream: 5,1,4,4,5,9,7,13,3
# in ord: 1,3,4,4,5,5,7,9,13
bst = node(5)
bst.left = node(1)
bst.left.right = node(4)
bst.left.right.left = node(4)
bst.left.right.left.left = node(3)
bst.left.right.right = node(5)
bst.right = node(9)
bst.right.left = node(7)
bst.right.right = node(13)
def bstGetRankOf(n, v):
"""
calling program to util
"""
print "bstGetRankOf value:{} result:{}".format(v, bstGetRankOfUtil(n, v))
# bstGetRankOf(bst, 1)
# bstGetRankOf(bst, 3)
# bstGetRankOf(bst, 4)
# bstGetRankOf(bst, 5)
# bstGetRankOf(bst, 13)
# class bstGetRankOfTest(unittest.TestCase):
#
# def setUp(self):
# """
# Test Node:
# (5)5
# (0)1 (7)9
# (3)4 (6)7 (8)13
# (2)4 (4)5
# (1)3
# """
# self.bst = node(5)
# self.bst.left = node(1)
# self.bst.left.right = node(4)
# self.bst.left.right.left = node(4)
# self.bst.left.right.left.left = node(3)
# self.bst.left.right.right = node(5)
# self.bst.right = node(9)
# self.bst.right.left = node(7)
# self.bst.right.right = node(13)
#
# def test_ranks(self):
# self.assertEqual(bstGetRankOfUtil(self.bst, 1), 0)
# self.assertEqual(bstGetRankOfUtil(self.bst, 3), 1)
# self.assertEqual(bstGetRankOfUtil(self.bst, 7), 6)
# self.assertEqual(bstGetRankOfUtil(self.bst, 5), 5)
"""
10.11
Peaks and Valley in array of ints
peak when adjacent are smaller
valley when adjacent are larger
brute force approach:
O(n) walk through array
when the next value is greater (keep last value in storage), the stored value is valley
when the next value is lesser (......), the stored value is a peak
store peaks and valleys in extra space, all others in extra space
at the end tie the two extras into one and return
"""
def pandvBF(a):
"""
peaks and valleys Brute Force
time complexity O(n), extra space O(n) - don't see it getting faster than that
issues with this method - not peak then valley, can be valley then peak
"""
if not a:
return []
curr_int = a[0] # first in in array
curr_dir = None # lt, gt
p_and_v = [] # peak and valley storage
the_rest = [] # everything else storage
#print "curr_int:{} curr_dir:{}".format(curr_int, curr_dir)
for i in range(1, len(a)):
if a[i] == curr_int:
#print "a[i]:{} == curr_int:{}".format(a[i], curr_int)
# no change - at to the regular pile
#print " append all the rest {}".format(curr_int)
the_rest.append(a[i])
elif a[i] > curr_int:
#print "a[i]:{} 'gt' curr_int:{}".format(a[i], curr_int)
if curr_dir is None or curr_dir == "lt":
# switching from less to greater - curr_int is peak
#print " re-direction append {} to p_and_v".format(curr_int)
p_and_v.append(curr_int)
else:
#print " append all the rest {}".format(curr_int)
the_rest.append(curr_int)
curr_dir = "gt"
curr_int = a[i]
else:
#print "a[i]:{} 'lt' curr_int:{}".format(a[i], curr_int)
if curr_dir is None or curr_dir == "gt":
# switching from greater to less - curr_int is valley
#print " re-direction append {} to p_and_v".format(curr_int)
p_and_v.append(curr_int)
else:
#print " append all the rest {}".format(curr_int)
the_rest.append(curr_int)
curr_dir = "lt"
curr_int = a[i]
#print "curr_int:{} curr_dir:{} a[i]:{}".format(curr_int, curr_dir, a[i])
#print "p_and_v:", p_and_v, " the_rest:", the_rest
p_and_v = p_and_v + the_rest
p_and_v.append(a[-1]) # last element in array, since looking 1 behind need to tack on
return p_and_v
def pandvSwap(a):
"""
peak and valley swapper
walk through array, if p or v out of order (defined peak(larger), then valley(smaller))
swap from adjacent elements, or however many are left to the end of the array
e.g. [1,3,2] - 1 is a valley, from None <- 1 -> 3 - switch with 3 ==> [3,1,2]
runtime O(n), no extra space
"""
if not a:
return []
def swap(i, y):
"""
swap value @ index i for y
"""
print "it's swap time! {} for {}".format(a[i], a[y])
if (i < 0 or i > len(a) - 1) and (y < 0 or y > len(a) - 1):
return
temp = a[i]
a[i] = a[y]
a[y] = temp
prev_i = 0
curr_d = "v" # peaks first!
for i in range(1, len(a)): # loop through, skip 2
if curr_d == "p":
# peaks
if a[prev_i] > a[i]:
# need to swap
swap(prev_i, i)
curr_d = "v"
else:
# valleys
if a[prev_i] < a[i]:
# need to swap
swap(prev_i, i)
curr_d = "p"
prev_i = i
return a
l01 = [5,8,6,2,3,4,6] # where [8,6] are peaks and [5,2] are valleys
l02 = [5,3,1,2,3] # p:5 v:1 -> [5,1,3,2,3]
#print pandvBF(l01)
print pandvSwap(l01)
######## unit test ########
if __name__ == '__main__':
unittest.main()
|
"""
Cracking the coding interview
Practice questions
Part 3. Stacks and Queues
"""
"""
Helper Code
"""
"""
3.1
Create 3 stacks from one array
Initial brute force thoughts - array list of array ? - array in an array... this wouldn't be one array though... maybe?
brute force #2 - create large array and allocate space in thirds for three stacks
** issues might be when pop, array will shrink
could just Null out space where pop occured to keep array the same length
** limit on stack space .. or double (triple) size of array
** shrinking would require checking all stacks for space constraints
pop: [1,2,3|4,5,6|7,N,N] -> pop() second stack = 6 -> [1,2,3|4,5,N|7,N,N]
grow: [1,2|3,4|5,6] -> grow, triple -> [1,2,N,N|3,4,N,N|5,6,N,N]
assume: not allowed to grow - return error if adding to stack and full
using a third of space only - not sharing space with other stacks
"""
class stackThreeContainer(object):
def __init__(self):
self.container = [] # array, list etc...
self.stackLength = {} # lengh to each stack
self.stackLength[1] = 0
self.stackLength[2] = 0
self.stackLength[3] = 0
self.numberOfStacks = 3
self.numberOfElements = 5
self.minValue = []
self.create_container(self.numberOfStacks * self.numberOfElements)
def create_container(self, n):
if not n or type(n) is not int:
raise ValueError('invalid integer passed to create array')
self.container = [None] * n
def print_container(self):
print self.container
def push(self, stack, value):
if not stack or type(stack) is not int:
raise ValueError('invalid stack value passed')
if stack < 1 or stack > 3:
raise ValueError('invalid stack number passed')
if not value:
raise ValueError('no value passed to push onto stack')
stack_start = self.numberOfElements * (stack - 1)
stack_end = stack_start + self.numberOfElements
stackLength = self.stackLength[stack]
if stackLength >= self.numberOfElements:
raise ValueError('cannot push any more values onto stack')
else:
pushIndex = stackIndex = stack_start + stackLength
self.setMin(value)
self.container[pushIndex] = value
self.stackLength[stack] += 1
# Note - min only takes into account entire container for question #2
def setMin(self, value):
if self.minValue:
if value < self.minValue[-1] and value != self.minValue[-1]:
self.minValue.append(value)
else:
self.minValue.append(value)
def popMin(self, value):
if self.minValue:
if value == self.minValue[-1]:
self.minValue.pop()
def getMin(self):
return self.minValue[-1]
def pop(self, stack):
# Note stack starts @ 1 to number of stacks, not zero
# note stack length from 0 to self.stackLength
if not stack or type(stack) is not int:
raise ValueError('invalid stack value passed')
if stack < 1 or stack > 3:
raise ValueError('invalid stack number passed')
# stack 1 with length 5 (0,1,2,3,4)
# stack 2 with length 5 (5,6,7,8,9) etc...
# 1 2 3 4 5 stack index
stack_start = self.numberOfElements * (stack - 1)
stack_end = stack_start + self.numberOfElements
stackLength = self.stackLength[stack]
if stackLength:
# stackIndex @ stack 2 of length 5 and stackLength = 1
# stack_start = 5 + stackLegth = 1; -1 = 5 ... good to go!
stackIndex = (stack_start + stackLength) - 1
stackValue = self.container[stackIndex]
self.popMin(stackValue)
self.container[stackIndex] = None
self.stackLength[stack] -= 1
return stackValue
else:
# nothing in stack
return None
def peek(self, stack):
# Note stack starts @ 1 to number of stacks, not zero
# note stack length from 0 to self.stackLength
if not stack or type(stack) is not int:
raise ValueError('invalid stack value passed')
if stack < 1 or stack > 3:
raise ValueError('invalid stack number passed')
# stack 1 with length 5 (0,1,2,3,4)
# stack 2 with length 5 (5,6,7,8,9) etc...
# 1 2 3 4 5 stack index
stack_start = self.numberOfElements * (stack - 1)
stack_end = stack_start + self.numberOfElements
stackLength = self.stackLength[stack]
if stackLength:
# stackIndex @ stack 2 of length 5 and stackLength = 1
# stack_start = 5 + stackLegth = 1; -1 = 5 ... good to go!
stackIndex = (stack_start + stackLength) - 1
stackValue = self.container[stackIndex]
return stackValue
else:
# nothing in stack
return None
# Test - 3 stacks in one array
# s = stackThreeContainer()
# #s.push(1, 'a')
# s.push(2, 'd')
# s.push(1, 'b')
# s.push(3, 'e')
# s.push(3, 'f')
# s.push(3, 'g')
# s.push(3, 'h')
# s.push(3, 'i')
# #s.push(3, 'j') # generate error
# s.push(1, 'c')
# s.print_container()
# print s.pop(1) # return c
# print s.pop(2) # return d
# print s.pop(2) # return None
# s.print_container()
# print s.peek(1) # print b
# print s.peek(2) # print None
# print s.peek(3) # print i
"""
3.2
Stack - return minimum element
Notes: push, pop, peek & min should all run in O(1) time
Brute force - store everything in a min heap. Problem in storage for min heap is avg. O(nlogn)time - no bueno
Or - track smallest value that is pushed onto stack in another variable. Return on min call.
"""
# lazy integration into above 3 stack
#print "min",s.getMin()
"""
3.3
Stack of plates - don't let them get too high! - create a new stack, etc.. as they are stacked
allow pop to pop top from any stack if defined, else from last stack
||||||| |||||||| |||||| - don't break any!
** unlimited stacks, pop from last stack
** thinking I can store stacks in a stack (list of lists) [0:[],1:[],2:[]]
** this data structure doesn't clean up empty stacks if popAt removes all plates from stack
** need to know if any under filled stacks should be filled first - if plates, yes ... if data that needed order then no
since this analogy is plates, just fill in non full stacks first.
plates are too heavy and valuable to move over so leave empty sub-stack spaces empty
"""
class setOfStacks(object):
def __init__(self):
self.stackHeight = 10
self.mainStack = []
self.subStackLength = {} # dict container for sub-stack size e.g., 0:10, 1:8 etc...
self.lastStack = None # last sub-stack in list ... not sure if I'll need this... integer value
#self.minStack = {None:None} # stack with minimum number of plates key:val
#self.maxStack = {None:None} # stack with maximum number of plates key:val
def print_container(self):
print self.mainStack
print self.subStackLength
def peek(self):
pass
def pop(self):
# pop from last available stack ? - easiest (going with easy)
# pop from stack with most plates ? - keep track of max
pop = None
# pop from last stack
if self.lastStack is None:
return None
# index exits in mainStack
print "lastStack:{} len.mainStack:{}".format(self.lastStack, len(self.mainStack))
if self.lastStack > len(self.mainStack) - 1:
return None
# sub-stack has something to pop off
if len(self.mainStack[self.lastStack]) == 0:
return None
pop = self.mainStack[self.lastStack].pop()
self.subStackLength[self.lastStack] -= 1
if pop is not None:
# sub-list cleanup
if len(self.mainStack[self.lastStack]) == 0:
# remove empty main-stack slot
self.mainStack.pop(self.lastStack)
# reset lastStack
if self.lastStack == 0:
self.lastStack = None
else:
self.lastStack -= 1
return pop
def popAt(self, stack=None):
# of course one would have to know how many stacks there were for this to work right
# let's just assume that is the case
pop = None
# pop defined stack
if stack is None:
return None
if type(stack) is not int:
return None
# index exits in mainStack
if stack > len(self.mainStack) - 1:
return None
# sub-stack has something to pop off
if len(self.mainStack[stack]) == 0:
return None
pop = self.mainStack[stack].pop()
self.subStackLength[stack] -= 1
if pop is not None:
# sub-list cleanup
if len(self.mainStack[stack]) == 0:
# remove empty main-stack slot
self.mainStack.pop(stack)
# reset lastStack
if self.lastStack == 0:
self.lastStack = None
else:
self.lastStack -= 1
return pop
def createStack(self):
# append a sub-stack to the main stack and return
self.mainStack.append([])
stackIndex = len(self.mainStack) - 1
#print "=========stackIndex:",stackIndex
self.subStackLength[stackIndex] = 0
return stackIndex
def firstAvailableStack(self):
# return first available (has room to grow) stack index
# walk through subStackLength (dict) key:len
for l in self.subStackLength:
# compare stacklength to class max stack height
if self.subStackLength[l] < self.stackHeight:
# return mainStack index
return l
# no available stacks
return None
def lastAvailableStack(self):
# return last available stack index
# walk through subStackLength (dict) key:len
for l in self.subStackLength:
#print "lastAvailableStack l:{} subStackLength[l]:{} stackHeight:{}".format(l, self.subStackLength[l], self.stackHeight)
# compare stacklength to class max stack height
if self.subStackLength[l] < self.stackHeight:
# return mainStack index
#print "returning l:",l
return l
# no available stacks
return None
# def getNextMax(self):
# # find next max value in stack lengths
# for l in self.subStackLength:
# pass
def push(self, value):
# need to know
# 1. any stack built yet
# 2. first stack with room
if self.mainStack:
# has at least one sub-stack
# let's find that stack
# index of last stack in mainStack -> stackIndex
stackIndex = self.firstAvailableStack()
#print "stackIndex from firstAvailableStack...",stackIndex
if stackIndex is None:
stackIndex = self.createStack()
#print "stackIndex from createStack...",stackIndex
# append value to
self.mainStack[stackIndex].append(value)
self.subStackLength[stackIndex] += 1
self.lastStack = stackIndex
else:
# no sub-stacks built yet
self.mainStack.append([value])
self.subStackLength[0] = 1
self.lastStack = 0 # last sub-stack in main-stack
#self.maxStack[0] = 1 # stack with the most plates (so far)
# Tests - stacks in array
# plates = setOfStacks()
# plates.pop()
# plates.push(1)
# plates.push(2)
# plates.push(3)
# plates.push(4)
# plates.push(5)
# plates.push(6)
# plates.push(7)
# plates.push(8)
# plates.push(9)
# plates.push(10)
# plates.push('a')
# plates.push('b')
# plates.push('c')
# plates.push('d')
# plates.push('e')
# plates.push('f')
# plates.push('g')
# plates.push('h')
# plates.push('i')
# plates.push('j')
# plates.push('k')
# plates.print_container()
# print "pop:",plates.pop()
# plates.print_container()
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "popAt:",plates.popAt(0)
# print "pop:",plates.pop()
# plates.print_container()
"""
3.4
Queue from two Stacks
push into stack 1, pop stack 1, push into stack 2 - now stack pop will act like a queue
"""
class queueStacks(object):
def __init__(self):
self.stack_fwd = []
self.stack_rev = []
def printQueue(self):
print "fwd:",self.stack_fwd
print "rev:",self.stack_rev
def push(self, val):
# add rev back to fwd
# pop: fwd:[1,2,3,4] pop to -> rev:[4,3,2,1]
# push: add 5,6... first pop rev to fwd -> [1,2,3,4] ... push 5,6 fwd:[1,2,3,4,5,6]
# repeat
while self.stack_rev:
pop = self.stack_rev.pop()
self.stack_fwd.append(pop)
# push new value onto stack
self.stack_fwd.append(val)
def pop(self):
# add fwd back to rev
while self.stack_fwd:
pop = self.stack_fwd.pop()
self.stack_rev.append(pop)
if self.stack_rev:
return self.stack_rev.pop()
else:
return None
def peek(self):
# like pop - just don't remove anything from rev
# add fwd back to rev
while self.stack_fwd:
pop = self.stack_fwd.pop()
self.stack_rev.append(pop)
if self.stack_rev:
return self.stack_rev[-1]
else:
return None
# Tests - Queue from two stacks
# queue = queueStacks()
# print "queue.pop:",queue.pop()
# print "queue.peek:",queue.peek()
# queue.push(1)
# queue.push(2)
# queue.push(3)
# queue.push(4)
# queue.printQueue()
# print "queue.pop:",queue.pop()
# queue.printQueue()
# print "queue.pop:",queue.pop()
# queue.printQueue()
# queue.push(5)
# queue.push(6)
# queue.printQueue()
# print "queue.pop:",queue.pop()
# queue.printQueue()
# print "queue.peek:",queue.peek()
# print "queue.peek:",queue.peek()
"""
3.5
Stack - order from min to max - assuming this means on push
pop will always return the min
No mention of time complexity
"""
class stackMin(object):
def __init__(self):
self.stack_fwd = []
self.stack_rev = []
def printQueue(self):
print "fwd:",self.stack_fwd
print "rev:",self.stack_rev
def is_empty(self):
if len(self.stack_fwd) > 0:
return False
else:
return True
def push(self, val):
#print "========== push-ing...", val
# add rev back to fwd
# pop: fwd:[1,2,3,4] pop to -> rev:[4,3,2,1] - pop out -> 1
# push: add 5,6... first pop rev to fwd -> [1,2,3,4] ... push 5,6 fwd:[1,2,3,4,5,6]
# repeat
# move rev back to fwd
#print ".fwd:", self.stack_fwd
#print ".rev:", self.stack_rev
while self.stack_rev:
self.stack_fwd.append(self.stack_rev.pop())
#print "..fwd:", self.stack_fwd
#print "..rev:", self.stack_rev
push_val = False
# insert val in order
#for v in self.stack_fwd:
while self.stack_fwd:
if val >= self.stack_fwd[-1]: # peek stack
#print "{} >= {}".format(val, self.stack_fwd[-1])
push_val = True
self.stack_fwd.append(val)
break
else:
# store in rev as temp storage
pop = self.stack_fwd.pop()
#print "pop stack @ ", pop
#self.stack_rev.append(self.stack_fwd.pop())
self.stack_rev.append(pop)
#print "....fwd:", self.stack_fwd
#print "....rev:", self.stack_rev
if not push_val:
self.stack_fwd.append(val)
# move temp back to fwd
while self.stack_rev:
self.stack_fwd.append(self.stack_rev.pop())
#print ".....fwd:", self.stack_fwd
#print ".....rev:", self.stack_rev
def pop(self):
# add fwd back to rev
while self.stack_fwd:
self.stack_rev.append(self.stack_fwd.pop())
if self.stack_rev:
return self.stack_rev.pop()
else:
return None
def peek(self):
# like pop - just don't remove anything from rev
# add fwd back to rev
while self.stack_fwd:
self.stack_rev.append(self.stack_fwd.pop())
if self.stack_rev:
return self.stack_rev[-1]
else:
return None
# Tests - Min Stack
# minstack = stackMin()
# print "queue.pop:",minstack.pop()
# print "queue.peek:",minstack.peek()
# minstack.push(4)
# minstack.push(7)
# minstack.push(9)
# minstack.push(3)
# print "queue.pop:",minstack.pop()
# print "queue.pop:",minstack.pop()
# minstack.printQueue()
# minstack.push(20)
# minstack.push(1)
# minstack.printQueue()
# print minstack.peek()
# print minstack.peek()
# minstack.printQueue()
"""
3.6
Queue - Animal Shelter
methods:
enqueue
dequeue
dequeueCat
dequeueDog
Note: using a single list to store cats and dogs results on O(c+d) time
using two lists and itering through both at the same time would give (c or d) time depending on the longer list
the more efficient algorithm (data structure) would be to use two lists
"""
class Animal(object):
def __init__(self, name='', age=0, species=None):
self.name = name
self.age = age
self.species = species
class queueAnimalShelter(object):
def __init__(self):
self.inventory = []
def printInventory(self):
if not self.inventory:
print "inventory: None"
return
for animal in self.inventory:
print "inventory:", animal.species, animal.name, animal.age
def printAnimal(self, animal):
if animal and type(animal) is Animal:
print "requested info:", animal.species, animal.name, animal.age
else:
print "requested info: none found"
def enqueue(self, name='', age=0, species=None):
# when queueing up, shoudl I check for dups ?
# assuming the animal is already processed with a tag - no need to dup check
if not name or not age or (species is not 'dog' and species is not 'cat'):
raise ValueError('please enter a name, age and species:dog or cat')
self.inventory.append(Animal(name, age, species))
def dequeue(self):
# dequeue first animal - species doesn't matter
pass
if len(self.inventory) > 0:
return self.inventory.pop(0)
else:
return None
def dequeueCat(self):
# dequeue first cat in list
for k in range(len(self.inventory)):
if self.inventory[k].species == 'cat':
return self.inventory.pop(k)
def dequeueDog(self):
# dequeue first dog in list
for k in range(len(self.inventory)):
if self.inventory[k].species == 'dog':
return self.inventory.pop(k)
# Tests - Queue - Animal Shelter
# shelterpets = queueAnimalShelter()
# shelterpets.enqueue('Fluffy', 8, 'dog')
# shelterpets.enqueue('Snipper', 2, 'dog')
# shelterpets.enqueue('Poopy', 7, 'cat')
# shelterpets.enqueue('Jughead', 3, 'dog')
# shelterpets.enqueue('Scrappy', 4, 'dog')
# shelterpets.enqueue('Tunces', 5, 'cat')
#
# shelterpets.printInventory()
#
# shelterpets.printAnimal(shelterpets.dequeue())
# #shelterpets.printAnimal(shelterpets.dequeue())
# #shelterpets.printAnimal(shelterpets.dequeue())
# shelterpets.printAnimal(shelterpets.dequeueCat())
# #shelterpets.printAnimal(shelterpets.dequeueCat())
# shelterpets.printAnimal(shelterpets.dequeueDog())
# shelterpets.printInventory()
|
from tkinter import *
# This is the list of all default command in the "Text" tag that modify the text
commandsToRemove = (
"<Control-Key-h>",
"<Meta-Key-Delete>",
"<Meta-Key-BackSpace>",
"<Meta-Key-d>",
"<Meta-Key-b>",
"<<Redo>>",
"<<Undo>>",
"<Control-Key-t>",
"<Control-Key-o>",
"<Control-Key-k>",
"<Control-Key-d>",
"<Key>",
"<Key-Insert>",
"<<PasteSelection>>",
"<<Clear>>",
"<<Paste>>",
"<<Cut>>",
"<Key-BackSpace>",
"<Key-Delete>",
"<Key-Return>",
"<Control-Key-i>",
"<Key-Tab>",
"<Shift-Key-Tab>"
)
class ROText(Text):
tagInit = False
def init_tag(self):
"""
Just go through all binding for the Text widget.
If the command is allowed, recopy it in the ROText binding table.
"""
for key in self.bind_class("Text"):
if key not in commandsToRemove:
command = self.bind_class("Text", key)
self.bind_class("ROText", key, command)
ROText.tagInit = True
def __init__(self, *args, **kwords):
Text.__init__(self, *args, **kwords)
if not ROText.tagInit:
self.init_tag()
# Create a new binding table list, replace the default Text binding table by the ROText one
bindTags = tuple(tag if tag!="Text" else "ROText" for tag in self.bindtags())
self.bindtags(bindTags)
#text = ROText()
#text.insert("1.0", """A long text with several
#lines
#in it""")
#text.pack()
#text.mainloop()
|
import random
computer_temporary = []
player_temporary = []
def check_overlap(list1, list2, card):
total_list = list1 + list2
for i in range(0, len(total_list)):
if card == total_list[i]:
return 0
def new_card_generator():
temporary = []
while len(temporary) != 1:
card_number = random.randint(0, 12)
card_shape = random.randint(0, 3)
if card_shape == 0:
card_shape = "♠︎"
elif card_shape == 1:
card_shape = "♣"
elif card_shape == 2:
card_shape = "♥"
else:
card_shape = "♦"
card = card_shape + str(card_number)
overlap = check_overlap(player_temporary, computer_temporary, card)
if overlap != 0:
return card
print(new_card_generator()) |
#!/usr/bin/env python3
__author__ = "Your Name"
###############################################################################
#
# Exercise 13.1
#
#
# Grading Guidelines:
# - No answer variable is needed. Grading script will call function.
# - Function "strip_and_lower" will not be checked aside from ability to run.
#
# 1. Write a function named "strip_and_lower" that reads "emma.txt", breaks each
# line into words, strips whitespace and punctuation from the words, and
# converts them to lowercase. Nothing should be returned at this time.
#
# Hint: The string module provides a string named "whitespace", which contains
# space, tab, newline, etc., and "punctuation" which contains the punctuation
# characters. Let's see if we can make Python swear:
#
# >>> import string
# >>> string.punctuation
# '!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'
#
import string
def strip_and_lower(file):
pass
strip_and_lower("emma.txt") |
# Markov Chain
RecLoc = [] # Records the locations of the particle
N = 1000 # Number of steps
import random
p_A = float(input("Enter the probability of leaving '0' and going to '1'."))
p_B = float(input("Enter the probability of leaving '1' and going to '0'."))
S = int(input("Enter either '0' and '1' as starting state."))
RecLoc.append(5)
for i in range(N):
r = random.uniform(0, 1)
if S == 0 and r < p_A:
S = 1
elif S == 1 and r < p_B:
S = 0
RecLoc.append(S)
X = 0
for x in RecLoc:
X = X + x
print("Percentage in state '1', ", X/N, '.')
print("Percentage in state '0', ", 1-(X/N), '.')
# Birthday problem
P = 1.0
K = 50
for k in range(1, K-1):
P = P * ((365 - k + 1) / 365)
print(k, 1-P)
# Poisson
L = float(input("Enter the value of the Poisson parameter."))
N = 25 # Number of probabilities
import math
P = math.exp(-L)
X = [0] # Horizontal axis
Y = [P] # Vertical axis
for i in range(N):
if i > 0:
P = P*(L/i) # Recursion
X.append(i)
Y.append(P)
print(i, P) # Poisson probabilities
import matplotlib.pyplot as plt
plt.plot(X, Y, 'r+')
plt.show()
|
list1 = [8, 15, 32, 42, 60, 75, 122, 132, 150, 180, 190]
def divisible(list):
for item in list:
if(item<120):
if(item%4==0):
print(item)
else:
break
t = divisible(list1)
print(t)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Kimmyzhang
@Email: 902227553.com
@File: kimmyzhang_20170912_03.py
@Time: 2017/9/12 15:38
"""
def ave_length(str):
fraction_str = 1
frequency = 1
frequency_list = []
for i in range(len(str) - 1):
if str[i] == str[i + 1]:
frequency += 1
else:
frequency_list.append(frequency)
frequency = 1
fraction_str += 1
print(len(str)/fraction_str)
ave_length("aabbcddaaaad")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @date : 2018-04-17 15:26:50
# @author : lyrichu
# @email :[email protected]
# @link : https://www.github.com/Lyrichu
# @version : 0.1
# @description:
'''
Q1:利用栈实现二叉树的非递归形式的前,中,后序遍历
'''
class Node:
def __init__(self,data=None,left=None,right=None):
self.data = data
self.left = left
self.right = right
class BinaryTree:
def __init__(self):
self.root = Node()
self.stack = []
def order_insert(self,data):
'''
二叉树顺序插入
'''
if self.root.data is None:
self.root.data = data
self.stack.append(self.root)
else:
new_node = Node(data)
cur_node = self.stack[0]
if cur_node.left is None:
cur_node.left = new_node
self.stack.append(cur_node.left)
else:
cur_node.right = new_node
self.stack.append(cur_node.right)
self.stack.pop(0) #去除根节点
def recursion_pre_print(self,root):
if root is None:
return
print(root.data,end = " ")
self.recursion_pre_print(root.left)
self.recursion_pre_print(root.right)
def recursion_mid_print(self,root):
if root is None:
return
self.recursion_mid_print(root.left)
print(root.data,end = " ")
self.recursion_mid_print(root.right)
def recursion_back_print(self,root):
if root is None:
return
self.recursion_back_print(root.left)
self.recursion_back_print(root.right)
print(root.data,end = " ")
def recursion_level_print(self):
if self.root.data is None:
print("This is an empty tree!")
print(self.root.data,end = " ")
level_stack = [self.root]
while level_stack:
cur_node = level_stack.pop(0)
if cur_node.left:
print(cur_node.left.data,end = " ")
level_stack.append(cur_node.left)
if cur_node.right:
print(cur_node.right.data,end = " ")
level_stack.append(cur_node.right)
def stack_pre_print(self):
'''
非递归前序遍历
'''
stack = []
cur_node = self.root
if cur_node.data is None:
print("This is an empty tree!")
while stack or cur_node:
while cur_node:
print(cur_node.data,end = " ")
# 左子树入栈
stack.append(cur_node)
cur_node = cur_node.left
# 开始查看右子树
cur_node = stack.pop()
cur_node = cur_node.right
def stack_mid_print(self):
'''
非递归中序遍历
'''
stack = []
cur_node = self.root
if cur_node.data is None:
print("This is an empty tree!")
while cur_node or stack:
# 左子树一直入栈
while cur_node:
stack.append(cur_node)
cur_node = cur_node.left
cur_node = stack.pop()
print(cur_node.data,end = " ")
# 查看右子树
cur_node = cur_node.right
def stack_back_print(self):
'''
非递归后序遍历
'''
stack = []
stack_print = [] # 最终的遍历打印栈
cur_node = self.root
stack.append(self.root)
while stack:
cur_node = stack.pop()
if cur_node.left:
stack.append(cur_node.left)
if cur_node.right:
stack.append(cur_node.right)
stack_print.append(cur_node)
while stack_print:
print(stack_print.pop().data,end = " ")
if __name__ == '__main__':
tree = BinaryTree()
data = range(1,11)
for d in data:
tree.order_insert(d)
print("递归前序遍历:",end = " ")
tree.recursion_pre_print(tree.root)
print("\n")
print("非递归先序遍历:",end = " ")
tree.stack_pre_print()
print("\n")
print("递归中序遍历:",end = " ")
tree.recursion_mid_print(tree.root)
print("\n")
print("非递归中序遍历:",end = " ")
tree.stack_mid_print()
print("\n")
print("递归后序遍历:",end = " ")
tree.recursion_back_print(tree.root)
print("\n")
print("非递归后序遍历:",end = " ")
tree.stack_back_print()
print("\n")
print("层次遍历:",end = " ")
tree.recursion_level_print()
print("\n")
|
# -*- coding:utf-8 -*-
'''
我们把一个N位的数字等于其各位的N次方之和的数字称为阿姆斯特朗数,求100000以内的所有阿姆斯特朗数。
'''
def is_armstrong_number(n):
'''
判断一个数是否是阿姆斯特朗数
:param n:数字n
:return: True or False
'''
# 数字n的位数
digits = len(str(n))
# 各位数字列表
numbers = map(int,list(str(n)))
sum_ = sum(map(lambda x:x**digits,numbers))
return sum_ == n
def find_armstrong_numbers(n):
'''
寻找小于n的所有armstrong数
'''
for i in range(n+1):
if(is_armstrong_number(i)):
print(i)
if __name__ == '__main__':
find_armstrong_numbers(100000)
|
#!/usr/bin/env python
# encoding: utf-8
"""
@author: Kimmyzhang
@license: Apache Licence
@file: kimmyzhang_20170911_02.py
@time: 2017/9/11 17:01
"""
# 将该题抽象成进制问题。即为25进制.但是要做很多准备工作。因为要处理很多特殊情况。
def getIndex(str):
index = 0
for i in range(4):
if i == 0:
index = (ord(str[i]) - 97)* pow(25, 3) + (ord(str[i]) - 96) * 3
#print(index)
# 这地方位置放的不同,会有什么区别
else:
index = index + (ord(str[i]) - 96) * pow(25, 3 - i)
print(index-1)
getIndex("bada")
|
# -*- coding:utf-8 -*-
'''
Q3:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
思路参考:http://www.cnblogs.com/pmars/archive/2013/12/04/3458289.html
'''
# 全排列字典排序打印(非递归形式)
def string_dict_order_print(string):
# 将 string 变为列表
string = list(string)
length = len(string)
# 排序
string.sort()
# 字典排序最大字符串(从高到低排序)
string_reverse = list(reversed(string))
while(string != string_reverse):
print("".join(string))
index = length-1
while(index>=1 and string[index-1] > string[index]):
index -= 1
max_index = length - 1
while(max_index >= index and string[max_index] < string[index-1]):
max_index -= 1
# 交换
string[index-1],string[max_index] = string[max_index],string[index-1]
string = string[:index] + list(reversed(string[index:]))
print("".join(string))
# 递归版本
def recursion_dict_order(string_list,from_index,end_index):
if from_index == end_index:
print("".join(string_list))
else:
for i in range(from_index,end_index+1):
# 重新排序
string_list = string_list[:from_index] + sorted(string_list[from_index:end_index+1])
string_list[from_index],string_list[i] = string_list[i],string_list[from_index]
recursion_dict_order(string_list,from_index+1,end_index)
string_list[from_index],string_list[i] = string_list[i],string_list[from_index]
if __name__ == '__main__':
string = input("Please input a string:(only have alphabets)")
print("The dict order permutation of \"%s\" is:" % string)
string_dict_order_print(string)
print("The dict order permutation of \"%s\" using recursion method is:" % string)
recursion_dict_order(list(string),0,len(string)-1)
|
# -*- coding:utf-8 -*-
'''
@author:lyrichu
@email:[email protected]
@description:
Q2:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
'''
def merge_ksorted_lists(klists):
'''
:param klists: k sorted lists in a list
:return total sorted lists
'''
# k is the num of sorted lists
k = len(klists)
total_lists = klists[0]
if(k > 1):
for lists in klists[1:]:
total_lists.extend(lists)
total_lists.sort()
return total_lists
if __name__ == '__main__':
klists = []
print("Please input a sorted number lists:")
_input = input()
while(_input):
lists = [int(i) for i in _input.split(" ")]
klists.append(lists)
print("Please input a sorted number lists:")
_input = input()
print("Your input is:")
for lists in klists:
print(" ".join(map(str,lists)))
total_sorted_lists = merge_ksorted_lists(klists)
print("The merged sorted lists is:{}".format(" ".join(map(str,total_sorted_lists))))
|
#!/usr/bin/env python
# encoding: utf-8
"""
@version: 0.1
@author: lyrichu
@license: Apache Licence
@contact: [email protected]
@software: PyCharm
@file: lyrichu_20170915_03.py
@time: 2017/9/25 21:11
@description:基本的快速排序算法
"""
from __future__ import print_function
import random
def quickSort(L, low, high):
'''
:param L: 待排序的列表
:param low: 左标记
:param high: 右标记
:return: 完成排序之后的列表
'''
i = low
j = high
if i >= j:
return L
key = L[i]
while i < j:
while i < j and L[j] >= key:
j = j-1
L[i] = L[j]
while i < j and L[i] <= key:
i = i+1
L[j] = L[i]
L[i] = key
quickSort(L, low, i-1)
quickSort(L, j+1, high)
return L
if __name__ == '__main__':
# 0-99 的顺序列表
L = list(range(100))
# 将列表随机打乱
random.shuffle(L)
print("before sort:",L)
quickSort(L,0,99)
print("after quick sort:",L)
|
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# @Time : 2017/9/6 8:45
# @Author : Lyrichu
# @Email : [email protected]
# @File : lyrichu_20170906_02.py
'''
@Description:输出前N个斐波那契数列
'''
num = int(raw_input()) # 输入N
f_list = [] # 存放数字的数组
for i in range(num):
if i == 0 or i == 1:
f_list.append(i)
else:
f_list.append(f_list[i-1] + f_list[i-2])
print(" ".join([str(i) for i in f_list]))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Kimmyzhang
@Email: 902227553.com
@File: kimmyzhang_20171024_01.py
@Time: 2017/10/24 21:16
"""
# 用dp算法去求解,其实就是递推,不过怎么递推还是需要去思考的。
def lcs_by_dp(a, b):
'''
求解最大公共子序列问题
:param a: 第一个字符串
:param b: 第一个字符串
:return: length of the LCS
'''
lena = len(a)
lenb = len(b)
c=[[0 for i in range(lenb+1)] for j in range(lena+1)] # 多一位
flag = [[0 for i in range(lenb + 1)] for j in range(lena + 1)]
for i in range(lena):
for j in range(lenb):
if a[i] == b[j]:
c[i + 1][j + 1] = c[i][j] + 1
flag[i + 1][j + 1] = 'ok'
elif c[i + 1][j] > c[i][j + 1]:
c[i + 1][j + 1] = c[i + 1][j]
flag[i + 1][j + 1] = 'left'
else:
c[i + 1][j + 1] = c[i][j + 1]
flag[i + 1][j + 1] = 'up'
return c, flag
def print_lcs(flag, a, i, j):
if i == 0 or j == 0:
return
if flag[i][j] == "ok":
print_lcs(flag, a, i - 1, j - 1)
print(a[i - 1], end="")
elif flag[i][j] == "left":
print_lcs(flag, a, i, j - 1)
else:
print_lcs(flag, a, i - 1, j)
if __name__ == '__main__':
a = 'ABCBDAB'
b = 'BDCABA'
c, flag = lcs_by_dp(a, b)
for i in c:
print(i)
print('')
for j in flag:
print(j)
print('')
print_lcs(flag, a, len(a), len(b))
print('') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.