text
stringlengths 37
1.41M
|
---|
from turtle import Turtle
WIDTH = 5
HEIGHT = 1
MOVE_DISTANCE = 20
class Paddle(Turtle):
def __init__(self, initial_x, initial_y):
super().__init__()
self.x_pos = initial_x
self.y_pos = initial_y
self.color("white")
self.shape("square")
self.turtlesize(stretch_wid=WIDTH, stretch_len=HEIGHT)
self.penup()
self.goto(x=self.x_pos, y=self.y_pos)
def move_up(self):
if self.ycor() < 240:
new_y = self.ycor() + MOVE_DISTANCE
self.goto(x=self.x_pos, y=new_y)
def move_down(self):
if self.ycor() > -240:
new_y = self.ycor() - MOVE_DISTANCE
self.goto(x=self.x_pos, y=new_y)
|
#!/usr/bin/env python3
# encoding: utf-8
# Splits a word into multiple parts
def split_word(word):
split_indexes = list(range(0, len(word)))
for i in split_indexes:
first_part = word[:i]
second_part = word[i:]
yield (first_part, second_part)
|
"""
==============
Plotting bars
==============
Here's a small example showcasing how to plot bars on a circular strip.
"""
import numpy as np
from circhic._base import CircHiCFigure
###############################################################################
# First, simulate some data
lengths = np.array([3500])
random_state = np.random.RandomState(42)
data = random_state.randn(100)
###############################################################################
# Then, create the `circhic` figure and plot the bars
circhicfig = CircHiCFigure(lengths)
_, ax = circhicfig.plot_bars(
data,
inner_radius=0.5,
color="0")
ax.set_title("Plotting bars", fontweight="bold")
|
"""
Utilizando lambdas
Conhecidas por expressões lambdas ou simplesmente lambdas
funções anonimas
"""
nome_completo = lambda nome, sobrenome: nome.strip().title() + " " + sobrenome.strip().title()
print(nome_completo(" ANGELINA ", " JOLIE")) |
import random
import time
import os
Jogadores = []
Classes = []
salvados = [""]
Atribuido = {}
def cadastraJogadores():
jogador = ""
numJog=0
while True:
numJog = int(input("--Diga quantos jogadores terá: "))
if numJog < 5:
print("Numero de jogadores menor que 5, insuficiente, digite novamente")
elif numJog >=8:
print("Numero de jogadores maior que o permitido(8), digite novamente")
else:
break
for x in range(numJog):
n = x+1
while True:
jogador=input("--Nome do Jogador %d: "%n)
ver=verificaJogadoremJogadores(jogador)
if ver == 0:
print("Jogadores nao podem ter o mesmo nome, digite novamente")
elif ver == 1:
if jogador != "":
Jogadores.insert(x,jogador)
break
elif jogador == "":
print("Jogador precisa ter um nome, digite novamente")
random.shuffle(Jogadores)
os.system('cls')
return numJog
def criaClasses(numJog):
#numJog = cadastraJogadores()
if numJog < 5:
print("Número mínimo não alcançado")
return
elif numJog < 10:
if numJog == 5:
Classes.insert(0,"Mafia")
Classes.insert(1,"Medico")
Classes.insert(2,"Suicida")
Classes.insert(3,"Civil 1")
Classes.insert(4,"Civil 2")
elif numJog == 6:
Classes.insert(0,"Mafia")
Classes.insert(1,"Medico")
Classes.insert(2,"Suicida")
Classes.insert(3,"Civil 1")
Classes.insert(4,"Civil 2")
Classes.insert(5,"Civil 3")
elif numJog == 7:
Classes.insert(0,"Mafia")
Classes.insert(1,"Sacerdote")
Classes.insert(2,"Medico")
Classes.insert(3,"Suicida")
Classes.insert(4,"Civil 1")
Classes.insert(5,"Civil 2")
Classes.insert(6,"Civil 3")
elif numJog == 8:
Classes.insert(0,"Mafia")
Classes.insert(1,"Sacerdote")
Classes.insert(2,"Medico")
Classes.insert(3,"Detetive")
Classes.insert(4,"Suicida")
Classes.insert(5,"Civil 3")
Classes.insert(6,"Civil 4")
Classes.insert(7,"Civil 5")
return
def atribuicoes():
#criaClasses()
qtd=0
tamC = len(Classes)
for x in range(tamC):
classe = Classes[x]
nomeJogador = Jogadores[x]
Atribuido[classe] = nomeJogador
print("--" + classe + ": " + nomeJogador)
#print(Atribuido["Mafia"])
#print(Atribuido)
return
def mostraJogadores():
print("------Lista dos Jogadores:")
for x in Atribuido:
print(x + ": " + Atribuido[x])
return
def mataJogador(acusado, qtd, mafia, suicida, qtdM):
tamAtribuido = len(Atribuido)
qtdAcusando = tamAtribuido - qtdM - 1
metadeAcusando = qtdAcusando//2
if qtd>metadeAcusando:
if acusado == mafia:
return 0 #acusado era o mafia, fim de jogo
elif acusado == suicida:
return 2 #acusado era o suicida, fim de jogo
else:
for x in Atribuido:
if acusado == Atribuido[x]:
Atribuido[x] = "morto"
#Jogadores.remove(acusado)
return 3 #acusado nao era o mafia, continua
else:
return 1 #Ninguem morreu
return 1
def verificaJogador(nome):
for x in Atribuido:
if nome == Atribuido[x]:
return 0 #ACHOU
return 1 #NAO ACHOU
def verificaJogadoremJogadores(nome):
for x in Jogadores:
if nome == x:
return 0 #ACHOU
return 1 #NAO ACHOU
def qtdMortos(): #Conta quantas pessoas estao mortas
qtd = 0
for x in Atribuido:
if Atribuido[x] == "morto":
qtd = qtd + 1
return qtd
def scriptNoite():
vitimaNoite = ""
vitimaSacerdote = "."
ultimoSalvado = len(salvados) - 1
tamAtribuido = len(Atribuido)
mafia = Atribuido["Mafia"]
vitimas = []
if tamAtribuido == 7 or tamAtribuido == 8:
sacerdote = Atribuido["Sacerdote"]
while True:
vitimaNoite = input("Se você pegou o mafia, digite quem você quer matar: ")
verifica = verificaJogador(vitimaNoite)
if verifica == 0:
if vitimaNoite == mafia: #Mafia nao pode se matar
print("Mafia nao pode se matar")
else:
break
elif verifica == 1:
print("--Nome passado nao corresponde aos jogadores disponiveis")
########SACERDOTE#########
if tamAtribuido == 7 or tamAtribuido == 8:
while True:
respSacerdote = input("Se você pegou o sacerdote, me fale se quer matar(s/n): ")
if sacerdote != "morto":
if respSacerdote == "s":
while True:
vitimaSacerdote = input("--Quem: ")
verifica = verificaJogador(vitimaSacerdote)
if verifica == 0:
if vitimaSacerdote == sacerdote: #Sacerdote nao pode se matar
print("Sacerdote nao pode se matar")
else:
break
elif verifica == 1:
print("--Nome passado nao corresponde aos jogadores disponiveis")
break
elif respSacerdote == "n":
break
else:
vitimaSacerdote = "." #Se o Sacerdote estiver morto, nao pode matar ninguem
break
##################################
while True:
salvado = input("Se você pegou o medico, digite quem você quer salvar: ")
if Atribuido["Medico"] != "morto":
verifica = verificaJogador(salvado)
if verifica == 0:
if salvado != salvados[ultimoSalvado]:
salvados.append(salvado)
break
else:
print("Nao pode salvar a mesma pessoa duas vezes seguidas")
elif verifica == 1:
print("--Nome passado nao corresponde aos jogadores disponiveis")
else:
salvado = "" #Se o medico estiver morto nao pode salvar ninguem
break
if tamAtribuido == 7 or tamAtribuido == 8 :
if sacerdote != "morto":
if vitimaSacerdote == mafia:
vitimas.append(mafia)
Atribuido["Mafia"] = "morto" #Mata o mafia
elif vitimaSacerdote == ".":
vitimaSacerdote = "."
else:
if vitimaNoite != sacerdote:
if salvado != sacerdote:
vitimas.append(sacerdote)
Atribuido["Sacerdote"] = "morto"
else:
if salvado == sacerdote:
vitimas.append(sacerdote)
Atribuido["Sacerdote"] = "morto"
tamVitimas = len(vitimas)
os.system('cls')
if tamVitimas == 0: #Significa que o sacerdote nao fez nada
if vitimaNoite == salvado:
print("Ninguem morreu essa noite.")
else:
for x in Atribuido:
if vitimaNoite == Atribuido[x]:
Atribuido[x] = "morto"
#Jogadores.remove(vitimaNoite)
break
print("A vitima da noite foi: %s"%vitimaNoite)
else:
if Atribuido["Sacerdote"] == "morto":
if vitimaNoite == salvado:
print("A vitima da noite foi: %s"%vitimas[0])
else:
for x in Atribuido:
if vitimaNoite == Atribuido[x]:
Atribuido[x] = "morto"
#Jogadores.remove(vitimaNoite)
break
print("As vitimas da noite foram: %s e %s"%(vitimaNoite,vitimas[0]))
elif Atribuido["Mafia"] == "morto":
if vitimaNoite == salvado:
print("A vitima da noite foi: %s"%vitimas[0])
else:
for x in Atribuido:
if vitimaNoite == Atribuido[x]:
Atribuido[x] = "morto"
#Jogadores.remove(vitimaNoite)
break
print("As vitimas da noite foram: %s e %s"%(vitimaNoite,vitimas[0]))
return
def scriptDia():
mafia = Atribuido["Mafia"]
suicida = Atribuido["Suicida"]
tamAtribuido = len(Atribuido)
acusado = ""
ver = "a"
qtdAcusacoes = 0
qtdMortoss = qtdMortos()
qtdVivos = tamAtribuido - qtdMortoss
if qtdVivos == 2:
return 2 #MAFIA GANHOU
if mafia == "morto":
return 0
print("Amanheceu, vocês tem 2 minutos para conversar")
while True:
acusacao = input("--Alguem fez alguma acusação?(s/n): ")
if acusacao == "s":
break
elif acusacao == "n":
break
else:
print("Por favor, digite (s/n)")
while acusacao=="s":
while True:
acusado = input("--Nome do acusado: ")
verifica = verificaJogador(acusado)
if verifica == 0:
break
print("--Nome passado nao corresponde aos jogadores disponiveis")
print("Acusado pode fazer sua defesa")
print("Me mandem mensagem dizendo se querem ou nao matar o acusado(s/n)")
for x in Atribuido:
if acusado != Atribuido[x]: #Acusado nao pode votar
if Atribuido[x] != "morto": #Morto nao pode votar
while True:
ver = input(Atribuido[x] + ":")
if ver == "s":
qtdAcusacoes = qtdAcusacoes + 1
break
elif ver == "n":
break
print("Mensagem nao valida, por favor digite (s/n)")
matanca = mataJogador(acusado,qtdAcusacoes,mafia,suicida,qtdMortoss)
if matanca == 0:
return 0 #ACABOU O JOGO
elif matanca == 3:
print("O acusado: " + acusado + " morreu")
print("Continua o jogo")
return 4 #ACABOU O DIA
elif matanca == 2:
return 3 #ACABOU O JOGO
elif matanca == 1:
print("Votos nao suficiente para matar")
acusacao = input("--Alguem fez alguma acusação?(s/n): ")
os.system('cls')
return 1
def jogo():
numJog=cadastraJogadores()
criaClasses(numJog)
atribuicoes()
print("-------------ANOITECEU-------------")
scriptNoite()
print("-------------AMANHECEU-------------")
mostraJogadores()
dia = scriptDia()
while dia == 1 or dia ==4:
print("-------------ANOITECEU-------------")
mostraJogadores()
scriptNoite()
print("-------------AMANHECEU-------------")
mostraJogadores()
dia = scriptDia()
if dia==0:
print("Mafia morreu")
print("Cidade ganhou!!!")
time.sleep(15)
return
elif dia==2:
print("Mafia ganhou!!!")
time.sleep(15)
return
elif dia==3:
print("Suicida morreu")
print("Suicida ganhou!!!")
time.sleep(15)
return
return
jogo()
|
from tkinter import *
import os
root=Tk() #
root.title('tk using label') #根窗口的标题
root.geometry('600x600') #根窗口的大小
'text: Label显示的文本'
'font: Label显示的字体'
'relief:控件的样式'
'padx:x方向上,Label内文字与Label边缘的距离'
'pady:y方向上,Label内文字与Label边缘的距离'
x = Label(root,
text='a beautiful girl',
font=('Arial',12),
relief=RIDGE,
padx = 5,pady=10)
x.pack(cnf={'pady':20,'ipady':20})
'Label y to show image'
file_dir = os.path.dirname(os.getcwd()) + '\image\girl.png'
bm = PhotoImage(file=file_dir)
y = Label(root,image=bm)
y.pack(cnf={'before':x})
#消息循环
root.mainloop() |
import numpy as np
def gradient_descent(x,y):
m_curr = b_curr = 0
n = len(x)
learning = 0.07
iterations = 100
for i in range(iterations):
y_pred = (m_curr * x + b_curr)
cost = (1/n) * sum([val**2 for val in (y - y_pred)])
md = -(2/n) * sum(x * (y - y_pred))
bd = -(2/n) * sum(y - y_pred)
m_curr = m_curr - learning * md
b_curr = b_curr - learning * bd
print("{}-> m--> {} b--> {} cost--> {}".format(i,m_curr,b_curr,cost))
x = np.array([1,2,3,4,5])
y = np.array([5,7,9,11,13])
gradient_descent(x,y) |
import threading
from queue import Queue
import statistics
import sys
def calcul(fonction, data_ready):
print("Starting thread:", threading.current_thread().name)
data_ready.wait()
data = queue.get()
print(fonction.__name__ + " : " + str(fonction(data)))
print("Ending thread:", threading.current_thread().name)
if __name__ == "__main__":
print("Starting thread:", threading.current_thread().name)
queue = Queue()
data_ready = threading.Event()
data = []
n = input("entrer liste de nb")
input_str = n.split()
for s in input_str:
try:
x = float(s)
except ValueError:
print("bad number", s)
else:
data.append(x)
queue.put(data)
data_ready.set()
for f in [min, max, statistics.median, statistics.mean, statistics.stdev]:
queue.put(data)
thread = threading.Thread(target=calcul, args=(f, data_ready))
thread.start()
thread.join()
print("Ending thread:", threading.current_thread().name)
|
import math
def pascal(rows):
for rownum in range (rows):
newValue=1
PrintingList = [newValue]
for iteration in range (rownum):
newValue = newValue * ( rownum-iteration ) * 1 / ( iteration + 1 )
PrintingList.append(int(newValue))
print(PrintingList)
rows = input('Enter the number of rows \n')
rows = int(rows)
pascal(rows)
print ('enter the row and column of the element to be looked up \n')
a = input('enter the row: \n')
b = input('enter the column: \n')
a, b = int(a), int(b)
print ('Element \n')
print (math.factorial(a)/((math.factorial(a-b))*math.factorial(b)))
|
import numpy as np
import pandas as pd
import visuals as vs
import matplotlib.pyplot as pl
pd.set_option('display.width', 800)
data = pd.read_csv('../resources/customers.csv')
SHOW_VISUALS = False
print '''
/*
* **************************************
* ********** DATA EXPLORATION **********
* **************************************
*/
'''
data.drop(['Region', 'Channel'], axis = 1, inplace = True)
print "Wholesale customers dataset has {} samples with {} features each.".format(*data.shape)
print data.describe(),"\n"
# print data[data['Fresh'] == 3]
print data[data['Fresh'] == 112151]
print "\n"
# print data[data['Detergents_Paper'] == 3]
print data[data['Detergents_Paper'] == 40827]
print "\n"
# print data[data['Delicatessen'] == 3]
print data[data['Delicatessen'] == 47943]
print "\n"
# TODO: Select three indices of your choice you wish to sample from the dataset
indices = [181, 85, 183]
# Create a DataFrame of the chosen samples
samples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True)
print "Chosen samples of wholesale customers dataset:"
print samples
print "\n\n"
print '''
/*
* ***** Feature Relevance *****
*/
'''
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeRegressor
# TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature
for column in data.columns:
new_data = data.drop([column], axis = 1)
Y = data[column]
#print "new_data.columns ", new_data.columns
#print "Y.shape ", Y.shape
# TODO: Split the data into training and testing sets using the given feature as the target
X_train, X_test, y_train, y_test = train_test_split(new_data, Y, test_size=0.25, random_state=42)
# TODO: Create a decision tree regressor and fit it to the training set
regressor = DecisionTreeRegressor(random_state=42)
regressor.fit(X_train, y_train)
# TODO: Report the score of the prediction using the testing set
score = regressor.score(X_test, y_test)
print "score on guessing '{}': {}".format(column, score)
if SHOW_VISUALS:
axes = pd.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
print "\n\n"
print '''
/*
* ****************************************
* ********** DATA PREPROCESSING **********
* ****************************************
*/
'''
print '''
/*
* ***** Feature scaling *****
*/
'''
# TODO: Scale the data using the natural logarithm
log_data = data.apply(np.log)
# TODO: Scale the sample data using the natural logarithm
log_samples = samples.apply(np.log)
if SHOW_VISUALS:
# Produce a scatter matrix for each pair of newly-transformed features
pd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
print "Log samples:"
print log_samples
print "\n\n"
print '''
/*
* ***** Outlier Detection *****
*/
'''
# For each feature find the data points with extreme high or low values
outliers_count = {}
for feature in log_data.keys():
# TODO: Calculate Q1 (25th percentile of the data) for the given feature
Q1 = np.percentile(log_data[feature], 25)
# TODO: Calculate Q3 (75th percentile of the data) for the given feature
Q3 = np.percentile(log_data[feature], 75)
# TODO: Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)
step = (Q3 - Q1) * 1.5
# Display the outliers
print "\n"
print "Data points considered outliers for the feature '{}':".format(feature)
feature_outliers = log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))]
print feature_outliers
for customer_index in feature_outliers.index:
outlier_features = [feature];
if customer_index in outliers_count:
outlier_features = outliers_count[customer_index]
outlier_features.append(feature)
outliers_count[customer_index] = outlier_features
print "\n"
print "Total outliers count"
print sorted(outliers_count.items(), key=lambda x: len(x[1]), reverse=True)
# OPTIONAL: Select the indices for data points you wish to remove
outliers = []
for k,v in outliers_count.items():
if len(v) > 1:
outliers.append(k)
print outliers
outliersPD = pd.DataFrame(data.loc[outliers], columns = data.keys())
print outliersPD
# Remove the outliers, if any were specified
good_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True)
print '''
/*
* ***** PCA Analysis *****
*/
'''
from sklearn.decomposition import PCA
# TODO: Apply PCA by fitting the good data with the same number of dimensions as features
pca = PCA(len(good_data.keys()))
pca.fit(good_data)
# TODO: Transform log_samples using the PCA fit above
pca_samples = pca.transform(log_samples)
if SHOW_VISUALS:
# Generate PCA results plot
pca_results = vs.pca_results(good_data, pca)
print "PCA with 6 components Explained Variance Ratio"
print pca.explained_variance_ratio_
print "Total variance of PCA 1 and 2: ", pca.explained_variance_ratio_[0] + pca.explained_variance_ratio_[1]
print "Total variance of PCA 1 to 4: ", pca.explained_variance_ratio_[0] + pca.explained_variance_ratio_[1] + pca.explained_variance_ratio_[2] + pca.explained_variance_ratio_[3]
print '''
/*
* ***** PCA Application *****
*/
'''
# TODO: Apply PCA by fitting the good data with only two dimensions
pca = PCA(n_components=2)
pca.fit(good_data)
# TODO: Transform the good data using the PCA fit above
reduced_data = pca.transform(good_data)
# TODO: Transform log_samples using the PCA fit above
pca_samples = pca.transform(log_samples)
# Create a DataFrame for the reduced data
reduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2'])
print "3 Scaled Samples with PCA=2..."
print pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2'])
if SHOW_VISUALS:
ax = vs.biplot(good_data, reduced_data, pca)
print '''
/*
* ************************************
* ********** IMPLEMENTATION **********
* ************************************
*/
'''
print '''
/*
* ***** Creating Clusters *****
*/
'''
from sklearn.mixture import GMM
from sklearn.metrics import silhouette_score
#mixtures = np.arange(2, 6)
mixtures = np.arange(2, 3)
for n_components in mixtures:
# TODO: Apply your clustering algorithm of choice to the reduced data
clusterer = GMM(n_components=n_components, random_state=42)
clusterer.fit(reduced_data)
# TODO: Predict the cluster for each data point
preds = clusterer.predict(reduced_data)
# TODO: Find the cluster centers
centers = clusterer.means_
print "centers: "
print centers
# TODO: Predict the cluster for each transformed sample data point
sample_preds = clusterer.predict(pca_samples)
# TODO: Calculate the mean silhouette coefficient for the number of clusters chosen
score = silhouette_score(reduced_data, preds)
print "Silhouette score with {} clusters: {}".format(n_components, np.round(score, 4))
if SHOW_VISUALS:
vs.cluster_results(reduced_data, preds, centers, pca_samples)
print '''
/*
* ***** Data recovery *****
*/
'''
# TODO: Inverse transform the centers
log_centers = pca.inverse_transform(centers)
# TODO: Exponentiate the centers
true_centers = np.exp(log_centers)
# Display the true centers
segments = ['Segment {}'.format(i) for i in range(0,len(centers))]
true_centers = pd.DataFrame(np.round(true_centers), columns = data.keys())
true_centers.index = segments
print "true_centers"
print true_centers
print "\ntrue_centers - data.mean().round()"
print true_centers - data.mean().round()
print "\ntrue_centers - data.median().round()"
print true_centers - data.median().round()
vs.channel_results(reduced_data, outliers, pca_samples)
#if SHOW_VISUALS:
pl.show() |
###########################################
# Suppress matplotlib user warnings
# Necessary for newer version of matplotlib
import warnings
warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
#
# Display inline matplotlib plots with IPython
#from IPython import get_ipython
#get_ipython().run_line_magic('matplotlib', 'inline')
###########################################
import pandas as pd
import matplotlib.pyplot as pl
import matplotlib.patches as mpatches
import matplotlib.cm as cm
import numpy as np
import sklearn.learning_curve as curves
from sklearn.tree import DecisionTreeRegressor
from sklearn.cross_validation import ShuffleSplit, train_test_split
def ModelLearning(X, y):
""" Calculates the performance of several models with varying sizes of training data.
The learning and testing scores for each model are then plotted. """
# Create 10 cross-validation sets for training and testing
cv = ShuffleSplit(X.shape[0], n_iter = 10, test_size = 0.2, random_state = 0)
# Generate the training set sizes increasing by 50
train_sizes = np.rint(np.linspace(1, X.shape[0]*0.8 - 1, 9)).astype(int)
print "train_sizes", train_sizes
# Create the figure window
fig = pl.figure(figsize=(15,9))
# Create three different models based on max_depth
for k, depth in enumerate([1,3,6,10]):
# Create a Decision tree regressor at max_depth = depth
regressor = DecisionTreeRegressor(max_depth = depth)
# Calculate the training and testing scores
sizes, train_scores, test_scores = curves.learning_curve(regressor, X, y, \
cv = cv, train_sizes = train_sizes, scoring = 'r2')
# Find the mean and standard deviation for smoothing
train_std = np.std(train_scores, axis = 1)
train_mean = np.mean(train_scores, axis = 1)
test_std = np.std(test_scores, axis = 1)
test_mean = np.mean(test_scores, axis = 1)
# Subplot the learning curve
ax = fig.add_subplot(2, 2, k+1)
ax.plot(sizes, train_mean, 'o-', color = 'r', label = 'Training Score')
ax.plot(sizes, test_mean, 'o-', color = 'g', label = 'Testing Score')
ax.fill_between(sizes, train_mean - train_std, \
train_mean + train_std, alpha = 0.15, color = 'r')
ax.fill_between(sizes, test_mean - test_std, \
test_mean + test_std, alpha = 0.15, color = 'g')
# Labels
ax.set_title('max_depth = %s'%(depth))
ax.set_xlabel('Number of Training Points')
ax.set_ylabel('Score')
ax.set_xlim([0, X.shape[0]*0.8])
ax.set_ylim([-0.05, 1.05])
ax.grid('on')
# Visual aesthetics
lgd = ax.legend(bbox_to_anchor=(1.05, 2.05), loc='lower left', borderaxespad = 0.)
fig.suptitle('Decision Tree Regressor Learning Performances', fontsize = 16, y = .03)
fig.tight_layout()
fig.subplots_adjust(right=.7, bottom = .1)
#fig.show()
pl.show()
def ModelComplexity(X, y):
""" Calculates the performance of the model as model complexity increases.
The learning and testing errors rates are then plotted. """
# Create 10 cross-validation sets for training and testing
cv = ShuffleSplit(X.shape[0], n_iter = 10, test_size = 0.2, random_state = 0)
# Vary the max_depth parameter from 1 to 10
max_depth = np.arange(1,11)
# Calculate the training and testing scores
train_scores, test_scores = curves.validation_curve(DecisionTreeRegressor(), X, y, \
param_name = "max_depth", param_range = max_depth, cv = cv, scoring = 'r2')
# Find the mean and standard deviation for smoothing
train_mean = np.mean(train_scores, axis=1)
train_std = np.std(train_scores, axis=1)
test_mean = np.mean(test_scores, axis=1)
test_std = np.std(test_scores, axis=1)
# Plot the validation curve
pl.figure(figsize=(7, 5))
pl.title('Decision Tree Regressor Complexity Performance')
pl.plot(max_depth, train_mean, 'o-', color = 'r', label = 'Training Score')
pl.plot(max_depth, test_mean, 'o-', color = 'g', label = 'Validation Score')
pl.fill_between(max_depth, train_mean - train_std, \
train_mean + train_std, alpha = 0.15, color = 'r')
pl.fill_between(max_depth, test_mean - test_std, \
test_mean + test_std, alpha = 0.15, color = 'g')
# Visual aesthetics
pl.legend(loc = 'lower right')
pl.xlabel('Maximum Depth')
pl.ylabel('Score')
pl.ylim([-0.05,1.05])
pl.show()
def PredictTrials(X, y, fitter, data):
""" Performs trials of fitting and predicting data. """
# Store the predicted prices
prices = []
for k in range(10):
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, \
test_size = 0.2, random_state = k)
# Fit the data
reg = fitter(X_train, y_train)
# Make a prediction
pred = reg.predict([data[0]])[0]
prices.append(pred)
# Result
print "Trial {}: ${:,.2f}".format(k+1, pred)
# Display price range
print "\nRange in prices: ${:,.2f}".format(max(prices) - min(prices))
def distribution(data, transformed = False):
"""
Visualization code for displaying skewed distributions of features
"""
# Create figure
fig = pl.figure(figsize = (11,5));
# Skewed feature plotting
for i, feature in enumerate(['capital-gain','capital-loss']):
ax = fig.add_subplot(1, 2, i+1)
ax.hist(data[feature], bins = 25, color = '#00A0A0')
ax.set_title("'%s' Feature Distribution"%(feature), fontsize = 14)
ax.set_xlabel("Value")
ax.set_ylabel("Number of Records")
ax.set_ylim((0, 2000))
ax.set_yticks([0, 500, 1000, 1500, 2000])
ax.set_yticklabels([0, 500, 1000, 1500, ">2000"])
# Plot aesthetics
if transformed:
fig.suptitle("Log-transformed Distributions of Continuous Census Data Features", \
fontsize = 16, y = 1.03)
else:
fig.suptitle("Skewed Distributions of Continuous Census Data Features", \
fontsize = 16, y = 1.03)
fig.tight_layout()
#fig.show()
pl.draw()
def evaluate(results, accuracy, f1):
"""
Visualization code to display results of various learners.
inputs:
- learners: a list of supervised learners
- stats: a list of dictionaries of the statistic results from 'train_predict()'
- accuracy: The score for the naive predictor
- f1: The score for the naive predictor
"""
# Create figure
fig, ax = pl.subplots(2, 3, figsize = (11,7))
# Constants
bar_width = 0.3
colors = ['#A00000','#00A0A0','#00A000']
# Super loop to plot four panels of data
for k, learner in enumerate(results.keys()):
for j, metric in enumerate(['train_time', 'acc_train', 'f_train', 'pred_time', 'acc_test', 'f_test']):
for i in np.arange(3):
# Creative plot code
ax[j/3, j%3].bar(i+k*bar_width, results[learner][i][metric], width = bar_width, color = colors[k])
ax[j/3, j%3].set_xticks([0.45, 1.45, 2.45])
ax[j/3, j%3].set_xticklabels(["1%", "10%", "100%"])
ax[j/3, j%3].set_xlabel("Training Set Size")
ax[j/3, j%3].set_xlim((-0.1, 3.0))
# Add unique y-labels
ax[0, 0].set_ylabel("Time (in seconds)")
ax[0, 1].set_ylabel("Accuracy Score")
ax[0, 2].set_ylabel("F-score")
ax[1, 0].set_ylabel("Time (in seconds)")
ax[1, 1].set_ylabel("Accuracy Score")
ax[1, 2].set_ylabel("F-score")
# Add titles
ax[0, 0].set_title("Model Training")
ax[0, 1].set_title("Accuracy Score on Training Subset")
ax[0, 2].set_title("F-score on Training Subset")
ax[1, 0].set_title("Model Predicting")
ax[1, 1].set_title("Accuracy Score on Testing Set")
ax[1, 2].set_title("F-score on Testing Set")
# Add horizontal lines for naive predictors
ax[0, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
ax[1, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
ax[0, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
ax[1, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
# Set y-limits for score panels
ax[0, 1].set_ylim((0, 1))
ax[0, 2].set_ylim((0, 1))
ax[1, 1].set_ylim((0, 1))
ax[1, 2].set_ylim((0, 1))
# Create patches for the legend
patches = []
for i, learner in enumerate(results.keys()):
patches.append(mpatches.Patch(color = colors[i], label = learner))
pl.legend(handles = patches, bbox_to_anchor = (-.80, 2.53), \
loc = 'upper center', borderaxespad = 0., ncol = 3, fontsize = 'x-large')
# Aesthetics
pl.suptitle("Performance Metrics for Three Supervised Learning Models", fontsize = 16, y = 1.10)
pl.tight_layout()
pl.draw()
def feature_plot(importances, X_train, y_train):
# Display the five most important features
indices = np.argsort(importances)[::-1]
columns = X_train.columns.values[indices[:5]]
values = importances[indices][:5]
# Creat the plot
fig = pl.figure(figsize = (9,5))
pl.title("Normalized Weights for First Five Most Predictive Features", fontsize = 16)
pl.bar(np.arange(5), values, width = 0.6, align="center", color = '#00A000', \
label = "Feature Weight")
pl.bar(np.arange(5) - 0.3, np.cumsum(values), width = 0.2, align = "center", color = '#00A0A0', \
label = "Cumulative Feature Weight")
pl.xticks(np.arange(5), columns)
pl.xlim((-0.5, 4.5))
pl.ylabel("Weight", fontsize = 12)
pl.xlabel("Feature", fontsize = 12)
pl.legend(loc = 'upper center')
pl.tight_layout()
pl.draw()
def pca_results(good_data, pca):
'''
Create a DataFrame of the PCA results
Includes dimension feature weights and explained variance
Visualizes the PCA results
'''
# Dimension indexing
dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
# PCA components
components = pd.DataFrame(np.round(pca.components_, 4), columns = good_data.keys())
components.index = dimensions
# PCA explained variance
ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)
variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
variance_ratios.index = dimensions
# Create a bar plot visualization
fig, ax = pl.subplots(figsize = (14,8))
# Plot the feature weights as a function of the components
components.plot(ax = ax, kind = 'bar');
ax.set_ylabel("Feature Weights")
ax.set_xticklabels(dimensions, rotation=0)
# Display the explained variance ratios
for i, ev in enumerate(pca.explained_variance_ratio_):
ax.text(i-0.40, ax.get_ylim()[1] + 0.05, "Explained Variance\n %.4f"%(ev))
# Return a concatenated DataFrame
return pd.concat([variance_ratios, components], axis = 1)
def biplot(good_data, reduced_data, pca):
'''
Produce a biplot that shows a scatterplot of the reduced
data and the projections of the original features.
good_data: original data, before transformation.
Needs to be a pandas dataframe with valid column names
reduced_data: the reduced data (the first two dimensions are plotted)
pca: pca object that contains the components_ attribute
return: a matplotlib AxesSubplot object (for any additional customization)
This procedure is inspired by the script:
https://github.com/teddyroland/python-biplot
'''
fig, ax = pl.subplots(figsize = (14,8))
# scatterplot of the reduced data
ax.scatter(x=reduced_data.loc[:, 'Dimension 1'], y=reduced_data.loc[:, 'Dimension 2'],
facecolors='b', edgecolors='b', s=70, alpha=0.5)
feature_vectors = pca.components_.T
# we use scaling factors to make the arrows easier to see
arrow_size, text_pos = 7.0, 8.0,
# projections of the original features
for i, v in enumerate(feature_vectors):
ax.arrow(0, 0, arrow_size*v[0], arrow_size*v[1],
head_width=0.2, head_length=0.2, linewidth=2, color='red')
ax.text(v[0]*text_pos, v[1]*text_pos, good_data.columns[i], color='black',
ha='center', va='center', fontsize=18)
ax.set_xlabel("Dimension 1", fontsize=14)
ax.set_ylabel("Dimension 2", fontsize=14)
ax.set_title("PC plane with original feature projections.", fontsize=16);
return ax
def cluster_results(reduced_data, preds, centers, pca_samples):
'''
Visualizes the PCA-reduced cluster data in two dimensions
Adds cues for cluster centers and student-selected sample data
'''
predictions = pd.DataFrame(preds, columns = ['Cluster'])
plot_data = pd.concat([predictions, reduced_data], axis = 1)
# Generate the cluster plot
fig, ax = pl.subplots(figsize = (14,8))
# Color map
cmap = cm.get_cmap('gist_rainbow')
# Color the points based on assigned cluster
for i, cluster in plot_data.groupby('Cluster'):
cluster.plot(ax = ax, kind = 'scatter', x = 'Dimension 1', y = 'Dimension 2', \
color = cmap((i)*1.0/(len(centers)-1)), label = 'Cluster %i'%(i), s=30);
# Plot centers with indicators
for i, c in enumerate(centers):
ax.scatter(x = c[0], y = c[1], color = 'white', edgecolors = 'black', \
alpha = 1, linewidth = 2, marker = 'o', s=200);
ax.scatter(x = c[0], y = c[1], marker='$%d$'%(i), alpha = 1, s=100);
# Plot transformed sample points
ax.scatter(x = pca_samples[:,0], y = pca_samples[:,1], \
s = 150, linewidth = 4, color = 'black', marker = 'x');
# Set plot title
ax.set_title("Cluster Learning on PCA-Reduced Data - Centroids Marked by Number\nTransformed Sample Data Marked by Black Cross");
def channel_results(reduced_data, outliers, pca_samples):
'''
Visualizes the PCA-reduced cluster data in two dimensions using the full dataset
Data is labeled by "Channel" and cues added for student-selected sample data
'''
# Check that the dataset is loadable
try:
full_data = pd.read_csv('../resources/customers.csv')
except:
print "Dataset could not be loaded. Is the file missing?"
return False
# Create the Channel DataFrame
channel = pd.DataFrame(full_data['Channel'], columns = ['Channel'])
channel = channel.drop(channel.index[outliers]).reset_index(drop = True)
labeled = pd.concat([reduced_data, channel], axis = 1)
# Generate the cluster plot
fig, ax = pl.subplots(figsize = (14,8))
# Color map
cmap = cm.get_cmap('gist_rainbow')
# Color the points based on assigned Channel
labels = ['Hotel/Restaurant/Cafe', 'Retailer']
grouped = labeled.groupby('Channel')
for i, channel in grouped:
channel.plot(ax = ax, kind = 'scatter', x = 'Dimension 1', y = 'Dimension 2', \
color = cmap((i-1)*1.0/2), label = labels[i-1], s=30);
# Plot transformed sample points
for i, sample in enumerate(pca_samples):
ax.scatter(x = sample[0], y = sample[1], \
s = 200, linewidth = 3, color = 'black', marker = 'o', facecolors = 'none');
ax.scatter(x = sample[0]+0.25, y = sample[1]+0.3, marker='$%d$'%(i), alpha = 1, s=125);
# Set plot title
ax.set_title("PCA-Reduced Data Labeled by 'Channel'\nTransformed Sample Data Circled");
|
"""
Skills function assessment.
Please read the instructions first. Your solutions should
go below this docstring.
"""
###############################################################################
# PART ONE: Write your own function declarations.
# NOTE: We haven't given you function signatures or docstrings for these, so
# you'll need to write your own.
# (a) Write a function that takes a town name as a string and returns
# `True` if it is your hometown, and `False` otherwise.
# (b) Write a function that takes a first and last name as arguments and
# returns the concatenation of the two names in one string.
# (c) Write a function that takes a home town, a first name, and a last name
# as arguments, calls both functions from part (a) and (b) and prints
# "Hi, 'full name here', we're from the same place!", or "Hi, 'full name
# here', I'd like to visit 'town name here'!" depending on what the function
# from part (a) evaluates to.
def is_hometown(town):
"""Determines if a town name is my hometown
>>> is_hometown("Leola")
True
>>> is_hometown("San Leandro")
False
"""
if town == "Leola":
return True
else:
return False
def combine_names(first,last):
"""Concatenates first and last names into one string
>>> combine_names("Megan","Hoffman")
'Megan Hoffman'
"""
full_name = (first + " " + last)
#Must return, because part c needs it returned, as opposed to printed--hence single quotes around returned value in doctest
return full_name
def greets_by_town(town,first,last):
"""Greets a person by name depending on their hometown
>>> greets_by_town("Leola","Michaela","Horst")
Hi, Michaela Horst, we're from the same place!
>>> greets_by_town("Indianola","Zach","Heater")
Hi, Zach Heater, I'd like to visit Indianola!
"""
#print(combine_names(first,last))
if is_hometown(town) == True:
print("Hi, " + combine_names(first,last) + ", we're from the same place!")
else:
print("Hi, " + combine_names(first,last) + ", I'd like to visit " + town + "!")
###############################################################################
# PART TWO
# (a) Write a function, `is_berry()`, which takes a fruit name as a string
# and returns a boolean if the fruit is a "strawberry", "raspberry",
# "blackberry", or "currant."
# (b) Write another function, shipping_cost(), which calculates shipping
# cost by taking a fruit name as a string and calling the `is_berry()`
# function within the `shipping_cost()` function. Your function should
# return 0 if is_berry() == True, and 5 if is_berry() == False.
# (c) Make a function that takes in a fruit name and a list of fruits. It should
# return a new list containing the elements of the input list, along with
# given fruit, which should be at the end of the new list.
# (d) Write a function calculate_price to calculate an item's total cost by
# adding tax and any fees required by state law.
# Your function will take as parameters (in this order): the base price of
# the item, a two-letter state abbreviation, and the tax percentage (as a
# two-digit decimal, so, for instance, 5% will be .05). If the user does not
# provide a tax rate it should default to 5%.
# CA law requires stores to collect a 3% recycling fee, PA requires a $2
# highway safety fee, and in MA, there is a Commonwealth Fund fee of $1 for
# items with a base price of $100 or less and $3 for items over $100. Fees are
# added *after* the tax is calculated.
# Your function should return the total cost of the item, including tax and
# fees.
def is_berry(fruit):
"""Determines if fruit is a berry
>>> is_berry("blackberry")
True
>>> is_berry("currant")
True
>>> is_berry("durian")
False
>>> is_berry("banana")
False
"""
if fruit == "strawberry" or fruit == "raspberry" or fruit == "blackberry" or fruit == "currant":
return True
else:
return False
def shipping_cost(fruit):
"""Calculates shipping cost of fruit
>>> shipping_cost("blackberry")
0
>>> shipping_cost("durian")
5
"""
if is_berry(fruit) == True:
return 0
else:
return 5
def append_to_list(lst, fruit):
"""Returns a new list consisting of the old list with the given number
added to the end.
>>> append_to_list(['banana', 'apple', 'blackberry'], 'dragonfruit')
['banana', 'apple', 'blackberry', 'dragonfruit']
>>> fruits = ['banana', 'apple', 'blackberry']
>>> append_to_list(fruits, 'dragonfruit')
['banana', 'apple', 'blackberry', 'dragonfruit']
>>> fruits
['banana', 'apple', 'blackberry']
"""
#Docstring says with given number added to end? Given fruit?
new_lst = lst[:]
new_lst.append(fruit)
return new_lst
def calculate_price(base_price,state,tax_percent=0.05):
"""Calculate total price of an item, figuring in state taxes and fees.
>>> calculate_price(40, "CA")
43.26
>>> calculate_price(400, "NM")
420.0
>>> calculate_price(150, "OR", 0.0)
150.0
>>> calculate_price(60, "PA")
65.0
>>> calculate_price(38, "MA")
40.9
>>> calculate_price(126, "MA")
135.3
"""
if state != "CA" and state != "PA" and state != "MA":
total_price = base_price * (1 + tax_percent)
if state == "CA":
prefee_price = base_price * (1 + tax_percent)
total_price = prefee_price * 1.03
if state == "PA":
total_price = (base_price * (1 + tax_percent)) + 2
if state == "MA":
prefee_price = base_price * (1 + tax_percent)
if prefee_price <= 100:
total_price = prefee_price + 1
if prefee_price > 100:
total_price = prefee_price + 3
return total_price
###############################################################################
# PART THREE
# NOTE: We haven't given you function signatures and docstrings for these, so
# you'll need to write your own.
# (a) Make a new function that takes in a list and any number of additional
# arguments, appends them to the list, and returns the entire list. Hint: this
# isn't something we've discussed yet in class; you might need to google how to
# write a Python function that takes in an arbitrary number of arguments.
# (b) Make a new function with a nested inner function.
# The outer function will take in a word.
# The inner function will multiply that word by 3.
# Then, the outer function will call the inner function.
# Print the output as a tuple, with the original function argument
# at index 0 and the result of the inner function at index 1.
# Example:
# >>> outer("Balloonicorn")
# ('Balloonicorn', 'BalloonicornBalloonicornBalloonicorn')
def makes_list(lst,*items):
"""Takes in a list and any number of addl arguments, adds args to list
>>> makes_list([1, 2, 3, 4], 5,)
[1, 2, 3, 4, 5]
>>> makes_list(['a','b'],'c','d','e','f')
['a', 'b', 'c', 'd', 'e', 'f']
>>> makes_list([1, 2, 3, 4], 5, 6)
[1, 2, 3, 4, 5, 6]
"""
#Need to make items into a tuple to send in as an argument?
#lst.append(list(items))
for i in items:
lst.append(i)
#Used to make sure fcn was recognizing tuple in arguments
#print("This fcn took in " + str(len(*items)) + " arguments.")
return lst
def outer_word_multiplied(word):
"""Takes in a word, for use in innter fcn--not sure I fully understand the question
>>> outer_word_multiplied('cheese')
('cheese', 'cheesecheesecheese')
>>> outer_word_multiplied('cheddar')
('cheddar', 'cheddarcheddarcheddar')
>>> outer_word_multiplied('mozzarella')
('mozzarella', 'mozzarellamozzarellamozzarella')
"""
def inner_word_multiplied(word):
#Don't think I need a docstring/doctest for this, since it's a nested fcn
#Looked up that the point of inner fcns is to keep them out of the global scope
inner_t = 3 * word
#Trying regular math operations to see if you can multiply strings
#created_tuple[1] = 2 * word
return inner_t
created_tuple = (word, inner_word_multiplied(word))
print(created_tuple)
###############################################################################
# END OF ASSESSMENT: You can ignore everything below.
if __name__ == "__main__":
import doctest
print()
result = doctest.testmod()
if not result.failed:
print("ALL TESTS PASSED. GOOD WORK!")
print()
|
n = int(input())
if n%2 != 0:
print("Weird")
elif n < 6:
print("Not Weird")
elif n < 21:
print("Weird")
else:
print("Not Weird")
|
n = int(input())
total = ""
i = 1
while i < (n+1):
total = total + str(i)
i += 1
print (total) |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
def sigmoid(x):
# changing if x goes less than e^-16
if( x < math.exp(-16)):
x = math.exp(-16)
y = 1 / (1 + math.exp(-x))
return y
def cross_entropy(y, r):
z = 1-y
if(z < math.exp(-16)):
z = math.exp(-16)
s = (r * math.log(y) + (1-r) * math.log(z))
return s
def cross_entropy_2(y, r):
s = float(0)
for i in range(0, len(y)):
z = 1 - y[i][0]
if(z < math.exp(-16)):
z = math.exp(-16)
s += (r[i][0] * math.log(y[i][0]) + (1-r[i][0]) * math.log(z))
return ((-1) * s)
def classification_error(Y, R):
c=0
for i in range(0,len(Y)):
#print(Y[i]," : ",R[i][0])
if(Y[i] != R[i]):
c+=1
#print(c)
return (c / len(Y)) * 100
def plot_graph(X,Y):
pass
# method for logistc
def logistic_regression(X, steps, eta, R):
# w0, w1, w2, w3, ..... w60 so total 61 weights
w0 = 0.5
W = np.full((60,1), 0.5)
cross_entropy_list = []
# making vectorize sigmoid_function
sigmoid_vector = np.vectorize(sigmoid)
cross_entropy_vector = np.vectorize(cross_entropy)
#print(X.shape)
#print(W.shape)
#print(np.dot(X,W) + w0)
# gradient descent 50 rounds
for i in range(0, steps):
entropy_list = []
# taking product of [180,60] * [60,1] gives [60,1]
# adding w0 to above
Z = np.dot(X,W) + w0
Y = sigmoid_vector(Z)
# taking difference between R - Y
diff = R - Y
# updating a new w0
w0 = w0 + (diff * eta)
# temp will be a matrix of 180
sum_prod = np.dot(X.T, diff) * eta
# updating the W, taking transpose bec sum_prod is of form [1, 60]
W = W + sum_prod
# calculating intermediate cross entropy for each iteration
entropy_error = ((cross_entropy_vector(Y, R).sum(axis = 0))[0] * (-1))
cross_entropy_list.append(entropy_error)
print(len(cross_entropy_list))
# with final values of w0 and w1,w2,w3 ... w60
Z = np.dot(X,W) + w0
Y = sigmoid_vector(Z)
Y_class = map(lambda x: 1 if x > 0.5 else 0, Y)
entropy_error = ((cross_entropy_vector(Y, R).sum(axis = 0))[0] * (-1))
# Debugg the cross entropy error value
# print(cross_entropy_2(Y.tolist(), R.tolist()))
# W2 regularization
W2 = np.square(W)
W2 = W2.sum(axis = 0)
W2 = math.sqrt(W2[0])
# calculate and return cross_entropy and classification error as tuple
return (entropy_error, classification_error(Y_class,R.tolist()), W2)
def main():
# making pandas data frame
data = pd.read_csv('sonar.csv', header=-1)
# class data R(t) in our equation, maping to 1 - C1,0 - C2
R = data[60]
value = {'Mine' : 1, 'Rock' : 0}
R = R.map(value).reshape((180,1))
# print(R.shape)
# drooping last column from data
X = data.drop(data.columns[[-1]], axis=1)
# value for eta
eta = [0.001,0.01,0.05,0.1,0.5,1.0,1.5]
for i in range(0,len(eta)):
# calling method for logistic regression
print(logistic_regression(X, 50,i, R))
if __name__ == "__main__":
main()
|
# python3
# this program takes list as input and returns new list without duplicates
user_list = list(input("enter list with some duplicates: "))
def remove_duplicates1(user_list):
user_list.sort()
i = len(user_list) - 1
while i > 0:
if user_list[i] == user_list[i - 1]:
user_list.pop(i)
i -= 1
return user_list
# remove_duplicates2 copied from here https://gist.github.com/prgrm/12788827aa38748214df#file-ex13
def remove_duplicates2(user_list):
new_list = []
for i in user_list:
if i not in new_list:
new_list.append(i)
return new_list
def remove_duplicates3(user_list):
return sorted(list(set(user_list)))
print("method 1", remove_duplicates1(user_list))
print("method 2", remove_duplicates2(user_list))
print("method 3", remove_duplicates3(user_list))
|
# python3
# this is example of list comprehensions
# for (set of values to iterate):
# if (conditional filtering):
# output_expression()
# TO
# [output_expression() for(set of values to iterate) if(conditional filtering)]
import random
list = random.sample(range(100), 10)
# it generates random list with length 10
even_num_list = [i for i in list if i % 2 == 0]
# prints all even numbers in list
print(even_num_list)
|
import numpy as np
import mysklearn.mypytable as mypytable
import operator
import copy
import random
def mean(x):
"""Computes the mean of a list of values
"""
return sum(x)/len(x)
def compute_slope_intercept(x, y):
"""
"""
mean_x = mean(x)
mean_y = mean(y)
m = sum([(x[i] - mean_x) * (y[i] - mean_y) for i in range(len(x))]) / sum([(x[i] - mean_x) ** 2 for i in range(len(x))])
# y = mx + b => b = y - mx
b = mean_y - m * mean_x
return float(m), float(b)
def compute_euclidean_distance(v1, v2):
"""
"""
assert len(v1) == len(v2)
dist = np.sqrt(sum([(v1[i] - v2[i]) ** 2 for i in range(len(v1))]))
return dist
def scale(vals, test_vals):
"""
"""
scaled_vals_list = []
maxs_list = []
mins_list = []
# for each list in list vals, get each values max and min and store in a list accordingly
for i in range(len(vals[0])):
maxs_list.append(max([val[i] for val in vals]))
mins_list.append(min([val[i] for val in vals]))
# for each list in list vals, scale each value according to the max and min to be between [0, 1]
for row in vals:
curr = []
for i in range(len(row)):
curr.append((row[i]-mins_list[i])/(maxs_list[i]-mins_list[i]))
scaled_vals_list.append(curr)
# for each list in list test_vals, scale each value according to the max and min to be between [0, 1]
for row in test_vals:
curr = []
for i in range(len(row)):
curr.append((row[i]-mins_list[i])/(maxs_list[i]-mins_list[i]))
scaled_vals_list.append(curr)
# returns all scaled values from the vals list, then the scaled values from the test_vals list
return scaled_vals_list[:len(vals)], scaled_vals_list[len(vals):]
def kneighbors_prep(scaled_X_train, scaled_X_test, n_neighbors):
"""
"""
scaled_X_train = copy.deepcopy(scaled_X_train)
scaled_X_test = copy.deepcopy(scaled_X_test)
# for each scaled list in scaled_X_train
for i, instance in enumerate(scaled_X_train):
distance = compute_euclidean_distance(instance, scaled_X_test)
instance.append(i) # append the original row index
instance.append(distance) # append the distance
scaled_X_train_sorted = sorted(scaled_X_train, key=operator.itemgetter(-1)) # sort the list in assending order
top_k = scaled_X_train_sorted[:n_neighbors] # get a list of the top_k neighbors
distances_list = []
indices_list = []
# for each row in the top_k list, append the distances and indices to their own lists
for row in top_k:
distances_list.append(row[-1])
indices_list.append(row[-2])
# return the distances and indices lists
return distances_list, indices_list
def get_label(labels):
"""
"""
label_types = []
# for each value in the labels list
for val in labels:
# if we have not see that label type
if val not in label_types:
label_types.append(val) # append to list of label types
count_list = [0 for label_type in label_types]
# for value in label types
for i, val in enumerate(label_types):
for label in labels:
# if the value is == to the label then incremept the count for that position
if val == label:
count_list[i] += 1
max_count = 0
label_prediction = ''
# for value in count_list
for i, val in enumerate(count_list):
if val > max_count:
label_prediction = label_types[i]
return label_prediction
def get_unique(vals):
"""
"""
unique = []
# for values in the vals list
for val in vals:
if val not in unique:
unique.append(val)
return unique
def group_by(x_train, y_train):
"""
"""
unique = get_unique(y_train)
grouped = [[] for _ in unique]
# for each value in y_train
for i, val in enumerate(y_train):
for j, label in enumerate(unique):
if val == label:
grouped[j].append(i)
return grouped
def shuffle(X, y):
"""
"""
for i in range(len(X)):
rand_index = random.randrange(0, len(X)) # [0, len(X))
X[i], X[rand_index] = X[rand_index], X[i] # this is the temporary value swap but in one line
if y is not None:
y[i], y[rand_index] = y[rand_index], y[i]
def get_from_folds(X_vals, y_vals, train_folds, test_folds):
"""
"""
X_train = []
y_train = []
X_test = []
y_test = []
# for each fold
for row in train_folds:
for i in row:
X_train.append(X_vals[i])
y_train.append(y_vals[i])
# for each test fold
for row in test_folds:
for i in row:
X_test.append(X_vals[i])
y_test.append(y_vals[i])
return X_train, y_train, X_test, y_test |
def linkage(T):
"""
This function converts a tree from our current format to a linkage matrix Z
and leaf node list V.
"""
condensations = sorted([v for v in T if len(v)==2])
increasing = condensations[0][0]<T[condensations[0]][0]
inner_nodes = sorted(list(set(T.values())), key=lambda e: e[0], reverse=not increasing)
base = condensations[0][0]
V = [v[1] for v in condensations]
L = {v:i for i,v in enumerate(condensations)}
Z = []
k = len(condensations)
for w in inner_nodes:
children = [v for v in condensations if T[v]==w]
x = children[0]
for y in children[1:]:
z = tuple([w[0]]+sorted(x[1:]+y[1:]))
Z.append([L[x],L[y],w[0],len(z[1:])])
L[z] = k
x = z
k += 1
for v in children:
condensations.remove(v)
condensations.append(w)
Y = [[a,b,base-c,d] for (a,b,c,d) in Z]
reordered_Y, reordered_V = reorder(Y,V)
return reordered_Y, reordered_V
def newick(T):
"""
The next function converts a tree from our current format to the standard
Newick format.
"""
condensations = [v for v in T if len(v)==2]
increasing = condensations[0][0]<T[condensations[0]][0]
inner_nodes = sorted(list(set(T.values())), key=lambda e: e[0], reverse=not increasing)
root = inner_nodes.pop()
mapping = {v:str(v[1])+':'+str(abs(T[v][0]-v[0])) for v in condensations}
for w in inner_nodes:
children = [v for v in condensations if T[v]==w]
mapping[w] = '('+','.join([mapping[v] for v in children])+'):'+str(abs(T[w][0]-w[0]))
for v in children:
condensations.remove(v)
condensations.append(w)
children = [v for v in condensations if T[v]==root]
return '('+','.join([mapping[v] for v in children])+');'
def reorder(Z, V):
"""
This function is a helper for the linkage function that reorders the leaf
nodes to prevent crossings in the dendrogram.
"""
# Check if the linkage matrix is constructed properly.
for i in range(len(Z)-1):
if Z[i][2]>Z[i+1][2]:
raise Warning("The rows in the linkage matrix are not monotonically nondecreasing by distance; crossings may occur in the dendrogram.")
break
# Below, we have the following variables:
# m: index for reordered leaf nodes
# n: number of leaf nodes
# queue: list of inner nodes, which we append and pop as we work from right to left and from top to bottom in the dendrogram.
# order: dictionary for the reordering of the leaf nodes
# transpose_order: transpose the key, value pairs in order
m = 0
n = len(V)
queue = [len(Z)-1]
order = {}
transpose_order = {}
# Continue while inner nodes remain.
while len(queue):
# Consider the right-most inner node.
i = queue.pop()
subqueue = []
# For the children of the inner node, reorder them if they are leaf nodes and append them if they are inner nodes.
for j in reversed(list(range(2))):
if Z[i][j]<n:
order[Z[i][j]] = n-m-1
transpose_order[n-m-1] = Z[i][j]
m += 1
else:
subqueue.append(Z[i][j]-n)
subqueue = sorted(subqueue, key=lambda i:Z[i][2])
queue.extend(subqueue)
# Construct the linkage matrix and list of leaf nodes for the reordered leaf nodes.
reordered_Z = [[y for y in z] for z in Z]
for i in range(len(Z)):
for j in reversed(list(range(2))):
if Z[i][j]<n:
reordered_Z[i][j] = order[Z[i][j]]
reordered_V = [V[transpose_order[i]] for i in range(n)]
# Return the results.
return reordered_Z, reordered_V
|
x = 1
if x == 1 :
print("x is ", x)
while x != 10:
print(x)
x += 1
print("Done!")
# https://www.learnpython.org/en/Variables_and_Types
one = 1
two = 2
three = one + two
print( "one + two = ", three )
hello = "hello"
world = "world"
print( hello + " " + world)
a,b = 3,4
print(a,b)
print("String replacement: %s is %d years old." % ("Eric", 23) )
# https://www.learnpython.org/en/Lists
numbers = []
strings = []
names = ["John","Eric","Jessica"]
second_name = names[1]
numbers.append(1)
numbers.append(2)
numbers.append(3)
strings.append("One")
strings.append("Two")
strings.append("Three")
print(numbers)
print(strings)
print("The second name on the names list is %s." % second_name)
# basic operators
number = 1 + 2 * 3 / 4.0
print(number)
remainder = 11 % 3
print(remainder)
squared = 7 ** 2
cubed = 2** 3
print(squared)
print(cubed)
print("Hello" + " " + "World")
lots_of_hellos = "hello..." * 10
print(lots_of_hellos)
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)
print([9,8,7] * 3)
# test
# objective: 10 instances and concat both into big_list
x = object()
y = object()
x_list = [x] * 10
y_list = [y] * 10
big_list = x_list + y_list
print( "x_list contains %d objects" % len(x_list))
print( "y_list contains %d objects" % len(y_list))
print( "big_list contains %d objects" % len(big_list))
if x_list.count(x) == 10 and y_list.count(y) == 10:
print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
print("Great!")
# strings
print("Strings are %s and %d of them are better. %f floats are wild, but %.2f contained floats are best. What about %s arrays/lists!? " % ("cool",25, 5.1241613, 5.1241613, [1,2,3]))
print("String len(%s) = %d " % ("This is the total length of this string...",len("This is the total length of this string...")))
a_string = "This is a totally new string."
print("The index for 'o' in this string, '%s', is '%d'. " % (a_string, a_string.index("o")))
print("The count for 'o' in this string, '%s', is '%d'. " % (a_string, a_string.count("o")))
print("The array call [11:25] in this string, '%s', is '%s'. " % (a_string, a_string[11:25]))
print("The sliced string [11:25:2] in this string, '%s', is '%s'. " % (a_string, a_string[11:25:2]))
print("The sliced string reverse [::-1] in this string, '%s', is '%s'. " % (a_string, a_string[::-1]))
print("The string upper() and lower() in this string, '%s', is '%s' and '%s'. " % (a_string, a_string.upper(), a_string.lower()))
print("String starts with 'This' = %s (case sensitive). " % a_string.startswith("This"))
print("String ends with 'afadgsdg' = %s (case sensitive). " % a_string.endswith("afadgsdg"))
print("String split at space = '%s' " % a_string.split(" "))
# string[from:to:slice]
# conditions
x = 2
print( x == 2)
print( x == 3)
print( x < 3)
y = 19
if x > 1 and y < 20:
print("AND Conditions are met 01")
if x < 5 or y > 20:
print("OR Conditions are met 02")
if "John" in ["Eric","John","Sam"]:
print("John was in array of names.")
pass
elif "John" in ["new","list"]:
print("else if (elif) condition met.")
pass
else:
pass
y = 2
print( x is y)
print( "False bool using not = %s " % (not False) )
# loops
for x in range(5):
print(x)
print("break...")
for x in range(3,6):
print(x)
print("break...")
for x in range(3,8,2):
print(x)
print("break...")
count = 0
while count < 15:
print("While count #%d" % count)
count += 1
count = 0
while True:
count+=1
if count >= 15:
break
if count % 2 == 0:
continue
print("While using break/continue, #%d" % count)
else:
print("While loop finished.")
for x in range(10):
print("For loop x in range(10) = %d " % x)
else:
print("For loop complete.")
# functions
def my_function(user, age):
print("Welcome %s, you still look splendid, even at %d!" % (user,age))
my_function("Josh",24)
# classes & objects
class myClass:
variable = "blah"
def help(self):
print("Function in class ")
obj = myClass()
print("Accesing class objects. obj.variable = %s" % obj.variable)
obj.variable = "new variable"
print("Changing then Accesing class objects. obj.variable = %s" % obj.variable)
obj.help()
# dictionaries
# dics are data types
phonebook = {}
phonebook["John"] = 5556421
phonebook["Sarah"] = 5579421
phonebook["Sam"] = 500721
print(phonebook)
# or
phonebook = {
"John" : 3456789,
"Sam" : 2345622,
"Jill" : 13513535,
}
print(phonebook)
for name, number in phonebook.items():
print("Phone number for %s is %d " % (name,number))
del phonebook["Sam"] # or
if "Sam" in phonebook:
phonebook.pop("Sam")
if "Sam" not in phonebook:
phonebook["New Sam"] = 12432542
print("Removed Sam and added New Sam")
print(phonebook)
# modules
import urllib
#urllib.parse("https://www.google.com/")
help(urllib) |
def test(x):
even = lambda z: True if z == k else odd(z+-1)
odd = lambda z: False if z == k else even(z+-1)
k = 0
return even(x)
print test(4)
|
x = 5
y = 2
l = [1,2,3]
b = x or y
z = not b
q = not (not l) and not x or not y
z = q or z and not l
print z
print q
print (not []) or (not [])
|
def foldl_p(f, init, lst, idx, length):
return init if idx == length else foldl_p(f, f(init, lst[idx]), lst, idx+1, length)
def foldl(f, init, lst, l):
return foldl_p(f, init, lst, 0, l)
def my_sum(lst, length):
return foldl(lambda x, y: x + y, 0, lst, length)
def mul(x, y):
return 0 if x == 0 or y == 0 else y + mul(x+-1, y)
def my_map(f, lst, length):
def map_p(f, lst, idx, length):
return [] if idx == length else [f(lst[idx])] + map_p(f, lst, idx+1, length)
return map_p(f, lst, 0, length)
mylist = [1,2,3,4,5]
print my_sum( my_map(lambda x: x + 1, mylist, 5), 5 )
|
x = 5
y = 0
z = [1,2,3,4,5,6,7,8,9]
print (z if y else False) if x else True
|
import csv
####### EXAMPLES ########
''' This is a file of examples of how to open the csv file of data
and get things out of it. Please add to this when you find interesting
things.
Please add anything you find as a function, as below, so people can use it
in their code. Act like you are building an API.'''
### Nick ###
def show_data():
"""This is an example of how to open the CSV file for reading.
Simply pattern match these steps and you can iterate through the rows
in the table.
NOTE: I cut off the iteration at 10 here, just to show you how it looks.
Feel free to mess around with this and see what you can do. Try not to
print the whole table--it has almost 6 million rows."""
with open("ScansforStudents.csv", "rU") as csvfile:
reader = csv.reader(csvfile, delimiter = ',', quotechar = '|')
k = 0
for row in reader:
print(row)
if k == 100:
break
k += 1
############# |
#!/usr/bin/env python3
'''
template_sample.py
Jeff Ondich
6 November 2020
Using templates in Flask.
'''
import sys
import argparse
import flask
import json
app = flask.Flask(__name__)
@app.route('/')
def home():
return flask.render_template('index.html')
@app.route('/hello/<name>')
def hello(name):
return flask.render_template('hello.html', user_name=name)
@app.route('/shared-header/')
def shared_header():
return flask.render_template('shared-header/index.html')
@app.route('/shared-header/<path:path>')
def shared_header_catchall(path):
return flask.render_template('shared-header/' + path)
if __name__ == '__main__':
parser = argparse.ArgumentParser('A sample Flask application demonstrating templates.')
parser.add_argument('host', help='the host on which this application is running')
parser.add_argument('port', type=int, help='the port on which this application is listening')
arguments = parser.parse_args()
app.run(host=arguments.host, port=arguments.port, debug=True)
|
#!/usr/bin/env python3
'''
api-test.py
Jeff Ondich, 11 April 2016
Updated 7 October 2020
An example for CS 257 Software Design. How to retrieve results
from an HTTP-based API, parse the results (JSON in this case),
and manage the potential errors.
'''
import sys
import argparse
import json
import urllib.request
API_BASE_URL = 'http://api.ultralingua.com/api/2.0'
API_KEY = 'cs257'
def get_root_words(word, language):
'''
Returns a list of root words for the specified word in the
specified language. The root words are represented as
dictionaries of the form
{'root':root_word, 'partofspeech':part_of_speech}
For example, the results for get_root_words('thought', 'eng')
would be:
[{'root':'thought', 'partofspeech':'noun'},
{'root':'think', 'partofspeech':'verb'}]
The language parameter must be a 3-letter ISO language code
(e.g. 'eng', 'fra', 'deu', 'spa', etc.).
Raises exceptions on network connection errors and on data
format errors.
'''
url = f'{API_BASE_URL}/stems/{language}/{word}?key={API_KEY}'
data_from_server = urllib.request.urlopen(url).read()
string_from_server = data_from_server.decode('utf-8')
root_word_list = json.loads(string_from_server)
result_list = []
for root_word_dictionary in root_word_list:
root = root_word_dictionary.get('text', '')
part_of_speech = root_word_dictionary.get('partofspeech', {})
part_of_speech_category = part_of_speech.get('partofspeechcategory', '')
result_list.append({'root':root, 'partofspeech':part_of_speech_category})
return result_list
def get_conjugations(verb, language):
'''
Returns a list of conjugations for the specified verb in the
specified language. The conjugations are represented as
dictionaries of the form
{'text':..., 'tense':..., 'person':..., 'number':...}
For example, the results for get_root_words('parler', 'fra')
would include:
[{'text':'parle', 'tense':'present', 'person':'first', 'number':'singular'},
{'text':'parles', 'tense':'present', 'person':'second', 'number':'singular'},
...
]
The language parameter must be a 3-letter ISO language code
(e.g. 'eng', 'fra', 'deu', 'spa', etc.).
Raises exceptions on network connection errors and on data
format errors.
'''
url = f'{API_BASE_URL}/conjugations/{language}/{verb}?key={API_KEY}'
data_from_server = urllib.request.urlopen(url).read()
string_from_server = data_from_server.decode('utf-8')
verbs = json.loads(string_from_server)
result_list = []
for verb in verbs:
if 'conjugations' not in verb:
print(f'Unexpected response format for {verb}', file=sys.stderr)
continue
for conjugation_dictionary in verb['conjugations']:
text = conjugation_dictionary.get('surfaceform', '')
part_of_speech = conjugation_dictionary.get('partofspeech', {})
tense = part_of_speech.get('tense', '')
person = part_of_speech.get('person', '')
number = part_of_speech.get('number', '')
result_list.append({'text':text, 'tense':tense, 'person':person, 'number':number})
return result_list
def main(args):
if args.action == 'root':
root_words = get_root_words(args.word, args.language)
for root_word in root_words:
root = root_word['root']
part_of_speech = root_word['partofspeech']
print(f'{root} [{part_of_speech}]')
elif args.action == 'conjugate':
conjugations = get_conjugations(args.word, args.language)
for conjugation in conjugations:
text = conjugation['text']
tense = conjugation['tense']
person = conjugation['person']
number = conjugation['number']
print(f'{text} [{tense} {person} {number}]')
if __name__ == '__main__':
# When I use argparse to parse my command line, I usually
# put the argparse setup here in the global code, and then
# call a function called main to do the actual work of
# the program.
parser = argparse.ArgumentParser(description='Get word info from the Ultralingua API')
parser.add_argument('action',
metavar='action',
help='action to perform on the word ("root" or "conjugate")',
choices=['root', 'conjugate'])
parser.add_argument('language',
metavar='language',
help='the language as a 3-character ISO code',
choices=['eng', 'fra', 'spa', 'deu', 'ita', 'por'])
parser.add_argument('word', help='the word you want to act on')
args = parser.parse_args()
main(args)
|
# Uses python3
import sys
# https://www.youtube.com/watch?v=Vj5IOD7A6f8
# the exact algorthim is at 27:03
total_count = 0
def merge(left_array,right_array):
i, j, inversion_counter = 0,0,0
final = []
while i < len(left_array) and j < len(right_array):
if left_array[i] <= right_array[j]:
final.append(left_array[i])
i += 1
else:
final.append(right_array[j])
# This formula is from the youtube video
# Correctness please follow up
inversion_counter += len(left_array) - i
j +=1
final += left_array[i:]
final += right_array[j:]
return final, inversion_counter
def merge_sort(array):
global total_count
if len(array)==1:
return array #nothing to sort
midpoint = len(array) // 2
left_arr = merge_sort(array[:midpoint])
right_arr = merge_sort(array[midpoint:])
sorted_arr,temp = merge(left_arr,right_arr)
total_count += temp
return sorted_arr
n = int(input())
seq = [int(i) for i in input().split()]
merge_sort(seq)
print(total_count) |
# Uses python3
import sys
#https://www.coursera.org/learn/algorithmic-toolbox/discussions/weeks/4/threads/IP3NQ-lEEeWFuw7QEATDpw
"""
get_majority(A[1...n]):
if n == 1:
return A[1]
{If there is only one element, it is the majority element}
mid = n/2
a = get_majority(A[1..mid])
b = get_majority(A[mid+1...n])
if a is not -1:
count occurence of a in A
if count > n/2:
return a
{this means a is the majority element for whole array}
{Now repeat the procedure with majority element b}
if b is not -1:
count occurence of b in A
if count > n/2:
return b
{this means b is the majority element for whole array}
return -1 {if there is no majority element}
"""
def get_majority_element(seq, left, right):
if left+1 == right:
# only one element left, thus it must be the greatest
return seq[left]
# print(seq)
midpoint = (left+right)//2
greatest_left = get_majority_element(seq,left, midpoint)
greatest_right = get_majority_element(seq,midpoint,right)
majority_cutoff = (right-left)//2 #this will be the number of elements
count_left, count_right = 0,0
for number in seq[left:right]:
if number == greatest_left:
count_left+=1
if number == greatest_right:
count_right +=1
if count_left>majority_cutoff and greatest_left != -1:
return greatest_left
elif count_right > majority_cutoff and greatest_right != -1:
return greatest_right
else:
return -1
n = int(input())
seq_input = [int(i) for i in input().split()]
# seq_input = [1,2,3,4,5,6,7,8,8,8,8,8,8,8,8]
# n = len(seq_input)
# get_majority_element(seq_input, 0, n)
print(int(get_majority_element(seq_input, 0, n) != -1))
|
# Uses python3
import sys
bag_size = 10
items = 3
import numpy as np
# define a matrix of 11 columns, 3 items
# fill in the first row
# weight, value pair
# code in the lecture notes
items_list = [(4, 16), (6, 30), (3, 14), (2, 9)]
n_items = len(items_list)
n_cols = 10
matrix = np.zeros((n_items + 1, n_cols + 1))
for item_index in range(1, n_items + 1):
for weight_index in range(1, n_cols + 1):
# init by assuming that the most optimal choice is same as the previous choice
# i.e no item is added since 2 items is optimal already
matrix[item_index, weight_index] = matrix[item_index - 1, weight_index]
# Get the current item and attributes
current_item_weight, current_item_value = items_list[item_index - 1]
# if the current item is less than the weight treshold,
if current_item_weight <= weight_index:
# get the index without the weight in the previous row
# e.g in the 3rd row, go to the 2nd row and pick the corresponding index
val = (
matrix[item_index - 1, weight_index - current_item_weight]
+ current_item_value
)
# if the new value is better, assign to new value instead
if matrix[item_index, weight_index] < val:
matrix[item_index, weight_index] = val
def optimal_weight(W, w):
# write your code here
result = 0
for x in w:
if result + x <= W:
result = result + x
return result
if __name__ == "__main__":
input = sys.stdin.read()
W, n, *w = list(map(int, input.split()))
print(optimal_weight(W, w))
|
"""
Day 22, part 1, a card shuffler
https://adventofcode.com/2019/day/22
"""
from typing import List
def new_stack(deck: List[int]) -> List[int]:
return [num for num in reversed(deck)]
def cut(deck: List[int], n: int) -> List[int]:
return deck[n:] + deck[:n]
deck = [num for num in range(10)]
assert new_stack(deck) == [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
assert cut(deck, 3) == [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
assert cut(deck, -4) == [6, 7, 8, 9, 0, 1, 2, 3, 4, 5]
def increment(deck: List[int], n: int) -> List[int]:
shuffled = [0 for _ in range(len(deck))]
for i, card in enumerate(deck):
shuffled[(i * n) % len(deck)] = deck[i]
return shuffled
assert increment(deck, 3) == [0, 7, 4, 1, 8, 5, 2, 9, 6, 3]
test1 = '''
deal with increment 7
deal with increment 9
cut -2
'''
test2 = '''
deal into new stack
cut -2
deal with increment 7
cut 8
cut -4
deal with increment 7
cut 3
deal with increment 9
deal with increment 3
cut -1
'''
print(deck)
for line in test2.split('\n'):
#line = line.strip()
if line == 'deal into new stack':
deck = new_stack(deck)
elif line.startswith('deal with'):
number = int(line.split()[-1])
deck = increment(deck, number)
elif line.startswith('cut'):
number = int(line.split()[-1])
deck = cut(deck, number)
print(deck)
factory_deck = [num for num in range(10007)]
with open('input.txt') as f:
new = cutting = inc = 0
for line in f:
#line = line.strip()
if line.startswith('deal into'):
factory_deck = new_stack(factory_deck)
new += 1
elif line.startswith('deal with'):
number = int(line.split()[-1])
factory_deck = increment(factory_deck, number)
inc += 1
elif line.startswith('cut'):
number = int(line.split()[-1])
factory_deck = cut(factory_deck, number)
cutting += 1
print(new, cutting, inc)
print(factory_deck.index(2019))
print(factory_deck[2430]) |
#!/usr/bin/env python3
string = "This is a string"
print(string.count("a")) #we can use .count to count things like how many s's.
integer = 4
print (integer.real)
|
"""
6.8 문제 : 시계 맞추기
- 난이도 : 중
"""
# 2021/02/16 15:34 ~ 16:12
# 내가 생각했던 방법이 큰 그림에서는 비슷함.
# 하나의 스위치는 최대 3번까지 누를 수 있고 4번 누르면 처음 상태로 돌아가는 것을 생각해야함.
INF = int(1e9)
switch = [
[0, 1, 2],
[3, 7, 9, 11],
[4, 10, 14, 15],
[0, 4, 5, 6, 7],
[6, 7, 8, 10, 12],
[0, 2, 14, 15],
[3, 14, 15],
[4, 5, 7, 14, 15],
[1, 2, 3, 4, 5],
[3, 4, 5, 9, 13]
]
def check(data):
isEnd = True
for i in range(16):
if data[i] != 12:
isEnd = False
return isEnd
def push(data, num_switch):
for i in switch[num_switch]:
data[i] += 3
if data[i] > 12:
data[i] -= 12
# 0번 스위치 부터 9번 스위치까지 눌러보면서 하나의 스위치가 몇 번씩 눌렸는지 누적함
def click(data, num_switch):
# def click(data, num_click)
# if check(data):
# return num_click
if num_switch == 10:
if check(data):
return 0
else:
return INF
result = INF
# for i in range(10):
# for j in switch[i]:
# data[j] += 3
# if data[j] > 12:
# data[j] -= 12
# candid = click(data, num_click + 1)
# result = min(result, candid)
# for j in switch[i]:
# data[j] -= 3
# if data[j] <= 0:
# data[j] += 12
# 모든 스위치는 4번 누르면 처음 상태로 돌아간다.
# i가 스위치를 누른 횟수를 저장함(어떤 스위치든 최대 3번까지 누를 수 밖에 없다.)
for i in range(4):
result = min(result, i + click(data, num_switch + 1))
push(data, num_switch)
return result
for tc in range(int(input())):
data = list(map(int, input().split()))
print(click(data, 0)) |
"""
8.11 예제 : 타일링 방법의 수 세기
- 난이도 : 하
- 부분 문제의 수는 O(n)이고 각각의 값을 계산하는데 O(1)의 시간이 들기 때문에
- 시간 복잡도 : O(n)
"""
# 부분 문제 정의하기
# tiling(n) = 2 * n 크기의 사각형을 2*1 크기의 타일로 덮는 방법을 의미
# 위 함수가 한 번 호출될 때 할 수 있는 선택은 세로 타일 하나를 쓰냐, 가로 타일 두 개를 쓰냐로 나뉜다.
# 점화식 tiling(n) = tiling(n - 1) + tiling(n - 2)
# n = 100이면 64bit 정수형 표현 범위도 훌쩍 넘어가기 때문에 MOD로 나눈 값을 반환하기로 함
MOD = 1000000007
cache = [-1] * 101
def tiling(width):
# 기저 사례 : width가 1 이하
if width <= 1:
return 1
# 메모이제이션
if cache[width] != -1:
return cache[width]
cache[width] = (tiling(width - 1) + tiling(width - 2)) % MOD
return cache[width]
print(tiling(100)) |
"""
6.5 문제 : 게임판 덮기
- 난이도 : 하
"""
# 2021/02/16 13:55 ~ 14:59
# 가능한 블럭의 모양을 배열을 통해 구현
"""
def checkComplete(temp):
for i in range(h):
for j in range(w):
if temp[i][j] == '.':
return False
return True
def turnBlock(center, wing1, wing2):
pass
def putBlock(temp, r, c):
center = (r, c)
wing1 = (r-1, c)
wing2 = (r, c+1)
"""
# 블록의 모양을 상대적인 인덱스로 표현
block_type = [[(0, 0), (1, 0), (0, 1)],
[(0, 0), (0, 1), (1, 1)],
[(0, 0), (1, 0), (1, 1)],
[(0, 0), (1, 0), (1, -1)]]
# t : 블럭 모양
# delta : 현재 게임판에 블럭 설치 여부 결정(1 : 설치 / -1 : 제거)
def setBlock(board, r, c, t, delta):
possible = True
for i in range(3):
nr = r + block_type[t][i][0]
nc = c + block_type[t][i][1]
if nr < 0 or nr >= h or nc < 0 or nc >= w:
possible = False
else:
board[nr][nc] += delta
# 값이 1이 넘어갈 경우 블록이 중복되어 설치되어있다고 간주
if board[nr][nc] > 1:
possible = False
return possible
def cover(board):
h = len(board)
w = len(board[0])
# 아직 채워지지 않은 가장 위쪽 왼쪽에 있는 칸을 찾음
r, c = -1, -1
for i in range(h):
for j in range(w):
if board[i][j] == 0:
r = i
c = j
break
if r != -1:
break
# 기저 사례 : 모든 칸을 채웠으면 1을 반환
if r == -1:
return 1
result = 0
for t in range(4):
# 게임판을 덮을 수 있는 경우, 재귀 호출을 통해 반복
if setBlock(board, r, c, t, 1):
result += cover(board)
# 설치한 블럭 제거
setBlock(board, r, c, t, -1)
return result
for tc in range(int(input())):
h, w = map(int, input().split())
board = []
for i in range(h):
board.append(list(map(int, input().split())))
"""
temp = [[0] * w for _ in range(h)]
for i in range(h):
for j in range(w):
temp[i][j] = board[i][j]
"""
print(cover(board))
|
# For loop
# Initialize three list
numbers = [10, 20, 30, 40]
vehicles = ['cars', 'bikes', 'buses', 'trucks']
age = [40, 'fifty', 60, 'seventy']
# List can have numbers and strings
# Execute for loop using the numbers in numbers list
for count in numbers:
print 'This is number: %d' % count
# %d indicates the list contains numbers
# Execute for loop using the vehicle names in vehicles list
for automobiles in vehicles:
print 'A type of automobile: %s' % automobiles
# %s indicates the list contains strings
# Execute for loop using numbers and strings in age list
for i in age:
print 'My age is: % r' % i
# %r when we don't know what exactly is in the list
# Initialize an empty element list, data will be appended to this list later
element = []
# Execute for loop using the numbers in the range 0 to 8
for j in range(0, 8):
print 'Adding to the list: %d' % j
element.append(j)
# Appending data to the element list
# Execute the for loop using the data appended in the element list
for k in element:
print 'Retrieving back from the list: %d' % k
|
def poweroftwo(num):
num = int(num)
result = 2 ** num
result = int(result)
print("The result is", result)
return result
def main():
num1 = input("Give a number:")
poweroftwo(num1)
if __name__ == '__main__':
main() |
def openfile():
fname=input("Give the file name: ")
try:
sourcefile = open(fname, 'r')
content = sourcefile.read()
sourcefile.close()
return content
except IOError:
return False
def conversion(fcontent):
try:
fcontent=int(fcontent)
return fcontent
except Exception:
return False
def main():
result=openfile()
if result == False:
print("There seems to be no file with that name.")
elif conversion(result) == False:
print("The file contents were unsuitable.")
else:
print("The result was", 1000/conversion(result))
if __name__=="__main__":
main() |
# Functions
# Defining a function
def student_scores(English, German, Spanish, French):
print 'My score in English is %d:' % English
print 'My score in German is %d:' % German
print 'My score in Spanish is %d:' % Spanish
print 'My score in French is %d:' % French
# Scores given to function directly
print 'Scores given directly to student_scores function:'
student_scores(70, 83, 92, 73)
# Scores given to function using variables
print 'Scores given using variables:'
score_1 = 70
score_2 = 83
score_3 = 92
score_4 = 73
student_scores(score_1, score_2, score_3, score_4)
# Scores added and given to function
print 'Scores given by adding assignment scores:'
student_scores(65 + 5, 80 + 3, 90 + 2, 70 + 3)
# Scores added to varilable values and given to function
print 'Scores added to values in variables'
student_scores(score_1 + 5, score_2 + 5, score_3 + 5, score_4 + 5)
|
import random
def win():
print("You WIN!")
result = 1
return result
def lose():
print("You LOSE!")
result = 3
return result
def choiceDisplay(user, AI):
print("You chose:", user)
print("Computer chose:", AI)
def play(user):
""" Takes user choice. Select AI's choice randomly. And decide who wins."""
play = random.randint(1, 3)
if play == 1:
AI = "Foot"
elif play == 2:
AI = "Nuke"
elif play == 3:
AI = "Cockroach"
if (AI == user) and (AI != "Nuke"):
choiceDisplay(user, AI)
print("it is a tie!")
result = 2
return result
elif (AI == user) and (AI == "Nuke"):
choiceDisplay(user, AI)
print("Both LOSE!")
result = 3
return result
elif user == "Foot":
choiceDisplay(user, AI)
if play == 2:
return lose()
elif play == 3:
return win()
elif user == "Nuke":
choiceDisplay(user, AI)
if play == 1:
return win()
elif play == 3:
return lose()
elif user == "Cockroach":
choiceDisplay(user, AI)
if play == 1:
return lose()
elif play == 2:
return win()
else:
print("Incorrect selection.")
return 4
def main():
rounds = 0
wonrounds = 0
tierounds = 0
while True:
user = input("Foot, Nuke or Cockroach? (Quit ends):")
if user == "Quit":
print("You played", rounds, "rounds, and won", wonrounds, \
"rounds, playing tie in", tierounds, "rounds.")
break
else:
result = play(user)
if result == 1: # When you win
rounds += 1
wonrounds += 1
elif result == 2: # When it's a tie
rounds += 1
tierounds += 1
elif result == 3: # When you lose
rounds += 1
if __name__ == "__main__":
main() |
lists=[]
def addition(name):
lists.append(name)
return lists
def remove(number):
del lists[number]
return lists
count = 0
while True:
select = int(input("""Would you like to
(1)Add or
(2)Remove items or
(3)Quit?:"""))
if select == 1:
add = input("What will be added?: ")
addition(add)
count = count + 1
count = int(count)
elif select == 2:
print("There are {} items in the list.".format(count))
rem = int(input("Which item is deleted?:"))
if rem < len(lists):
remove(rem)
count = count - 1
else:
print("Incorrect selection.")
elif select == 3:
print("The following items remain in the list:")
for i in lists:
print(i)
break
else:
print("Incorrect selection.") |
text = input("Give a file name:")
readfile = open(text,"w")
print("Write something:")
readtext = readfile.write(input())
readfile.close()
readfile = open(text,"r")
content = readfile.readlines()
for i in content:
print("Wrote", i,"to the file", text)
readfile.close() |
# coding=utf8
__author__ = 'smilezjw'
def longestPalindrome(s):
if len(s) == 1:
return s
p = s[0]
# 遍历中心点,以中心点向两侧取出回文字符串
for i in range(1, len(s)):
# 如果长度是奇数回文字符串,如‘abcba'
m = palindrome(s, i, i)
# 如果长度是偶数回文字符串,如‘abba’
n = palindrome(s, i-1, i)
mlen = len(m)
nlen = len(n)
plen = len(p)
if mlen > len(p) and mlen > nlen:
p = m
if nlen > len(p) and nlen > mlen:
p = n
return p
# 从中间位置开始判断是否是回文字符串
def palindrome(s, begin, end):
while (begin >= 0)and (end < len(s)) and s[begin] == s[end]:
begin -= 1
end += 1
return s[begin + 1: end]
if __name__ == '__main__':
print longestPalindrome('abb')
print longestPalindrome('eabcbaxabcdedcbaf')
print longestPalindrome('ccc')
print longestPalindrome('ccd')
###############################################################################
# 遍历中心点,对每一个中心点都向两侧扩散判断是否为回文字符串,需要考虑两种情况:
# 1.奇数长度回文字符串
# 2.偶数长度回文字符串
# 时间复杂度为O(n^2).
# |
# coding=utf8
__author__ = 'smilezjw'
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 深度优先搜索,耗时46ms
def preorderTraversal(self, root):
Solution.res = []
self.preOder(root)
return Solution.res
def preOder(self, root):
if root:
Solution.res.append(root.val)
self.preOder(root.left)
self.preOder(root.right)
# 用栈操作非递归,耗时43ms
def preorderTraversal_Stack(self, root):
stack = []
res = []
while root or stack:
# 首先遍历根节点的左子树直至叶子结点
if root:
stack.append(root)
res.append(root.val)
root = root.left
# 开始出栈,判断当前结点是否有右子树
else:
root = stack.pop()
root = root.right
return res
if __name__ == '__main__':
s = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
p = root.left
p.left = TreeNode(4)
p.right = TreeNode(5)
print s.preorderTraversal(root)
print s.preorderTraversal_Stack(root)
###########################################################################################
# 先序遍历二叉树用递归实现比较简单。题目要求用非递归方法,考虑用栈来实现。
# 首先遍历根节点并入栈,继续遍历其左子树并入栈;
# 直至当前结点没有左孩子为止开始出栈,每次出栈判断是否有右子树,如果有右子树继续入栈重复上
# 述操作,否则继续出栈。直至节点为None并且栈为空。
# 画个图比较清楚。 |
# coding=utf8
__author__ = 'smilezjw'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
curr = ListNode(0) # 头结点
dummy = curr
while l1 and l2: # 主要循环条件
if l1.val <= l2.val:
curr.next = l1
curr = curr.next
l1 = l1.next
else:
curr.next = l2
curr = curr.next
l2 = l2.next
if l2 is None:
curr.next = l1
else:
curr.next = l2
return dummy.next
if __name__ == '__main__':
s = Solution()
l1 = ListNode(0)
head = l1
for i in [1, 3, 5, 7, 9]:
node = ListNode(i)
head.next = node
head = head.next
l2 = ListNode(0)
head = l2
for i in [2, 4, 6, 8]:
node = ListNode(i)
head.next = node
head = head.next
print s.mergeTwoLists(l1.next, l2.next).val
#####################################################################################################
# 这道题注意循环条件是while l1 and l2, 然后判断两个结点的值的大小,移动指针。第23题是k个有序列表,
# 则不是这么简单操作。
# |
# coding=utf8
__author__ = 'smilezjw'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def removeNthFromEnd(head, n):
if not head or n == 0:
return None
dummy = ListNode(0)
dummy.next = head
p1, p2 = dummy, dummy # 双指针
for i in xrange(n): # p1先移动n个节点
if p1.next:
p1 = p1.next
else:
return None
while p1.next: # 这里利用的还是倒数第n个节点 = 第列表长度减去n个节点
p1 = p1.next # p1到达链表末尾
p2 = p2.next # p2和p1相差n个节点,此时p2指向的节点正是要删除的节点
p2.next = p2.next.next
return dummy.next
if __name__ == '__main__':
llist = ListNode(0)
head = llist
for i in [1, 2, 3, 4, 5]:
node = ListNode(i)
head.next = node
head = head.next
print removeNthFromEnd(llist.next, 2)
#############################################################################################
# 一遍扫描即可找到链表倒数第n个节点删除掉,利用双指针,首先加一个头结点,p1先向前移动n个节点,
# 然后p1和p2同时向前移动, 当p1到达链表最后一个节点时,p1.next == None, 此时p2指向的正是要删除
# 的节点。真是太机智了!!!
# 考虑3种极值情况:
# 1.空链表,头结点为None,则直接返回None;
# 2.链表总数小于n,则返回None;
# 3.n为0,由于链表中最后一个结点是从1开始算,因此n为0也是返回None。
#
|
# coding=utf8
__author__ = 'smilezjw'
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator:
def __init__(self, root): # 初始化栈用于依次入栈下一个最小的元素
self.stack = []
self.pushLeft(root)
# @return a boolean, whether we have a next smallest number
def hasNext(self): # 判断栈是否为空
return len(self.stack) > 0
# @return an integer, the next smallest number
def next(self): # 栈顶的节点的值为下一个最小的数字,注意出栈后要将其右孩子节点入栈
top = self.stack.pop()
self.pushLeft(top.right)
return top.val
def pushLeft(self, node): # 将根结点及其右孩子结点依次入栈
while node:
self.stack.append(node)
node = node.left
###################################################################################
# 这道题要求实现一个二叉搜索树的迭代器,迭代器从二叉搜索树的根结点进行初始化,调用
# next()方法会返回二叉搜索树中下一个最小的数字。题目要求next()和hasnext()方法满足
# O(1)时间复杂度,这里用栈来实现。从根节点开始,每次迭代地将根节点及其左孩子入栈,
# 直至左孩子为空。调用next()弹出栈顶,如果被弹出的节点有右孩子,则将右孩子入栈,并
# 将该右孩子节点的左孩子迭代入栈。
# |
# coding=utf8
class Solution(object):
def detectCapitalUse(self, word):
# if len(word) < 2:
# return True
# return word.upper() == word or word[1:].lower() == word[1:]
return word.isupper() or word.islower() or word.istitle()
if __name__ == '__main__':
solution = Solution()
word = 'Google'
print(solution.detectCapitalUse(word))
|
# coding=utf8
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
sortedNum = sorted(nums)[::-1]
root = TreeNode(sortedNum[0])
idx = nums.index(sortedNum[0])
left = nums[:idx]
right = nums[idx+1:]
if left and len(left) > 0:
root.left = self.constructMaximumBinaryTree(left)
if right and len(right) > 0:
root.right = self.constructMaximumBinaryTree(right)
return root
def printTree(self, root):
if root:
print(str(root.val) + ' - ')
self.printTree(root.left)
self.printTree(root.right)
print('- None -')
if __name__ == '__main__':
solution = Solution()
root = solution.constructMaximumBinaryTree([3,2,1,6,0,5])
solution.printTree(root)
|
# coding=utf8
__author__ = 'smilezjw'
class Solution:
def combine(self, n, k):
Solution.res = []
Solution.count = 0
self.dfs(n, k, 1, [])
return Solution.res
def dfs(self, n, k, start, valueList): # 求组合的问题,这里用DFS来解决
if Solution.count == k: # count记录valueList中元素个数
Solution.res.append(valueList)
return
for i in xrange(start, n+1):
Solution.count += 1
self.dfs(n, k, i+1, valueList + [i])
Solution.count -= 1 # 每次从递归中返回,则valueList中元素个数少1个
return
if __name__ == '__main__':
s = Solution()
print s.combine(4, 2)
################################################################################################
# 每次这种递归的题目都做不好。这道题用深度优先搜索求解。用变量count来记录列表中元素个数,用来
# 判断返回条件。注意每次从递归中返回,count都要减1,因为里面元素个数少1个了。如果当前位置的元素
# 都遍历完了,这时候也要从递归中返回。
# 做递归的题目还是需要判断返回条件和传入的参数。 |
# coding=utf8
__author__ = 'smilezjw'
def isPalindrome(x):
if x < 0:
return False
elif 0 <= x < 10:
return True
else:
flag = True
num = x
length = 0
while x >= 10:
x = x / 10
length += 1
ll = length
while length > 0:
if num / (10 ** length) != num % 10:
flag = False
break
num = (num - (num / 10 ** length) * (10 ** length) - (num % 10))/10
length -= 2
return flag
if __name__ == '__main__':
print isPalindrome(10021)
print isPalindrome(121)
print isPalindrome(-1)
print isPalindrome(-1012147447412)
####################################################################################
# 如果将int转换为字符串,则需要extra space;
# 如果将整数反过来写,则会跟第7题一样出现溢出的问题;
# 因此这道题考虑从整数的第一个数字和最后一个数字比较,依次比较,
# 直到出现不相同的数字或者比较完成。
# |
# coding=utf8
__author__ = 'smilezjw'
class Solution:
# 一开始想到这种方法,不能处理负数啊
def hammingWeight(self, n):
count = 0
while n > 0:
count += n & 1 # n和1做位与操作,计算最低位的1的个数, 还可以n%2也是取得最低位1的个数
n >>= 1 # n向右移一位相当于n /= 2
return count
# 这种方法需要循环n的二进制位数次
def hammingWeight_II(self, n):
count = 0
flag = 1
while flag:
if (flag & n):
count += 1
flag <<= 1
return count
# 把一个整数减去1,再和原来的整数做位与运算,会把该整数最右边一个1变成0。
# 那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。
def hammingWeight_III(self, n):
count = 0
while n:
count += 1
n &= (n-1)
return count
if __name__ == '__main__':
s = Solution()
print s.hammingWeight(0)
print s.hammingWeight(11)
print s.hammingWeight(2**31-1)
######################################################################################
# 这道题比较简单,方法也很多,但思路是一致的,对n取得最低位1的个数,然后n右移相当于
# 除以2。这里对n取最低位1的个数可以和1位与操作,可以模2取余数等。
# |
# coding=utf8
__author__ = 'smilezjw'
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def binaryTreePaths(self, root):
res = []
self.dfs(root, '', res)
return res
def dfs(self, root, path, res):
if root and root.left is None and root.right is None:
res.append(path + str(root.val))
return
elif root:
path += str(root.val) + '->'
self.dfs(root.left, path, res)
self.dfs(root.right, path, res)
if __name__ == '__main__':
s = Solution()
root = TreeNode(1)
curr = root
curr.left = TreeNode(2)
curr.right = TreeNode(3)
curr = curr.left
curr.right = TreeNode(5)
print s.binaryTreePaths(root) |
# coding=utf8
__author__ = 'smilezjw'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def merge(self, head1, head2): # 对两个链表进行归并排序
if head1 is None:
return head2
if head2 is None:
return head1
dummy = ListNode(0)
p = dummy
while head1 and head2:
if head1.val < head2.val:
p.next = head1
p = p.next
head1 = head1.next
else:
p.next = head2
p = p.next
head2 = head2.next
if head1 is None:
p.next = head2
if head2 is None:
p.next = head1
return dummy.next
def sortList(self, head): # 这里将一个链表拆分成两个链表
if head is None or head.next is None:
return head
slow = fast = head
while fast.next and fast.next.next: # 使用快慢指针来截断链表,注意这里的循环停止条件,避免出现死循环
slow = slow.next
fast = fast.next.next
head1 = head
head2 = slow.next
slow.next = None # 注意截断链表时将前半部分的链表最后一个节点next指针指向None
head1 = self.sortList(head1) # 递归对head1链表进行排序
head2 = self.sortList(head2) # 递归对head2链表进行排序
return self.merge(head1, head2)
if __name__ == '__main__':
s = Solution()
head = ListNode(1)
p = head
for i in [3, 2, 5]:
p.next = ListNode(i)
p = p.next
print s.sortList(head)
###################################################################################################
# 这道题参考网上都采用归并排序,归并排序最坏情况下时间复杂度为O(nlogn),空间复杂度为O(n)。
# 这里是对一个链表进行归并排序,因此需要将该链表截断为两部分,并递归分别对两部分链表进行排序,最后
# 才对两部分链表进行归并排序。尤其需要注意:
# 1.截断两个链表时的快慢指针技巧,已经截断后前一部分最后一个节点的next指针指向None;
# 2.需要递归对两部分链表进行排序,不要截断完直接对两部分链表排序就错了。
# |
# coding=utf8
__author__ = 'smilezjw'
class Solution:
def sqrt(self, x): # Implement int sqrt(int x)
i = 0
j = x / 2 + 1 # 二分查找的终点为x / 2 + 1, 因为(x / 2 + 1) ^ 2 > x
while i <= j:
mid = (i + j) / 2
if mid ** 2 == x:
return mid
elif mid ** 2 > x:
j = mid - 1
else:
i = mid + 1
return j # 如果x开方的结果不是整数,那么返回整数部分,注意这里应该返回j
if __name__ == '__main__':
s = Solution()
print s.sqrt(9)
print s.sqrt(2)
######################################################################################################
# 因为这道题要求开方的结果是整数,所以考虑用二分查找的方法来求解。注意二分查找的起点为0,终点为
# x / 2 + 1, 还要主要如果开方的结果不是一个整数,那么返回其整数部分,搞清楚代码里应该返回i还是返回j。
# |
# coding=utf8
class Solution(object):
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
row = len(matrix)
column = len(matrix[0])
for i in range(row-1):
for j in range(column-1):
num = matrix[i][j]
if i+1 < row and j+1 < column and matrix[i][j] != matrix[i+1][j+1]:
return False
return True
if __name__ == '__main__':
sol = Solution()
matrix0 = [[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2]]
print(sol.isToeplitzMatrix(matrix0))
matrix1 = [[1, 2],
[2, 2]]
print(sol.isToeplitzMatrix(matrix1))
|
# coding=utf8
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""
# This solution is common for all kinds of binary tree
# trimRoot = None
# if root is None:
# return root
# elif L <= root.val <= R:
# trimRoot = TreeNode(root.val)
# trimRoot.left = self.trimBST(root.left, L, R)
# trimRoot.right = self.trimBST(root.right, L, R)
# else:
# trimRoot = self.trimBST(root.left, L, R) or self.trimBST(root.right, L, R)
# return trimRoot
# This solution is only for binary search tree
if root is None:
return root
elif root.val > R:
root = self.trimBST(root.left, L, R)
elif root.val < L:
root = self.trimBST(root.right, L, R)
else:
root.left = self.trimBST(root.left, L, R)
root.right = self.trimBST(root.right, L, R)
return root
def DFS(self, root):
if root is None:
return root
print root.val
self.DFS(root.left)
self.DFS(root.right)
if __name__ == '__main__':
root = TreeNode(3)
root.left = TreeNode(1)
p = root.left
p.left = TreeNode(4)
p.right = TreeNode(2)
solution = Solution()
print solution.DFS(root)
print '---'
trimRoot = solution.trimBST(root, 1, 2)
print solution.DFS(trimRoot)
|
# coding=utf8
__author__ = 'smilezjw'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head, m, n):
dummy = ListNode(0)
dummy.next = head
prev = dummy
curr = head
for i in xrange(1, m): # prev指向第m个结点前面的那个结点
prev = curr # curr指向第m个结点
curr = curr.next
p1 = ListNode(0)
p2 = ListNode(0) # 初始化p1和p2,p1和p2可能为空
if curr:
p1 = curr.next # p1指向第m个结点后面的那个结点, p1可能为空
if p1:
p2 = p1.next # p2指向第m个结点后面的第2个结点
for i in xrange(m, n): # 每次反转相邻两个结点的链接,并且顺序移动三个指针
p1.next = curr # 循环结束时curr指向第n个结点
curr = p1
p1 = p2
if p2:
p2 = p2.next
prev.next.next = p1 # 原来第m个结点链接到p1,p1现在指向第n个结点后面一个结点
prev.next = curr # 原来第m个结点的前一个结点链接到第n个结点,同时完成链表的反转
return dummy.next
################################################################################################
# 这道题需要用到三个指针,依次从第m个结点到第n个结点两两反转,最后处理第m个链接到第n个结点后面
# 一个结点,并且第m个结点的前一个结点链接到第n个结点。画画图会更加清晰。
# |
# coding=utf8
__author__ = 'smilezjw'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeElements(self, head, val):
dummy = ListNode(0)
dummy.next = head
p = dummy
while p and p.next:
if p.next.val == val:
p.next = p.next.next
else: # 这里如果p.next.val != val,再移动指针p,避免连续两个节点的值都等于val
p = p.next
return dummy.next
def removeElements_II(self, head, toBeDeleted):
if not head:
return head
if toBeDeleted.next:
nextNode = toBeDeleted.next
toBeDeleted.val = nextNode.val
toBeDeleted.next = nextNode.next
del nextNode
elif head == toBeDeleted:
head = None
else:
p = head
while p.next != toBeDeleted:
p = p.next
p.next = None
return head
if __name__ == '__main__':
s = Solution()
head = ListNode(1)
p = head
for i in [2, 6, 3, 4, 5, 6]:
p.next = ListNode(i)
p = p.next
head2 = ListNode(1)
head2.next = ListNode(1)
print s.removeElements(head, 6)
print s.removeElements(head2, 1)
head = ListNode(1)
p = head
for i in [2, 3, 4, 5, 6]:
p.next = ListNode(i)
p = p.next
toBeDeleted = head.next.next
# print s.removeElements_II(head, p)
print s.removeElements_II(head, toBeDeleted)
head2 = ListNode(1)
print s.removeElements_II(head2, head2)
#####################################################################################
# 题目比较简单,建立头节点,并用指针p来遍历链表,p.next判断节点是否要删除,这样p指向
# 要删除的节点的前一个节点。注意只有当判断p.next不是要删除的节点时,再移动p指针,避免
# 连续节点都要被删除。
# 根据剑指Offer中要求在O(1)时间删除链表结点,假设要删除结点i,先把i的下一个结点j的内
# 容复制到i,然后把i的指针指向结点j的下一个结点,此时再删除结点j,其效果正是把结点i
# 给删除了。如果要删除的结点位于链表的尾部,则只能从链表头结点开始,顺序遍历得到该结点
# 的前序结点完成删除操作。如果链表中只有一个结点,需要在删除之后把链表的头结点置为None。
# 这种方法基于假设要删除的结点在链表中。
# 第一种方法是删除具有val的结点,因此可能多个结点都具有val值,第二种方法则不存在删除多个
# 结点的情况。
# |
#!/usr/bin/env python
# coding=utf-8
def get_Mutil_CnFirstLetter(str):
index = 0;
strReturnCn = ""
print
"len(str)=%s" % len(str)
while index < (len(str) - 1):
# print "strReturnCn=%s" % strReturnCn
# print get_cn_first_letter(str[index:index+2],"GBK")
# print str[index:index+2]
strReturnCn += get_cn_first_letter(str[index:index + 2], "GBK")
index += 2;
return strReturnCn;
def get_cn_first_letter(str, codec="UTF8"):
if codec != "GBK":
if codec != "unicode":
str = str.decode(codec)
str = str.encode("GBK")
if str < "/xb0/xa1" or str > "/xd7/xf9":
return ""
if str < "/xb0/xc4":
return "a"
if str < "/xb2/xc0":
return "b"
if str < "/xb4/xed":
return "c"
if str < "/xb6/xe9":
return "d"
if str < "/xb7/xa1":
return "e"
if str < "/xb8/xc0":
return "f"
if str < "/xb9/xfd":
return "g"
if str < "/xbb/xf6":
return "h"
if str < "/xbf/xa5":
return "j"
if str < "/xc0/xab":
return "k"
if str < "/xc2/xe7":
return "l"
if str < "/xc4/xc2":
return "m"
if str < "/xc5/xb5":
return "n"
if str < "/xc5/xbd":
return "o"
if str < "/xc6/xd9":
return "p"
if str < "/xc8/xba":
return "q"
if str < "/xc8/xf5":
return "r"
if str < "/xcb/xf9":
return "s"
if str < "/xcd/xd9":
return "t"
if str < "/xce/xf3":
return "w"
if str < "/xd1/x88":
return "x"
if str < "/xd4/xd0":
return "y"
if str < "/xd7/xf9":
return "z"
if __name__ == '__main__':
s = "人"
print(s.encode("utf-8"))
# print( get_Mutil_CnFirstLetter("大埔的d") )
# print
# get_cn_first_letter("们", "GBK")
# print
# get_cn_first_letter("他", "GBK")
# print
# get_cn_first_letter("是", "GBK")
# print
# get_cn_first_letter("大", "GBK")
# print
# get_Mutil_CnFirstLetter("大埔的d") |
#!/usr/bin/env python3
import sys
def gcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, x, y = gcd(b%a, a)
return (g, y-(b//a)*x, x)
def inv(b, n):
g, x, _ = gcd(b, n)
if g == 1:
return x%n
else:
return None
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} A P")
else:
a, p = int(sys.argv[1]), int(sys.argv[2])
i = inv(a, p)
if i != None:
print(i)
else:
print(f"Usage: {sys.argv[0]} A P")
|
from math import log
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b, division_type=""):
if division_type == "float":
return a / b
elif division_type == "remainder":
return a % b
else:
return a // b
def logarithm(a, b):
return log(a, b)
def power(a, b):
return a ** b
def root(a, b=2):
return a ** (1 / b)
|
'''
Selection Sort
'''
import random
def SelectionSort(array):
for step in range(len(array)):
min = step
for i in range(min+1,len(array)):
if array[i] < array[min]:
min = i
array[step],array[min] = array[min],array[step]
if __name__ == "__main__":
d = random.sample(range(-50,50),50)
SelectionSort(d)
print("Array sorted using Selection sort:")
print(d) |
min_num = 1
mid = 0
max_num = 100
while True :
#print('Max', max_num, 'Min', min_num)
mid = (min_num + max_num) // 2
print('%d입니까?'%mid)
user = input('높으면 H, 낮으면 L, 맞으면 C를 입력하세요.')
if user == 'H' or user == 'h' :
min_num = mid
max_num = max_num
elif user == 'L' or user == 'l' :
min_num = min_num
max_num = mid
elif user == 'c' or user == 'C' :
print('정답은 :', mid)
break |
def firstVerse(count, bottleTense):
firstVerse = "%s %s of beer on the wall, %s %s of beer." % (count, bottleTense, count, bottleTense)
print(firstVerse)
def secondVerse(count, bottleTense):
secondVerse = "Take one down and pass it around, %s %s of beer on the wall!\n" % (count, bottleTense)
print(secondVerse)
def lyrics():
count = 99
bottleTense = "bottles"
while count > 1:
firstVerse(count, bottleTense)
count -= 1
if count > 1:
secondVerse(count, bottleTense)
elif count == 1:
bottleTense = "bottle"
secondVerse(count, bottleTense)
firstVerse(count, bottleTense)
count = "no more"
bottleTense = "bottles"
secondVerse(count, bottleTense)
count = "No more"
firstVerse(count, bottleTense)
print("Go to the store and buy some more, 99 bottles of beer on the wall!\n")
lyrics()
|
from functools import reduce
l = [8, 10, 1, -8, 4, -9, 10, -5, -10, 5]
l1 = [1, 2, 3]
def x(num):
if num > 0:
return num
def double_num(num):
return num * 2
ml = map(x, l)
m2 = map(double_num, l1)
f1 = filter(x, l)
# print(list(f1))
# print(list(ml))
# map(函数,可迭代对象):返回可迭代对象的每一个元素传入这个函数后的返回值,
# map函数的返回值是一个map对象的迭代器,需要的话可以转成list
# 所以不论这个fun是什么样的函数,这个map函数的结果map对象的元素个数==可迭代对象的元素个数
# 遮掩map适合的场景是:对可迭代对象进行一些统一的处理,【处理】,而不是【过滤】,因为它的结果格式和可迭代对象一样样啊
# 切忌:map(fun,inter_object):其中的fun只写函数名,千万千万不要加()
# 处理的话,就比较适合:统一的比如/2,在比如一些统一的方法:
# s1 = {'d': 3, 'a': 2, 'b': 2}
# s2 = {'a': 4, 'f': 2, 'b': 2}
# s3 = {'e': 4, 'd': 4, 'b': 3}
# ms = map(lambda x:x.pop('b'), [s1, s2, s3])
# print(list(ms))
# filter:重点在过滤
# filter(fun, inter_object):会过滤调所有使得fun返回值为false的inter_object元素,只保留为真的元素
# 它的重点是【过滤】【过滤】【过滤】
# filter函数返回也是一个filter对象的迭代器,可以转成list
# 面试题:返回列表中所有的偶数
# ll = [8, 10, 1, 4, 10, 5]
# l2 = list(filter(lambda x: x % 2 == 0, ll))
# print(l2)
# reduce(fun,inter_object):把inter_object的第一个元素和第二个元素传给fun,fun函数返回一个值,
# 然后把这个值和inter_object的第三个元素再传给fun函数,fun函数再返回一个值
# 然后再把这个值和inter_object的第4个元素传给fun函数,一次类推,直到最后一个元素遍历完
# 特别适合做全量的加、乘这样的运算
ll = [0, 1, 2, 3, 4]
sum = 0
def sum_num(num1, num2):
return num1 + num2
ls = reduce(sum_num, ll)
print(ls)
|
# 解析xml文件
from xml.etree.ElementTree import parse
f = open('../tmp/test.xml', 'r')
et = parse(f)
print(et)
root = et.getroot()
print(root)
print(root.tag)
print(root.attrib)
# python3中使用elementtree.iter()来代替getiterator,使用list()来代替getChildren()
# print(list(et.iter()))
# for child in et.iter():
# print(child.tag)
# for i in et.iterfind('country'):
# print(i.get('name'))
# for i in et.findall('country'):
# print(i.get('name'))
# for j in i.findall('neighbor'):
# print(j.get('name'))
# for i in list(root.iter('neighbor')):
# print(i)
# for i in list(root.iter('country/*')): # 迭代对象里为空,root.iter('标签名'):这里不支持xpath
# print(i)
# a = list(root.findall('country/*')) # root.findall('表达式'):这里支持xpath,xpath:*任意元素
# # print(a)
# b = list(root.findall('.//neighbor')) # xpath:.//任意位置
# print(b)
# c = list(root.findall('.//neighbor[1]')) # xpath:.//任意位置
# print(c)
# d = list(root.findall('.//neighbor[last()]')) # xpath:.//任意位置
# print(d)
# f = list(root.findall('.//country[@name="beijin"]'))
# print(f)
g = list(root.findall('country[rank]')) # 找到含有rank这个标签的所有的country标签
print(g)
h = list(root.findall('country[rank="3"]')) # 找到含有rank,且值为3的这个标签的所有的country标签
print(h)
|
# 如何让字段有序
# tips:使用collection中的OrderedDict
# 存进去的时候顺序是什么样,再OrderedDict中的顺序就是什么样
from collections import OrderedDict
import time
import random
d = OrderedDict()
people = ["Tom","Bob","Jerry","ketty","Tiffy","Hanna","Sun"]
start = time.time()
for i in range(7):
p = people.pop(random.randint(0,6-i))
time.sleep(random.randint(1, 4))
end = time.time()
print(p, i+1, int(end-start))
d[p] = (i+1, int(end-start))
print(d) |
# 根据字典中的值的大小对字典的项进行排序
stu = {'tom': 80, 'jerry': 90, 'kelly': 64, 'kimmy': 45}
# 使用sotred()
# sorted()里面传入的是可迭代对象,而字典的可迭代对象是字典的key
# 方法1:利用zip把字典转成每一对转成元组
# r = zip(stu.values(),stu.keys())
# r = sorted(r, reverse=False)
# print(r)
# 方法2:sorted()的key参数
r = sorted(stu.items(), key=lambda x:x[1],reverse=False)
print(r)
|
#Dylan Grafius 1/16/2018
#CSC131-004
#Purpose: The purpose of this program is to convert binary into its base 10 value.
a = int(input('Enter leftmost digit:'))
num1=a*(2**0)
b = int(input('Enter the next digit:'))
num2=b*(2**1)
c = int(input('Enter the next digit:'))
num3=c*(2**2)
d = int(input('Enter the next digit:'))
num4=d*(2**3)
final = (num1 + num2 + num3 + num4)
print('The value is',final)
|
###########################################
#Dylan Grafius 1/31/2018
#CSC 131-005
#Problem 1: The purpose of this program is to evaluate the length of the 3 sides of a triangle that the user will enter and state whether it is an equilateral or not.
print('Problem 1: Using if statements')
side1 = int(input('Enter your first side:'))
side2 = int(input('Enter your second side:'))
side3 = int(input('Enter your third side:'))
if side1 == side2 and side2 == side3 and side3 == side1:
print('This is an equilateral')
else:
print('This is not an equilateral')
print()
#Problem 2: The purpose of this program is to display a word depending on what letter the user enters.
print('Problem 2: Using nested if statements')
letter = input('Enter "A" for apple, "B for banana, or "C" for coconut:')
if letter == 'A' or letter == 'a':
print('Apple')
if letter == 'B' or letter == 'b':
print('Banana')
if letter == 'C' or letter == 'c':
print('Coconut')
print()
#Problem 3: The purpose of this program is to display a word depending on what letter the user enters.
print('Problem 3: Using elif headers instead')
word = input('Enter "A" for apple, "B for banana, or "C" for coconut:')
if word == 'A' or word == 'a':
print('Apple')
elif word == 'B' or word == 'b':
print('Banana')
elif word == 'C' or word == 'c':
print('Coconut')
|
# Modify the previous program such that only the users Alice and Bob are greeted with their names.
def greeting_alice_and_bob():
user = input("Enter your name: ")
name = ["Alice", "Bob"]
if user == name[0] or name == name[1]:
print(f"Hello {user}!")
greeting_alice_and_bob() |
#User function Template for python3
class Solution:
#Function to return the count of number of elements in union of two arrays.
def doUnion(self,a,n,b,m):
a=list(set(a))
b=list(set(b))
n=len(a)
m=len(b)
ans=len(a)+len(b)
count=0
if(n<=m):
for _ in range(n):
if(a[_] in b):
count+=1
else:
for _ in range(m):
if(b[_] in a):
count+=1
return ans-count
#code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__=='__main__':
t=int(input())
for _ in range(t):
n,m=[int(x) for x in input().strip().split()]
a=[int(x) for x in input().strip().split()]
b=[int(x) for x in input().strip().split()]
ob=Solution()
print(ob.doUnion(a,n,b,m))
# } Driver Code Ends |
#!/bin/python3
import math
import os
import random
import re
import sys
# https://www.hackerrank.com/challenges/grading/problem
#
# Complete the 'gradingStudents' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
#
def gradingStudents(grades):
roundedGrades = []
for g in grades:
if g < 38:
roundedGrades.append(g)
else:
if (g+2)%5 == 0:
roundedGrades.append(g+2)
elif (g+1)%5 == 0:
roundedGrades.append(g+1)
else:
roundedGrades.append(g)
return roundedGrades
if __name__ == '__main__':
grades_count = int(input().strip())
grades = []
for _ in range(grades_count):
grades_item = int(input().strip())
grades.append(grades_item)
result = gradingStudents(grades) |
while True:
entrada = raw_input(“> “)
if entrada == “adios”:
break
else:
print entrada
|
class Calculator:
def __init__(self, name, make, model):
self.name = name
self.make = make
self.model = model
def get_calculator_details(self):
details = (self.name, self.make, self.model)
return details
def addition(self, x, y):
print("inside addition self = : ", self)
sum1 = x + y
return sum1
@staticmethod
def subtraction(x, y):
sub1 = x - y
return sub1
@staticmethod
def multiplication(x, y):
return x * y
def division(self, a, b):
res = a / b
return res
|
class Calculator:
def __init__(self, name, make, model, x,y):
self.name = name
self.make = make
self.model = model
self.x = x
self.y = y
def get_calculator_details(self):
details = (self.name, self.make, self.model)
return details
def get_addition(self):
sum1 = self.x + self.y
return sum1
def get_subtraction(self):
sub1 = self.x - self.y
return sub1
def get_multiplication(self):
malt1 = self.x * self.y
return malt1
def get_division(self):
div1 = self.x / self.y
return div1
|
from math import ceil
import heapq
class Heap:
def __init__(self, arr=None):
self.heap = []
self.heap_size = 0
if arr is not None:
self.heapify(arr)
self.heap = arr
self.heap_size = len(arr)
def heapify(self, arr):
"""
Convert a given array into a min heap
--- Parameters ---
arr: input array of numbers
"""
n = len(arr)
for i in range(int(n / 2), -1, -1):
self.sift_down(i, arr)
def sift_up(self, i):
# Get parent index of the current node
parent = int(ceil(i / 2 - 1))
# Check if the parent value is smaller than the newly inserted value
# if so, then replace the value with the parent value and check with the new parent
while parent >= 0 and self.heap[i] < self.heap[parent]:
self.heap[i], self.heap[parent] = self.heap[parent], self.heap[i]
i = parent
parent = int(ceil(i / 2 - 1))
def sift_down(self, i, arr):
"""
Assuming sub trees are already min heaps, converts tree rooted at current indx into a min heap.
:param indx: Index to check for min heap
"""
# Get index of left and right child of indx node
left_child = i * 2 + 1
right_child = i * 2 + 2
smallest = i
# check what is the smallest value node in indx, left child and right child
if left_child < len(arr):
if arr[left_child] < arr[smallest]:
smallest = left_child
if right_child < len(arr):
if arr[right_child] < arr[smallest]:
smallest = right_child
# if indx node is not the smallest value, swap with the smallest child
# and recursively call min_heapify on the respective child swapped with
if smallest != i:
arr[i], arr[smallest] = arr[smallest], arr[i]
self.sift_down(smallest, arr)
def insert(self, value):
"""
Inserts an element in the min heap
:param value: value to be inserted in the heap
"""
self.heap.append(value)
self.sift_up(self.heap_size)
self.heap_size += 1
def delete(self, indx):
"""
Deletes the value on the specified index node
:param indx: index whose node is to be removed
:return: Value of the node deleted from the heap
"""
if self.heap_size == 0:
print("Heap Underflow!!")
return
self.heap[-1], self.heap[indx] = self.heap[indx], self.heap[-1]
self.heap_size -= 1
self.sift_down(indx, self.heap)
return self.heap.pop()
def delete_min(self):
"""
Extracts the minimum value from the heap
:return: extracted min value
"""
return self.delete(0)
def print(self):
print(*self.heap)
"""A Min heap is a complete binary tree [CBT] (implemented using array)
in which each node has a value smaller than its sub-trees"""
from math import ceil
class MinHeap:
def __init__(self, arr=None):
self.heap = []
self.heap_size = 0
if arr is not None:
self.create_min_heap(arr)
self.heap = arr
self.heap_size = len(arr)
def create_min_heap(self, arr):
"""
Converts a given array into a min heap
:param arr: input array of numbers
"""
n = len(arr)
# last n/2 elements will be leaf nodes (CBT property) hence already min heaps
# loop from n/2 to 0 index and convert each index node into min heap
for i in range(int(n / 2), -1, -1):
self.min_heapify(i, arr, n)
def min_heapify(self, indx, arr, size):
"""
Assuming sub trees are already min heaps, converts tree rooted at current indx into a min heap.
:param indx: Index to check for min heap
"""
# Get index of left and right child of indx node
left_child = indx * 2 + 1
right_child = indx * 2 + 2
smallest = indx
# check what is the smallest value node in indx, left child and right child
if left_child < size:
if arr[left_child] < arr[smallest]:
smallest = left_child
if right_child < size:
if arr[right_child] < arr[smallest]:
smallest = right_child
# if indx node is not the smallest value, swap with the smallest child
# and recursively call min_heapify on the respective child swapped with
if smallest != indx:
arr[indx], arr[smallest] = arr[smallest], arr[indx]
self.min_heapify(smallest, arr, size)
def insert(self, value):
"""
Inserts an element in the min heap
:param value: value to be inserted in the heap
"""
self.heap.append(value)
self.heap_size += 1
indx = self.heap_size - 1
# Get parent index of the current node
parent = int(ceil(indx / 2 - 1))
# Check if the parent value is smaller than the newly inserted value
# if so, then replace the value with the parent value and check with the new parent
while parent >= 0 and self.heap[indx] < self.heap[parent]:
self.heap[indx], self.heap[parent] = self.heap[parent], self.heap[indx]
indx = parent
parent = int(ceil(indx / 2 - 1))
def delete(self, indx):
"""
Deletes the value on the specified index node
:param indx: index whose node is to be removed
:return: Value of the node deleted from the heap
"""
if self.heap_size == 0:
print("Heap Underflow!!")
return
self.heap[-1], self.heap[indx] = self.heap[indx], self.heap[-1]
self.heap_size -= 1
self.min_heapify(indx, self.heap, self.heap_size)
return self.heap.pop()
def extract_min(self):
"""
Extracts the minimum value from the heap
:return: extracted min value
"""
return self.delete(0)
def print(self):
print(*self.heap)
if __name__ == "__main__":
a = {'1': {'2': 6, '3': 10, '4': 11}, '2': {'1': 6, '4': 3, '6': 6, '7': 12}, '3': {'1': 10, '4': 5, '5': 8, '9': 9},
'4': {'1': 11, '2': 3, '3': 5, '5': 7, '6': 2, '9': 12}, '5': {'3': 8, '4': 7, '6': 4, '8': 2, '9': 3},
'6': {'2': 6, '4': 2, '5': 4, '7': 7, '8': 9}, '7': {'2': 12, '6': 7, '8': 4, 'p': 11},
'8': {'5': 2, '6': 9, '7': 4, 'p': 7}, '9': {'3': 9, '4': 12, '5': 3, 'p': 10}, 'p': {'8': 7, '9': 10, '7': 11}}
|
#!/usr/bin/python3
import sys
def mapper_1():
"""
First Job - Mapper
This mapper selects three columns from the input: video_id, category, country
Return key: video_id
value: category + country
"""
header = True
for line in sys.stdin:
# Clean and split input
line = line.strip().split(",")
# Filter header
if header:
header = False
continue
# Check the format of the columns
if len(line) != 12:
continue
# Extract three relevant columns
video_id = line[0].strip()
category = line[3].strip()
country = line[-1].strip()
# Check and filter header
category_country = category + "," + country
print("{}\t{}".format(video_id, category_country))
if __name__ == "__main__":
mapper_1()
|
def sorted(A):
if len(A)==1:
return 0
return A[0]<=A[1] and sorted(A[1:])
A=[127,72,42,25,727]
print(sorted(A))
|
# given an algorithms for finding maximum element in tree .
# class newNode:
# def __init__(self,data):
# self.data = data
# self.left=self.right = None
# def findmax(root):
# if (root == None): base case for resursion..
# return float('-inf')
# res = root.data
# lres = findmax(root.left)
# rres = findmax(root.right)
# if(lres > res):
# res=lres
# if(rres >res):
# res = rres
# return res
# if __name__ == '__main__':
# root = newNode(2)
# root.left = newNode(7)
# root.right = newNode(5)
# root.left.right = newNode(6)
# root.left.right.left = newNode(1)
# root.left.right.right = newNode(11)
# root.right.right = newNode(9)
# root.right.right.left = newNode(4)
# print("The Maximum element is : "),
# findmax(root)
# Python3 program to find maximum
# and minimum in a Binary Tree
# A class to create a new node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Returns maximum value in a
# given Binary Tree
def findMax(root):
# Base case
if (root == None):
return float('-inf')
res = root.data
lres = findMax(root.left)
rres = findMax(root.right)
if (lres > res):
res = lres
if (rres > res):
res = rres
return res
# Driver Code
if __name__ == '__main__':
root = newNode(2)
root.left = newNode(7)
root.right = newNode(5)
root.left.right = newNode(6)
root.left.right.left = newNode(1)
root.left.right.right = newNode(11)
root.right.right = newNode(9)
root.right.right.left = newNode(4)
# Function call
print("Maximum element is",
findMax(root))
|
def Min(arr,n):
res = arr[0]
for i in range(1,n):
res= min(res,arr[i])
return res
def Max(arr,n):
res=arr[0]
for i in range(1,n):
res = max(res,arr[i])
return res
arr =[15, 16, 10, 9, 6, 7, 17]
n=len(arr)
MIN=Min(arr,n)
MAX=Max(arr,n)
print(MIN)
print(MAX)
Range=MAX-MIN
print(Range) |
#More advanced calculator.
num1 = float(input("Enter first number:"))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
#If condition statements to check the operator the user would like to use.
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
else:
print("Invalid operator.")
|
# 线程之间数据安全的容器队列
import queue
# 不是内置的错误类型,而是queue模块中的错误
from queue import Empty
# fifo 先进先出的队列
# q = queue.Queue(4)
# q.get()
# q.put(1)
# q.put(2)
# q.put(3)
# q.put(4)
# print('4 done')
# q.put_nowait(5)
# q.put('5 done')
# try:
# q.get_nowait()
# except queue.Empty:
# pass
#
# print('队列为空')
# last in first out 后进先出 栈
# from queue import LifoQueue
#
# lq = LifoQueue()
# lq.put(1)
# lq.put(2)
# lq.put(3)
# print(lq.get())
# print(lq.get())
# print(lq.get())
# 优先级队列
from queue import PriorityQueue
priq = PriorityQueue()
priq.put((2,'alex'))
priq.put((1,'wusir'))
priq.put((3,'太白'))
print(priq.get())
print(priq.get())
print(priq.get())
|
'''
和python解释器相关的操作
'''
# 获取命令行方式运行的脚本后面的参数
import sys
# 脚本名
# print('脚本名',sys.argv[0])
# # 第一个参数
# print('第一个参数',sys.argv[1])
# # 第二个参数
# print('第二个参数',sys.argv[2])
# 类型字符串
# print(type(sys.argv[1]))
# arg1 = int(sys.argv[1])
# arg2 = int(sys.argv[2])
# print(arg1 +arg2)
# 解释器寻找模块的路径
# sys.path
# 已经加载的模块
# print(sys.modules)
|
'''
自定义模块
'''
# 使用__all__控制被导入的成员
__all__ = ['age','age2']
age = 10
def f1():
print('hell')
age2 = 20
age3 = 30
# 调试函数,在开发阶段,对本模块的功能进行测试
def main():
print(age)
f1()
# 可以快速生成
if __name__ == '__main__':
main()
|
# # 作业:用函数完成登录注册功能以及购物车的功能
# # 1.启动程序,用户可以选择四个选项:登录,注册,购物,退出
# # 2.用户注册,用户名不能重复,注册成功之后,用户名密码记录到文件中,密码的长度不能超过14个字符
# #
# # 3.用户登录,用户名密码从文件中读取,进行三次验证,验证不成功则退出整个程序
# # 4.用户登录成功之后才能选择购物车功能进行购物,购物功能
# # 购物要求:
# # 1.将购物车封装到一个函数中
# # 2.在上周的基础上,可以实现充值的扩展,以及其他相关扩展
# # 3.用户选择退出购物车时,将以购物的商品记录到一个文件中,将未付钱的但加入购物车的商品记录到一个文件中
# # 4每个用户专属两个文件,一个文件(文件名:登录的用户名_buy_goods)存储已购买的商品,另一个文件(文件名:登录的用户名_want_buy)
# # 存储加入购物车的商品但没有购买的文件(升级功能)
# # 5.给购物车增加两个功能:1.可查看已购买的商品,2.可查看上次退出时加入购物车未购买的商品(升级功能)
# # 6.对于第五题的第二个功能可以进行购买商品并追加到已购买的文件中(升级功能)
# # 5.退出则是退出整个程序
#
#
# def register():
# pass
#
# def login():
# pass
#
# def quit_out():
# pass
#
# def shopping_car():
# pass
#
#
# choice_dict = {
# 1:register,
# 2:login,
# 3:shopping_car,
# 4:quit_out
#
# }
#
#
# while 1:
# choice = input('''
# 1.注册
# 2.登录
# 3.购物
# 4.退出
# ''')
#
#
# '''
# if choice == '1':
# register()
# elif choice == '2':
# login()
# '''
#
# choice_dict[int(choice)]()
goods = [
{'name':'电脑','price':1999},
{'name':'鼠标','price':10},
{'name':'游艇','price':20},
{'name':'美女','price':998}
]
shopping_car = {}
while 1:
money = input('请充值:').strip()
if money.isdigit():
money = int(money)
break
else:
print('有非数字元素,重新输入')
# enumerate 可哈希的,比如:列表,字典
flag = True
while flag:
print('所有商品展示如下:')
for index,commodity_dict in enumerate(goods):
print('{}\t{}\t{}'.format(index+1,commodity_dict['name'],commodity_dict['price']))
print('n或N\t 购物车结算\nq或Q\t 退出程序')
select_num = input('请输入您的选择:')
if select_num.isdigit():
select_num = int(select_num)
if 0<select_num<len(goods):
if (select_num-1) not in shopping_car:
shopping_car[select_num-1] = {'name':goods[select_num-1]['name'],'price':goods[select_num-1]['price'],'amount':1}
else:
shopping_car[select_num-1]['amount'] += 1
print('您成功将:商品为{},单价为{},数量为1添加到购物车'.format(shopping_car[select_num-1]['name'],shopping_car[select_num-1]['price']))
else:
print('您输入的超出范围')
elif select_num.upper() == 'N':
# print(shopping_car)
while 1:
total_price = 0
print('您购物车的商品如下:')
for ind,com_dict in shopping_car.items():
print('商品序号:{},商品名称:{},商品单价:{},商品数量:{}'.\
format(ind+1,shopping_car[ind]['name'],shopping_car[ind]['price'],shopping_car[ind]['amount']))
total_price += shopping_car[ind]['price'] * shopping_car[ind]['amount']
print('此次购物车所有的商品的总价:%s元' %(total_price))
if money < total_price:
# 可以扩展充值功能
del_num = input('请选择需要删除的商品序号(默认每次数量减一)').strip()
if del_num.isdigit():
del_num = int(del_num)
if (del_num - 1) in shopping_car:
shopping_car[del_num - 1]['amount'] -= 1
if shopping_car[del_num-1]['amount'] == 0:
shopping_car.pop(del_num-1,'无此key')
else:
print('您输入的超出范围')
else:
print('您输入的有误,请重新输入')
else:
money -= total_price
print('您已经成功购买了上面的所有商品,剩余 %s 元' % (money))
flag = False
break
# 保留购物车未结算的商品,写入文件,以便后续在结算
elif select_num.upper() == 'Q':
break
else:
print('您输入的有误,请重新输入')
|
# 用一行代码构建一个比较复杂有规律的列表
# l1 = []
# for i in range(1,11):
# l1.append(i)
# print(l1)
# 列表推导式
# l1 = [i for i in range(1,11)]
# print(l1)
# 列表推导式分为两类
# 循环模式
# 1.将10以内所有整数的平方写入列表。
# l1 = [i**2 for i in range(1,11)]
# print(l1)
# # 2.100以内所有的偶数写入列表.
# l2 = [i for i in range(2,101,2)]
# print(l2)
# # 3.python1期到python100期写入列表lst
# l3 = [f'python{i}期' for i in range(1,101)]
# print(l3)
# 筛选器
# 筛选模式:[变量(加工后的变量) for 变量 in iterable if 条件]
# 30以内能被3整除的数
# l1 = [i for i in range(1,31) if i % 3 == 0]
# print(l1)
# 过滤掉长度小于3的字符串列表,并将剩下的转化成大写字母
# l1 = ['barry','ab','alex','wusir','xo']
#
# l2 = [i.upper() for i in l1 if len(i) > 3]
# print(l2)
# 找到嵌套列表中名字含有两个‘e’的所有名字
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
l3 = [name for i in names for name in i if name.count('e') == 2]
# for i in names:
# for name in i:
# if name.count('e') == 2:
# l3.append(name)
print(l3)
# 生成器表达式
# 与列表推导式的写法几乎一摸一样,也有筛选模式和循环模式,多层循环构建,与写法只有一个不同
# l1 = [i for i in range(10)]
# print(l1)
# # 变成生成器了
# get = (i for i in range(10))
# print(get)
# for i in get:
# print(i)
# 总结:
# 列表推导式:
# 1.有毒,列表推导式只能构建比较复杂并且有规律的列表
# 2.超过三层循环才能构建成功的,就不建议用列表推导式了
# 3.查找错误(debug模式)不行
# 优点:
# 一行构建,简单
#
# 构建一个列表[2,3,4,5,6,7,8,9,10,k,q,k,a]
l1 = [i for i in range(2,11)] + list('JQKA')
print(l1)
# 列表推导式与生成器表达式的区别
# 方法上:[] ()
# iterable iterator
# 字典推导式
lst1 = ['jar','jj','meet']
lst2 = ['周杰伦','林俊杰','元宝']
dic = {lst2[i]:lst1[i] for i in range(len(lst1))}
print(dic)
# 集合推导式
print({i for i in range(1,10)})
|
'''
web框架
根据不同的url返回不同的内容
1.先拿到用户访问的url是什么
2.返回不同的url
'''
import socket
sk = socket.socket()
sk.bind(('127.0.0.1',8088))
sk.listen()
while 1:
conn,addr = sk.accept()
data = conn.recv(9000)
# 用户发送的请求消息
print(data)
# 从请求的消息中拿到请求的url是什么?
data_str = str(data,encoding='utf8')
# 按照\r\n分割字符串
list = data_str.split('\r\n')
url = list[0].split(' ')[1]
print(url)
if url == '/index/':
msg = 'this is index page'
elif url == '/home/':
msg = 'this is home page'
else:
msg = '404 Not Found'
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
# 发送响应数据
conn.send(bytes(msg,encoding='utf8'))
conn.close()
|
# 函数
# def func():
# print(111)
# print(222)
# return 3
# ret = func()
# print(ret)
# 生成器
# def func():
# print(111)
# print(222)
# yield 3
# yield 4
#
# ret = func()
# # print(ret)
# print(next(ret))
# print(next(ret))
# 一个next对应一个yield
# return 和 yield
# return:函数中只存在一个return结束函数,并且给函数的执行者返回值
# yield:只要函数中有yieldname它就是生成器函数而不是函数了
# 生成器函数中可以存在多个yield,yield不会结束生成器函数,一个yield对应一个next
# 生成器
# def func():
# print(111)
# yield 222
#
# ret = func()
# print(ret)
# print(next(ret))
# 吃包子
# def func():
# l1 = []
# for i in range(1,5001):
# l1.append(f'{i}号包子')
# return l1
# ret = func()
# print(ret)
# 迭代器和生成器可以叫成一个
# def gen_func():
# for i in range(1,5001):
# yield f'{i}号包子'
# ret = gen_func()
# for i in range(200):
# print(next(ret))
#
# for i in range(200):
# print(next(ret))
# yield from
# def func():
# l1 = [1,2,3,4,5]
# # 将l1 变成了迭代器
# yield from l1
# # 将l1这个列表变成了迭代器返回
# ret = func()
# print(next(ret))
# print(next(ret))
# print(next(ret))
def func():
lst1 = ['卫龙', '老冰棍', '北冰洋', '牛羊配']
lst2 = ['馒头', '花卷', '豆包', '大饼']
yield from lst1
yield from lst2
g = func()
for i in range(8):
print(next(g))
|
# 猫
# 吃
# 喝
# 睡
# 爬树
# 狗
# 吃
# 喝
# 睡
# 看家
# class Cat:
# def __init__(self,name):
# self.name = name
#
# def eat(self):
# print('%s is eating'%(self.name))
#
# def drink(self):
# print('%s is drinking'%(self.name))
#
# def sleep(self):
# print('%s is sleeping'%(self.name))
#
# def climb_tree(self):
# print('%s is clamb_tree'%(self.name))
#
#
# class Dog:
# def __init__(self, name):
# self.name = name
#
# def eat(self):
# print('%s is eating' %(self.name))
#
# def drink(self):
# print('%s is drinking' %(self.name))
#
# def sleep(self):
# print('%s is sleeping' %(self.name))
#
# def house_keep(self):
# print('%s house keepimg' %(self.name))
# 小白 = Cat('小白')
# 小白.eat()
# 小白.drink()
# 小白.climb_tree()
#
# 小黑 = Dog('小黑')
# 小黑.eat()
# 小黑.drink()
# 小黑.house_keep()
# 继承 - 需要解决代码的重复
# 继承语法
# class A:
# pass
#
# class B(A):
# pass
# B继承A,A是父类,B是子类
# A是父类 基类 超类
# B是子类 派生类
# 子类可以使用父类中的:方法 静态变量
# class Animal:
# def __init__(self,name):
# self.name = name
#
# def eat(self):
# print('%s is eating'%(self.name))
#
# def drink(self):
# print('%s is drinking'%(self.name))
#
# def sleep(self):
# print('%s is sleeping'%(self.name))
# class Cat(Animal):
# def climb_tree(self):
# print('%s is clamb_tree'%(self.name))
#
#
# class Dog(Animal):
# def house_keep(self):
# print('%s house keepimg' %(self.name))
#
#
# 小白 = Cat('小白')
# # 先开辟空间,空间里面有一个类指针 ---> 指向Cat
# # 调用init,对象在自己的空间中找init没找打,到Cat类中找init也没找到
# # 找父类Animal中的init
# 小白.eat()
#
# xiaohei = Dog('小黑')
# xiaohei.eat()
# 当子类和父类的方法重名的时候,我们只使用子类的方法,而不会去调用父类的方法了
# class Animal:
# def __init__(self,name):
# self.name = name
#
# def eat(self):
# print('%s is eating'%(self.name))
#
# def drink(self):
# print('%s is drinking'%(self.name))
#
# def sleep(self):
# print('%s is sleeping'%(self.name))
#
#
#
# class Cat(Animal):
# def eat(self):
# print('%s 吃猫粮'%(self.name))
#
# def climb_tree(self):
# print('%s is clamb_tree'%(self.name))
#
# 小白 = Cat('小白')
# 小白.eat()
# 子类想要调用父类的方法的同时还想要执行自己的同名方法
# 猫和狗在调用eat的时候既调用自己的方法也调用父类的
# 在子类的方法中调用父类的方法:父类名.方法名(self)
# class Animal:
# def __init__(self,name,food):
# self.name = name
# self.food = food
# self.blood = 100
# self.waise = 100
#
# def eat(self):
# print('%s is eating %s'%(self.name,self.food))
#
# def drink(self):
# print('%s is drinking'%(self.name))
#
# def sleep(self):
# print('%s is sleeping'%(self.name))
#
#
#
# class Cat(Animal):
# def eat(self):
# self.blood += 100
# Animal.eat(self)
#
# def climb_tree(self):
# print('%s is clamb_tree'%(self.name))
# self.drink()
#
# class Dog(Animal):
# def eat(self):
# self.waise += 100
# Animal.eat(self)
#
# def house_keep(self):
# print('%s house keep'%(self.name))
#
# 小白 = Cat('小白','猫粮')
# 小黑 = Dog('小黑','狗粮')
# 小白.eat()
# 小黑.eat()
# print(小白.__dict__)
# print(小黑.__dict__)
# 父类和子类方法的选择:
# 子类的对象,如果去调用方法
# 永远优先调用自己的
# 如果自己有 用自己的
# 自己没有 用父类的
# 如果自己有 还想用父类的:直接在子类方法中调用父类的方法 父类名.方法名(self)
# class Foo:
# def __init__(self):
# # 在每一个self调用func的时候,我们不看这句话是在哪里执行,只看self是谁
# self.func()
#
# def func(self):
# print('in fo')
#
# class Son(Foo):
# def func(self):
# print('in son')
#
# Son()
# 思考二:如果想给猫和狗定制个性的属性
# class Animal:
# def __init__(self,name,food):
# self.name = name
# self.food = food
# self.blood = 100
# self.waise = 100
#
# def eat(self):
# print('%s is eating %s'%(self.name,self.food))
#
# def drink(self):
# print('%s is drinking'%(self.name))
#
# def sleep(self):
# print('%s is sleeping'%(self.name))
#
# class Cat(Animal):
# def __init__(self,name,food,eye_color):
# # 调用父类的初始化,去完成一些通用属性的初始化
# Animal.__init__(self,name,food)
# # 派生属性
# self.eye_color = eye_color
#
#
# class Dog(Animal):
# def __init__(self,name,food,size):
# # 调用父类的初始化,去完成一些通用属性的初始化
# Animal.__init__(self,name,food)
# # 派生属性
# self.size = size
# # 猫:eye_color眼睛的颜色
# # 狗:size型号
#
# 小白 = Cat('小白','猫粮','蓝色')
# print(小白.__dict__)
#
# xiaohei = Dog('小黑','狗粮','1000')
# print(xiaohei.__dict__)
# 单继承
# class D:
# def func(self):
# print('in D')
# class C(D):pass
# class A(C):
# def func(self):
# print('in A')
# class B(A):pass
#
# b = B()
# b.func()
# 多继承 有好几个爹
# 有一些语言不支持多继承 java
# python语言的特点:可以在面向对象中支持多继承
class A:
def func(self):
print('in A')
class B:
def func(self):
print('in B')
class C(A,B):pass
C().func()
# 调子类的:子类自己有的时候
# 调父类的:子类自己没有的时候
# 调子类和父类的:子类和父类都有的,在子类中调用父类的
# 多继承
# 一个类有多个父类,在调用父类方法的时候,按照继承的顺序,先继承的就先寻找
|
# 基础数据类型的复习
# 整型,布尔值,字符串,字典,元组,集合
# 1.字符串 不可变数据类型
# 方法
# 首字母大写,全部大写,全部小写
# start以什么开头,end以什么结尾
# find,index 按照元素查找索引
# 公共方法:count,len
# replace替换 center 居中
# 索引和切片
# 2.列表 list 可变的数据类型
# 索引和切片
# lit = [1,2,3]
# 索引lit[0],切片lit[::2]
# 方法
# 增
# append()
# insert() 需要两个参数 在哪个位置插入什么值
# extend() 可迭代对象
# 删
# remove()
# pop() 有返回值
# del
# 改
# lit[1] = 'alex'
# 查
# for 循环
# 3.元组
# 只能查看,不能增删改
# 4.字典 {}
# dic = {
# "name":"太白",
# "age":18,
# "hobby_list":['直男',"开车"]
# }
# 字典的方法
# 增 有则改之无则加勉
# dic['sex'] = '男'
# print(dic)
# dic.setdefault('sex','男')
# print(dic)
# update(sex='男')
# 删
# pop()
# clear()
# del
# 改
# dic['name'] = 'alex'
# update()
# 查
# let = dic.get('name')
# print(let)
# 三个特殊的方法
# keys()
# values()
# items()
# 5.集合 set {}
# 增
# add()
# update() 里面的参数是字典,有则改之无则增加
# 删
# remove() 按照元素删除
# pop() 随机删除
# is id == 的区别 |
# 场景,角色,类 - 属性和方法
# 站在每个角色的角度上去思考程序执行的流程
import sys
class Course:
def __init__(self,name,price,period,teacher):
self.name = name
self.price = price
self.period = period
self.teacher = teacher
class Student:
openate_lst = [('查看可选课程', 'show_course'),
('选择课程', 'select_course'),
('查看已选课程', 'check_selected_course'),
('退出', 'exit')]
def __init__(self,name):
self.name = name
self.courses = []
def show_course(self):
print('查看可选课程')
def select_course(self):
print('选择课程')
def check_selected_course(self):
print('查看已选课程')
def exit(self):
exit()
class Manager:
openate_lst = [('创建课程','create_course'),
('创建学生','create_student'),
('查看所有课程','show_course'),
('查看所有学生','show_student'),
('查看所有学生的选课情况','show_student_course'),
('退出','exit')]
def __init__(self,name):
self.name = name
def create_course(self):
print('创建课程')
def create_student(self):
print('创建学生')
def show_course(self):
print('查看所有的课程')
def show_student(self):
print('查看所有学生')
def show_student_course(self):
print('查看所有学生的选课情况')
def exit(self):
exit()
# 学生:登录就可以选课了
# 有学生
# 有课程了
# 管理员:
# 学生的账号是管理员创建的
# 课程也应该是管理员创建的
# 应该先站在管理员的角度来开发
# 登录
# 登录必须能够自动识别生份
# 用户名/密码/自动识别生份
def login():
name = input('username:')
pawd = input('password:')
with open('userinfo',encoding='utf-8') as f:
for line in f:
usr,pwd,identify = line.strip().split('|')
if usr == name and pwd == pawd:
return {'result':True,'name':name,'id':identify}
else:
return {'result':False,'name':name}
ret = login()
if ret['result']:
print('登录成功')
if hasattr(sys.modules[__name__],ret['id']):
cls = getattr(sys.modules[__name__],ret['id'])
obj = Manager(ret['name'])
for id,item in enumerate(Manager.openate_lst,1):
print(id,item[0])
func_str = Manager.openate_lst[int(input('>>>')) - 1]
if hasattr(obj,func_str):
getattr(obj,func_str)()
# if ret['id'] == 'Manager':
# obj = Manager(ret['name'])
# for id,item in enumerate(Manager.openate_lst,1):
# print(id,item[0])
# func_str = Manager.openate_lst[int(input('>>>')) - 1]
# if hasattr(obj,func_str):
# getattr(obj,func_str)()
# elif ret['id'] == 'Student':
# obj = Manager(ret['name'])
# for id, item in enumerate(Manager.openate_lst, 1):
# print(id, item[0])
# func_str = Manager.openate_lst[int(input('>>>')) - 1]
# if hasattr(obj, func_str):
# getattr(obj, func_str)()
|
# count = 1;
# while count < 11:
# if count == 7:
# count +=1;
# continue
# else:
# print(count);
# count +=1;
#
# count = 1;
# while count < 11:
# if count == 7:
# count +=1
# print(count);
# count +=1;
# 输出1-100内的所有偶数
count = 1
while count < 101:
if count % 2 == 0:
print(count)
count += 1;
|
# eval() 剥去字符串的外衣,运算里面的代码,有返回值
# s1 = '1+3'
# print(s1)
# print(eval(s1))
# 网络传输的str,input 输入的时候,sql注入等等绝对不能使用eval
# exec 与eval几乎一样,代码流
# msg = '''
# for i in range(10):
# print(i)
# '''
# # print(msg)
# exec(msg)
# hash 哈希值
# print(hash('jdkjkd'))
# help 帮助
# s1 = 'dafdsa'
# print(help(str.upper))
# callable 判断一个对象是否可被调用
# def func():
# pass
# # func()
# print(callable(func))
# # bin:将十进制转换成二进制并返回。
# print(bin(10))
# # oct:将十进制转化成八进制字符串并返回。
# print(oct(10))
# # hex:将十进制转化成十六进制字符串并返回
# print(hex(13))
# divmod() **
# print(divmod(10,3))
# round() 保留浮点数的小数位数
# print(round(3.1415926,2))
# pow() 一个参数的幂 **
# print(pow(2,3,3))
# bytes() ***
# s1 = '太白'
# b = bytes(s1,encoding='utf-8')
# print(b)
# ord 输入字符找该字符编码的位置
# print(ord('a'))
# chr() 输入位置数字找出其对应的字符
# print(chr(97))
# repr() 返回一个对象的string形式(原形毕露) ***
# s1 = '台标'
# print(repr(s1))
# msg = '我叫%r' %s1
# print(msg)
# all() 可迭代对象中,全部是true才是true
# l1= [1,2,'太白','']
# print(all(l1))
# any() 可迭代对象中,有一个true才是true
# l1= [1,2,'太白','']
# print(any(l1))
# print()
# print(1,2,3)
# sep 分隔符
# print(1,2,3,sep='&')
# print(1,end=' ')
# print(2)
# list
# l1 = [1,2,3]
# l2 = list('dsafdafd')
# print(l2)
# dict 创建字典的几种方式
# 直接创建
# 元祖的解构
# dic = dict([(1,'onr')])
# dic = dict(one=1)
# print(dic)
# fromkeys
# update
# 字典推导式
# abs() 绝对值 ***
# print(abs(-8))
# sum() 求和
# l1 = [i for i in range(0,10)]
# print(sum(l1))
# print(sum(l1,100))
# reversed() 返回的是一个翻转的迭代器
# l1 = [i for i in range(0,10)]
# l1.reverse() 列表的方法
# print(l1)
# l1 = [i for i in range(0,10)]
# obj = reversed(l1)
# print(obj)
# print(l1)
# print(list(obj))
# zip 拉链方法
# l1 = [1,2,3,4,5]
# tul = ('太白','b哥','德刚')
# s1 = 'abcd'
# obj = zip(l1,tul,s1)
# print(obj)
# for i in obj:
# print(i)
# print(list(obj))
# *********************************************** 一下方法最最最重要
l1 = [33,2,1,54,7,-1,-9]
# print(min(l1))
# 以绝对值的方式取最小的
# l2 = []
# func = lambda a: abs(a)
# for i in l1:
# l2.append(func(i))
# print(min(l2))
# def abss(a):
# '''
# 第一次:a = 33 以绝对值取最小值33
# 第一次:a = 2 以绝对值取最小值2
# '''
# return abs(a)
# print(min(l1,key=abss))
# 凡是可以加key的,他会自动的将可迭代对象中的每一个元素按照顺序传入key对应的函数中
# 已返回值比较大小
# dic = {'a':3,'b':3,'c':1}
# 求出值最小的键值对
# min默认会按照字典的键去比较大小
# def func(a):
# return dic[a]
# print(min(dic,key=func))
# l2 = [('太白',108),('alex',73),('wusir',35),('昊天',41)]
# def func1(a):
# return a[1]
# print(min(l2,key=func1))
# print(min(l2,key=func1)[0])
# print(min(l2,key=func1)[1])
# sorted 加key
# l1 = [22,33,1,2,8,7,6,5]
# l2 = sorted(l1)
# print(l1)
# print(l2)
# l2 = [('太白',108),('alex',73),('wusir',35),('昊天',41)]
# def func1(a):
# return a[1]
# # 返回一个列表
# print(sorted(l2,key=func1))
# print(sorted(l2,key=func1,reverse=True))
# filter 列表推导式的筛选模式
# l1 = [2,3,4,1,6,7,8]
# ret = filter(lambda x: x>3,l1)
# print(ret)
# 迭代器取值,next,for ,list
# print(list(ret))
# map() 列表推导式的循环模式
# l1 = [1,4,9,16,25]
# ret 是一个迭代器
# ret = map(lambda x:x**2,l1)
# print(ret)
# print(list(ret))
# reduce()
from functools import reduce
def func(x,y):
'''
第一次:x y:1,2 x+y=3 记录3
第二次:x = 3,y=3 x+y=6 记录6
第三次:x = 6,y=4,x+y=10
'''
return x*10 + y*10
l1 = reduce(func,[1,2,3,4])
print(l1)
|
#通过代码,将其构建成这种数据类型:
# [{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。
l1 = []
l2 = ['name','price','amount']
with open('a.txt',encoding='utf-8') as f1:
for old in f1:
line_list = old.strip().split()
dic = {}
for i in range(len(l2)):
dic[l2[i]] = line_list[i]
l1.append(dic)
print(l1)
|
# 文件操作
class File:
lst = [('读文件','read'), ('写文件','write'), ('删除文件','remove'), ('文件的重命名','rename'), ('复制','cpoy')]
def __init__(self,filepath):
self.filepath = filepath
def write(self):
print('in write func')
def read(self):
print('in read func')
def remove(self):
print('in remove func')
def rename(self):
print('in rename func')
def copy(self):
print('in copy func')
f = File('dsafdsa')
while 1:
for index,opt in enumerate(File.lst,1):
print(index,opt[0])
num = int(input('请输入你要做的操作序号>>>'))
# print(File.lst[num-1][1])
if hasattr(f,File.lst[num-1][1]):
getattr(f,File.lst[num-1][1])()
# if num == '1':
# f.read()
# elif num == '2':
# f.write()
# elif num == '3':
# f.remove()
# elif num == '4':
# f.rename()
# elif num == '5':
# f.copy()
# 显示所有可以做的操作
# 1.读文件
# 2.写文件
# 3.删除文件
# 4.文件的重名民
|
'''
Created on Oct 27, 2015
@author: Avery
'''
import Triple
class RoutingTable(object):
'''
Table to hold the distance vectors. Each Router will have a RoutingTable
'''
#dictionary holding list of vectors
vector_list = []
name = ""
def __init__(self, name):
self.vector_list = []
self.name = name
def addRoute(self, dest, length, firstHop):
#Adds the route to the routing table
v = Triple.Triple(dest, length, firstHop)
self.vector_list.append(v)
def delRoute(self, dest):
#Delets a route from the routing table
try:
v = self.getVector(dest)
self.vector_list.remove(v)
except:
raise ValueError("Not in List")
def editRoute(self, dest, length, firstHop):
#Edits a route in the routing table
v = self.getVector(dest)
v.dist = length
v.first_hop = firstHop
def contains(self, dest):
#checks to see whether the table contains a route
for vector in self.vector_list:
#If the vector's name is the correct name, return true. It is contained in the list
if vector.dest == dest:
return True
return False
def getVector(self, dest):
#returns a specified vector from the list
for vector in self.vector_list:
#If the vector's name is the correct name, return the vector
if vector.dest == dest:
return vector
return None
def printTable(self):
#prints the table
for vector in self.vector_list:
#print the data of the vector
print(vector.dest +" "+ str(vector.dist)+" "+ vector.first_hop)
def printTableToX(self, x):
#prints the table links that go to router named X
for vector in self.vector_list:
#print the data of the vector if its dest is X
if vector.dest == x:
print(vector.dest +" "+ str(vector.dist)+" "+ vector.first_hop) |
# These are the emails you will be censoring. The open() function is opening the text file that the emails are contained in and the .read() method is allowing us to save their contexts to the following variables:
email_one = open("email_one.txt", "r").read()
email_two = open("email_two.txt", "r").read()
email_three = open("email_three.txt", "r").read()
email_four = open("email_four.txt", "r").read()
### Variables ###
proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]
negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressed", "distressed", "concerning", "horrible", "horribly", "questionable"]
### Functions ###
# Takes two variables, list of terms to sensor and a text file that you want to edit
def censor_email(email, prop_terms):
for term in prop_terms:
email = email.replace(term + ' ', '#' * len(term) + ' ')
email = email.replace(term.title() + ' ', '#' * len(term) + ' ')
email = email.replace(term.upper() + ' ', '#' * len(term) + ' ')
return email
# Removes subsequent mentions of "negative words" from a text strig after one mention of a word.
def negative_remove(email, neg_terms):
for term in neg_terms:
# Use word_index to find the 3rd mention of term in a string. start index at -1
word_index = -1
for i in range(2):
word_index = email.lower().find(term[word_index + 1 :])
if word_index > 0:
email = email.replace(term + ' ', '#' * len(term) + ' ')
email = email.replace(term.title() + ' ', '#' * len(term) + ' ')
email = email.replace(term.upper() + ' ', '#' * len(term) + ' ')
return email
def censor_neg_remove_email(email):
email = negative_remove(email, negative_words)
email = censor_email(email, proprietary_terms)
return email
# Censors the immediate word before and after a word that is already censored
def super_censor(email):
email = censor_neg_remove_email(email)
spl_email = email.split()
siter = iter(range(len(spl_email)))
for i in siter:
if spl_email[i] == '#' * len(spl_email[i]):
if i > 0:
spl_email[i - 1] = '#' * len(spl_email[i - 1])
if i < len(spl_email) - 1:
spl_email[i + 1] = '#' * len(spl_email[i + 1])
next(siter, None)
return ' '.join(spl_email)
### Main ###
#print(email_two)
email_four = super_censor(email_four)
print(email_four)
|
num = int(input("Enter a number: "))
dict1 = {}
for x in range(1, num + 1):
dict1[x] = x * x
print(dict1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.