text stringlengths 37 1.41M |
|---|
# Create three separate lists, each of which contains the names
# of several cities in a different country. Create another list
# which contains these three lists. Print the whole list of
# nested lists.
# Print the second member of the list of lists.
# Use a while loop to print the names in the second member list.
cities1 = ["London", "Manchester", "Birmingham"]
cities2 = ["Krakow", "Warszawa", "Szczecin"]
cities3 = ["Glasgow", "Edinburgh", "Dundee"]
citiesall = [cities1, cities2, cities3]
print(citiesall[1])
i = 0
while (i < len(citiesall)):
print(citiesall[i])
i += 1 |
# Write a program to calculate compound interest. The program
# should ask the user for the initial sum invested, the term
# (no of years) over which the interest should be paid and the
# rate of interest. It should then calculate the compound
# interest and print out the initial sum, interest and final
# value of the savings. (Clue: the final value can be
# calculated using the following formula
# compound_interest = initial_sum(1+interest_rate/100)^term
import math
print("This program will calculate the compound interest.")
initial_sum = float(input("What is the invested sum? £"))
years = int(input("How many years it was invested for? "))
interest = float(input("What is the interest rate? "))
final_sum = initial_sum * (math.pow(1+interest/100, years))
print("The £%.2f deposited on %.2f%% interest rate will result in £%.2f after %d years." % (initial_sum, interest, final_sum, years)) |
# Write a program which reads in a string and counts the number of occurrences
# of each letter in the string. The results should be stored in a dictionary
# and displayed. For example:
# Enter text to count: mississippi
# {'i': 4, 'p': 2, 's': 4, 'm': 1}
print("This program counts the different characters in given strings.")
a = input("Please enter some text: ")
counting = {}
for i in a:
if i in counting:
counting[i] += 1
else:
counting[i] = 1
print(counting) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
def validate_patter(date_text, patter):
"""
Validate string with specific patters
:param date_text: String date to validae, Ie. '22/06/1994'
:param patter: String patter to match, Ie. '%d/%m/%Y'
:return: Bool valid if match with patter. Ie. True
"""
try:
datetime.datetime.strptime(date_text, patter)
return True
except ValueError:
return False
def get_birthday():
"""
Inteface to get information by console imputs
:return: Int year of birth, Ie. 1994
"""
flag = False
while not flag:
chair = "Digite su fecha de birthday en el formato: 'dd/mm/aaaa': "
date_user = input(chair)
flag = validate_patter(date_user, '%d/%m/%Y')
return date_user
def get_age(birthday):
"""
Calculate date
:param birthday: String, date of birth dd/mm/yyyy, Ie. '22/06/1994'
:return: 27 years
"""
date_now = datetime.datetime.now()
date_now_str = datetime.datetime.strftime(date_now, '%d/%m/%Y')
year = str(date_now_str[-4:])
age = int(year) - int(birthday[-4:])
return '{age} years'.format(age=age)
if __name__ == '__main__':
birthday = get_birthday()
print('birthday', birthday)
age = get_age(birthday)
print('you age is: {age}'.format(age=age)) |
numeros = [1,3,6,8,1,9,45,90]
# imprime la posicion 2
print(numeros[2])
# agregar elementos a una lista
numeros.append(10)
print(numeros)
# borrar elementos de una lista
numeros.pop(1)
print(numeros)
# recorrer cada elemento
for i in numeros:
print(i)
# slice de la posicion 1 al 3
print(numeros[1:3])
# sentido inverso
print(numeros[::-1])
# cantidad de veces que aparece en la lista
print(numeros.count(1))
# limpiar una lista
numeros.clear()
print(numeros)
|
""""Tuplas y Desempaquetado"""
"""
A partir de ls siguiente lista instanciar una tupla que contenga todos sus valores
y en el mismo orden.
"""
lista = ["casa", "perro", "pato", "gato"]
# COMPLETAR - INICIO
# COMPLETAR - FIN
assert tupla == ("casa", "perro", "pato", "gato")
"""
A partir de ls siguiente tupla instanciar una lista que contenga todos sus valores
y en el mismo orden.
"""
tupla = "casa", "perro", "pato", "gato", "tenedor"
# COMPLETAR - INICIO
# COMPLETAR - FIN
assert lista == ["casa", "perro", "pato", "gato", "tenedor"]
"""
Desempaquetar la siguiente tupla en las variables a, b y c
"""
tupla = ("primer", 25, [1, 2, 3])
# COMPLETAR - INICIO
# COMPLETAR - FIN
assert a == "primer" and b == 25 and c == [1, 2, 3]
"""
Desempaquetar la siguiente tupla y luego sumar sus valores
"""
tupla = (87, 98, 35, 67, 4, 9)
# COMPLETAR - INICIO
# COMPLETAR - FIN
assert total == 300
"""
Desempaquetar la siguiente lista y luego concatenar sus elementos
Restricción: Utilizar f-Strings.
"""
lista = ["esta", "mañana", "sali", "a", "correr"]
# COMPLETAR - INICIO
# COMPLETAR - FIN
assert string_concatenado == "esta mañana sali a correr"
"""
Desempaquetar el primer elemento de la siguiente tupla
Restricción: Utilizar desempaquetado con comodines
"""
tupla = (73, 45, 344, 3434, 2)
# COMPLETAR - INICIO
# COMPLETAR - FIN
assert primer == 73
"""
Desempaquetar el primer y el último elemento de la siguiente lista y luego sumarlos
Restricción: Utilizar desempaquetado con comodines
"""
lista = [73, 45, 344, 3434, 2]
# COMPLETAR - INICIO
# COMPLETAR - FIN
assert suma == 75
"""
Desempaquetar el primer, el segundo, el tercer, el cuarto y el quinto elemento de la
siguiente tupla y luego concatenarlos
Restricción: Utilizar desempaquetado con comodines y f-Strings
"""
tupla = ("anoche", "fui", "a", "la", "fiesta", "pero", "no", "pude", "entrar")
# COMPLETAR - INICIO
# COMPLETAR - FIN
assert string_concatenado == "anoche fui a la fiesta" |
"""
Create initials of entered names
"""
names = input("Въведете имената си: ")
namesList = names.split()
namesListLength = len(namesList)
initials = list() # []
if namesListLength > 0:
for a in range(namesListLength):
name = namesList[a]
initials.append(name[0])
print(".".join(initials) + ".")
else:
print("No names entered")
|
"""
ако съществителното завършва на y , то се премахва и се добавя ies ;
ако съществителното завършва на o , ch , s , sh , x или z , се добавя es ;
в останалите случаи към съществителното се добавя s
"""
end_parts_add = {'o': 'es', 'ch': 'es', 's': 'es', 'sh': 'es', 'x': 'es', 'z': 'es'}
end_parts_cut = {'y': 'ies'}
DEFAULT_NOUN_END = 's'
noun = input()
noun = noun.strip()
try:
if noun and noun.isalpha():
changed_noun = ""
flag = True
noun_is_upper = noun.isupper()
for part in end_parts_cut:
noun_end = end_parts_cut[part]
if noun_is_upper:
part = part.upper()
noun_end = noun_end.upper()
if noun.endswith(part):
changed_noun = noun[:-1] + noun_end
flag = False
break
if flag:
for part in end_parts_add:
noun_end = end_parts_add[part]
if noun_is_upper:
part = part.upper()
noun_end = noun_end.upper()
if noun.endswith(part):
changed_noun = noun + noun_end
flag = False
break
if flag:
end = DEFAULT_NOUN_END
if noun_is_upper:
end = end.upper()
changed_noun = noun + end
else:
raise Exception('Wrong input')
print(changed_noun)
except Exception:
print('INVALID INPUT') |
sentence3 = "За да дефинирате многоредов стринг"
print(sentence3)
print(sentence3.replace('а', 'AA'))
print(sentence3)
print(sentence3[3])
print(sentence3[3:15])
print(sentence3[3:])
print(sentence3[:])
print('---')
print(sentence3[9:156])
# new way of formatting strings
name = 'boris'
print("I am {name} and I'm happy {when}".format(name=name, when='now'))
price = 37.345523
print("Price: {:.2f}".format(price))
# old way for string formatting
print("I am %s and I'm happy " % name)
print(len("За - ! :)"))
print(sentence3[1])
print(len(sentence3))
parts = "I am %s and I'm happy".split()
print("-".join(parts))
print("12345678901234567890"[:10])
t = "12345678901234567890"
d = "67"
print(t[t.index(d) + len(d):]) |
numbers1 = {1, 2, 3, 4, 5} # set {}
numbers2 = set((3, 4, 5, 6, 7, 8))
text = "sdkgfkjsfkjghjghgfkjsgflsgfieuhfkjsfkbsdkhgfleykfbewkhafk"
text_set = set(text)
print(len(text))
print(len(text_set))
print(text_set)
print(numbers1.intersection(numbers2)) # numbers1 & numbers2
print(numbers1.union(numbers2)) # numbers1 | numbers2
print(numbers1.symmetric_difference(numbers2)) # numbers1 * numbers2
print(numbers1.difference(numbers2)) # numbers1 - numbers2
numbers1 = {1, 2, 3, 'chetiri', 5}
numbers2 = set((3, 4, 5, 6, 7))
print('-' * 20)
print(numbers1)
print(numbers2)
print(2 in numbers1)
if 2 in numbers2:
print('ima go')
else:
print('niama go')
numbers1.add(77)
print(numbers1)
numbers1.add(2)
print(numbers1)
text = "Множеството (set) е съвкупност от уникални елементи. При него няма дефинирана подредба, а основната операция е принадлежност на елемент към множеството."
unique_chars = set()
for char in text:
unique_chars.add(char)
print(unique_chars)
print(len(unique_chars))
unique_chars = set(text)
print(unique_chars)
print(len(unique_chars))
# --------------------------------------
numbers1 = {1, 2, 3, 4, 5}
numbers2 = set((3, 4, 5, 6, 7))
print(numbers1 & numbers2)
print(numbers1.intersection(numbers2))
print(numbers1 | numbers2)
print(numbers1.union(numbers2))
print(numbers1 - numbers2)
print(numbers1.difference(numbers2))
print(numbers1.symmetric_difference(numbers2)) |
# name = input('What is your name? ')
# print('Hi ' + name)
# name = input('What is your name? ')
# favourite_colour = input('What is your favourite colour? ')
# print(name + ' likes ' + favourite_colour)
# birth_year = input('Birth year: ')
# age = 2021 - int(birth_year)
# print(age)
# weight_lbs = input('Weight (lbs): ')
# weight_kg = int(weight_lbs) * 0.45
# print(weight_kg)
# course = 'Pithon Course for "Beginners"'
# print(course[-2])
course ='Pithon is for Beginners'
print(course[-9])
course = 'Pithon is for Beginners'
print(course[:])
name = 'Jennifer'
print(name[1:-1])
|
#!/usr/bin/python
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
# number of features
INPUT_SIZE = 19
# opens the csv file with the stock data.
# creates train-test split of the stock data.
def getData():
file = 'INTC.csv'
data = pd.read_csv(file)
X = data.Close[:9500]
X = X.values.reshape((475, INPUT_SIZE+1))
y = X[:, -1]
X = X[:, :INPUT_SIZE]
return train_test_split(X, y, test_size=0.2, random_state=42)
if __name__ == '__main__':
# gets the data after the split
# the X data contains stock prices of 19 consecutive days
# the y data is the stock price of the 20th day
X_train, X_test, y_train, y_test = getData()
print 'Train Size: ' + str(X_train.shape)
print 'Test Size: ' + str(X_test.shape)
learning_rate = tf.constant(0.0001)
# layers: 19 -> 16 -> 4 -> 1
input_size = INPUT_SIZE
hidden1_size = 16
hidden2_size = 4
output_size = 1
# placeholder for input and output
X = tf.placeholder(tf.float32, shape=[None, input_size])
y = tf.placeholder(tf.float32, shape=[None])
# the weights and biases of the layers
weights = {
'h1': tf.Variable(tf.truncated_normal([input_size, hidden1_size], stddev=0.1)),
'h2': tf.Variable(tf.truncated_normal([hidden1_size, hidden2_size], stddev=0.1)),
'hout': tf.Variable(tf.truncated_normal([hidden2_size, output_size], stddev=0.1))
}
biases = {
'b1': tf.Variable(tf.constant(0.1, shape=[hidden1_size])),
'b2': tf.Variable(tf.constant(0.1, shape=[hidden2_size])),
'bout': tf.Variable(0.)
}
# the creation of the layers using relu activation
hidden_layer1 = tf.nn.relu(tf.add(tf.matmul(X, weights['h1']), biases['b1']))
hidden_layer2 = tf.nn.relu(tf.add(tf.matmul(hidden_layer1, weights['h2']), biases['b2']))
out_layer = tf.add(tf.matmul(hidden_layer2, weights['hout']), biases['bout'])
out_layer = tf.transpose(out_layer)
loss = tf.reduce_mean(tf.squared_difference(out_layer, y))
update = tf.train.AdamOptimizer(learning_rate).minimize(loss)
# start learning
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(11000):
_, loss_ = sess.run([update, loss], feed_dict={X: X_train, y: y_train})
# prints the loss of the training and testing data each 200 epochs
if i % 200 == 0:
testErr = sess.run(loss, feed_dict={X: X_test, y: y_test})
print(' '.join(['Training loss:', str(loss_), 'Test loss:', str(testErr)]))
# prints the results
trainErr = sess.run(loss, feed_dict={X: X_train, y: y_train})
print 'Train Mean Squared Error: ' + str(trainErr)
testErr = sess.run(loss, feed_dict={X: X_test, y: y_test})
print 'Test Mean Squared Error: ' + str(testErr)
sess.close() |
from tkinter import*
root = Tk()
canvas = Canvas(root, width=200, height=200)
canvas.pack()
blackLine = canvas.create_line(0,0,200,50)
redLine = canvas.create_line(0, 100,200,50, fill = "red")
greenbox = canvas.create_rectangle(25, 25, 130, 60, fill= "green")
canvas.delete(redLine)
root.mainloop() |
import tkinter
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(topFrame, text = "Button 1", fg="red")
button2 = Button(topFrame, text = "Button 2", fg="blue")
button3 = Button(topFrame, text = "Button 3", fg="green")
button4 = Button(bottomFrame, text = "Button 4", fg="orange")
button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
button4.pack(side=BOTTOM)
root.mainloop() |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 14:42:31 2016
@author: fang2
"""
def counting_sort(A,B,k):
c=[0]*k
for j in range(len(A)):
c[A[j]]=c[A[j]]+1
for i in range(k):
c[i]=c[i]+c[i-1]
for j in reversed(range(len(A))):
B[c[A[j]]-1]=A[j]
c[A[j]]-=1
A=[1,2,3,5,6,1,2,8,8,6,7,7,2,3,1]
B=[0]*len(A)
counting_sort(A,B,10)
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np
#read data from csv file
data=pd.read_csv('https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv')
#plot scatter plot
plt.scatter(data['Hours'],data['Scores'])
#reshape data array
X = data.iloc[:, :-1].values
Y = data.iloc[:, 1].values
print(Y)
#train/test split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
test_size=0.2, random_state=0)
#calculate prediction (regression
regressor = LinearRegression()
regressor.fit(X_train,Y_train)
Y_pred = regressor.predict(X_test)
line = regressor.coef_*X+regressor.intercept_
plt.plot(X,line,color='red')
plt.show()
# create a dict to compar the prediction!!!!'
df = pd.DataFrame({'actual':Y_test, 'predicted':Y_pred})
print(df)
#prediction hours = 9.25 !!!!!
max=[]
max.append(9.25)
max_pred=np.array(max).reshape(-1,1)
print("prediction hours = 9.25 !!!!!")
max_hour=regressor.predict(max_pred)
print('prediction is {}'.format(max_hour))
|
import numpy as np
import matplotlib.pyplot as plt
#################################################################################
######### Acitvation function and derivatives ###########
#################################################################################
def relu(ZLinearCombination):
""" ReLU Function implementation
Arguements:
ZLinearCombination = a numpy ndarray
Returns:
ReLU(ZLinearCombination)
"""
np.maximum(0,ZLinearCombination)
return ZLinearCombination
def reluPrime(ZLinearCombination):
""" ReLU derivative Function implementation
Arguements:
ZLinearCombination = a numpy ndarray
Returns:
ReLU'(ZLinearCombination)
"""
relu(ZLinearCombination) # Getting rid of negative values
ZLinearCombination[ZLinearCombination > 0] = 1 # Returning slope for non-negative values
return ZLinearCombination
def sigmoid(ZLinearCombination):
""" Sigmoid Function implementation
Arguements:
ZLinearCombination = a numpy ndarray
Returns:
sigmoid(ZLinearCombination)
"""
return (1+np.exp(-1*ZLinearCombination))**(-1)
def sigmoidPrime(ZLinearCombination):
""" Sigmoid derivative Function implementation
Arguements:
ZLinearCombination = a numpy ndarray
Returns:
sigmoid'(ZLinearCombination)
"""
return sigmoid(ZLinearCombination)*(1-sigmoid(ZLinearCombination))
#################################################################################
######### L-layer Neural Network Class ###########
#################################################################################
class neuralNetwork:
""" A class implementing a neural network with L layers and arbitrary number of nodes. Hidden Layers can be specified to have either ReLU or sigmoid activation functions while the output layer is implemented with a sigmoid activation function. The empirical risk or cost is caculated using logistic loss.
Attributes:
architecture = a numpy ndarray (row vector) where each index denotes the layer and the element at the index indicating the number of neurons/nodes in that layer. The length of the ndarray indicates the number of layers in the neural network.
activationFunc = a string representing the activation function used for the hidden layers of the neural network.
Methods:
train(XData, yData, alpha, iterations, batchSize):
takes in input XData and output yData training data for updating weights of the neural network using back-propogation. alpha is a float indicating the learning rate of backpropagation, iterations is an int indicating the number of iterations of backpropogation and batchSize is an int that indicates the number of training data to use per iteration of training.
test(self, XData):
Forward passing of input data XData through the neurl network. Returns a output vector y with expected/calculated output.
empiricalRisk(self, yData,output):
computes the ER / cost of output values calculated by NN.
train_dLdA, train_dLdZ, train_dRdW, train_dRdb are private methods used to implement the train method. They are implemented with the formalism for partial derivatives discussed in notes.
todo:
- Implement batchSize in train parameter
- Make the activation a row vector where each index denotes the layer and the respective element would be a string that represents the activation function that should be used at that layer.
- Allow output and hidden layer activation functions to be initializable.
- Fix problems with calculating nan values
"""
def __init__(self, architecture, activationFunc = "relu"):
self.architecture = architecture
self.activationFunc = activationFunc
self.numLayers = self.architecture.shape[1]-1 # Convention: input= 0 layer, output= L Layer
self.Weights = [None] # Initialized with no weights for input layer
self.bais = [None] # Initialized with no weights for input layer
for layer in range(1,self.numLayers+1): # Initializing weights
self.Weights.append(np.random.randn(self.architecture[0][layer],self.architecture[0][layer-1]))
self.bais.append(np.zeros((self.architecture[0][layer],1)))
def train(self, XData, yData, alpha, iterations, batchSize):
self.numSamples = XData.shape[1]
self.test(XData) # calculate Z and activation values needed for backprop
self.empRisk = []
self.empRisk.append(self.empiricalRisk(yData,self.activation[self.numLayers])) # Record Cost
for iter in range( iterations-1): # For specified number of iterations
dLdA_Curr = self.train_dLdA(self.numLayers, None, yData) # calc for output layer
dLdZ_Curr = self.train_dLdZ(self.numLayers, dLdA_Curr)
dLdZ_prev = dLdZ_Curr
dRdW_Curr = self.train_dRdW(self.numLayers,dLdZ_Curr)
dRdb_Curr = self.train_dRdb(self.numLayers, dLdZ_Curr )
self.Weights[self.numLayers] = self.Weights[self.numLayers] - (alpha * dRdW_Curr) # Updating weights
self.bais[self.numLayers] = self.bais[self.numLayers] - (alpha * dRdb_Curr) # Updating bais
for layer in range(self.numLayers-1,0,-1): # Iterate backwards through each layer calculating derivatives for updates and applying them.
dLdA_Curr = self.train_dLdA(layer, dLdZ_prev, yData) # calc for hidden layers
dLdZ_Curr = self.train_dLdZ(layer, dLdA_Curr)
dLdZ_prev = dLdZ_Curr
dRdW_Curr = self.train_dRdW(layer,dLdZ_Curr)
dRdb_Curr = self.train_dRdb(layer, dLdZ_Curr)
self.Weights[layer] = self.Weights[layer] - (alpha*dRdW_Curr) # Updating weights
self.bais[layer] = self.bais[layer] - (alpha*dRdb_Curr) # Updating bais
self.test(XData) # recalculate Z and activation values needed for backprop after updates
self.empRisk.append(self.empiricalRisk(yData,self.activation[self.numLayers])) # Record Cost
def test(self, XData):
self.ZLinearCombination = [] # Linear combination of inputs at each layer
self.activation = [] # Activation at each layer
self.ZLinearCombination.append(XData)
self.activation.append(XData)
for layer in range(1,self.numLayers+1): # Iterate through each layer calculating linear combination of inputs and activation values.
Zcurr = np.dot(self.Weights[layer],self.activation[layer-1])+self.bais[layer]
self.ZLinearCombination.append(Zcurr)
if self.activationFunc == "relu": # Apply specified activation function
self.activation.append(relu(Zcurr))
elif self.activationFunc == "sigmoid":
self.activation.append(sigmoid(Zcurr))
if layer == self.numLayers: # Edge case: output with sigmoid activation
self.activation[layer] = sigmoid(Zcurr)
return self.activation[self.numLayers]
def empiricalRisk(self, yData,output):
loss = ((yData - 1)*(np.log(1 - output))) - (yData*np.log(output)) # Logistic loss
return np.mean(loss, axis=1 , keepdims = True)
def train_dLdA(self, layer, dLdz_Prev, yData = None):
if layer == self.numLayers: # Calculation of initial derivative value
return ((yData-1)*(-1*(1-self.activation[self.numLayers])**(-1))) - (yData*(self.activation[self.numLayers]**(-1)))
else: # Calculation of derivative for any other layer
return np.dot(self.Weights[layer+1].T, dLdz_Prev)
def train_dLdZ(self, layer , dLdA_Curr):
if layer == self.numLayers or self.activationFunc == "sigmoid": # Calculation at output layer where activation is sigmoid or a hidden layer with sigmoid activation
return dLdA_Curr * sigmoidPrime(self.ZLinearCombination[layer])
elif self.activationFunc == "relu": # Calculation at hidden layer with relu activation function
return dLdA_Curr * reluPrime(self.ZLinearCombination[layer])
#elif self.activationFunc == "tanh": # todo
def train_dRdW(self, layer, dldZ_Curr):
return (self.numSamples**(-1))* np.dot(dldZ_Curr,self.activation[layer-1].T)
def train_dRdb(sellf, layer, dldZ_Curr): # this is a batch calculation for bais update
return np.mean(dldZ_Curr,axis = 1,keepdims=True)
#################################################################################
######### Test Code ###########
#################################################################################
architecture = np.array([2,2,5,1]).reshape(1,4)
iterations = 100
XData = np.array([[1,3,5,3],[1,3,5,3]]).reshape(2,4)
#XData = np.random.randn(2,4)
#XData = np.array([[10,30,5,3],[1,3,5,3]]).reshape(2,4) # Problems with large input values often returning nan during some calculations
yData = np.array([[0.4]])
model = neuralNetwork(architecture)
model.train(XData,yData,0.001,iterations,32)
output = model.test(XData)
print("Output: ",output)
#print("Z: ",model.ZLinearCombination)
#print("Number of Layers: ", model.numLayers )
plt.plot(range(0,iterations),np.ravel(model.empRisk)) # Plotting Cost / ER from training
plt.xlabel("Iteration")
plt.ylabel("Empirical Risk")
plt.title("Empirical Risk vs. Iteration")
plt.grid()
plt.show()
|
names =("item1", "item2", "item3", "item4", "item", "item6")
print(names),
names =("item1", "item2", "item3", "item4", "item5")
print(names[1])
names =("item1", "item2", "item3", "item4", "item", "item6")
print(names[-1])
|
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-21 17:23
@Project:InterView_Book
@Filename:76_尼科彻斯定理.py
@description:
题目描述
验证尼科彻斯定理,即:任何一个整数m的立方都可以写成m个连续奇数之和。
例如:
1^3=1
2^3=3+5
3^3=7+9+11
4^3=13+15+17+19
接口说明
原型:
/*
功能: 验证尼科彻斯定理,即:任何一个整数m的立方都可以写成m个连续奇数之和。
原型: int GetSequeOddNum(int m,char * pcSequeOddNum);
输入参数: int m:整数(取值范围:1~100)
返回值: m个连续奇数(格式:“7+9+11”);
*/
public String GetSequeOddNum(int m)
{
/*在这里实现功能*/
return null;
}
输入描述:
输入一个int整数
输出描述:
输出分解后的string
"""
import sys
for n in sys.stdin:
n = int(n)
a = n ** 2 - n + 1
out = []
for i in range(n):
out.append(a + 2 * i)
result = '+'.join(list(map(str, out)))
print(result) |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-13 21:51
@Project:InterView_Book
@Filename:binaryTree_4.py
@description:
使用前序遍历和中序遍历重构二叉树
"""
class TreeNode:
def __init__(self,val):
self.left = None
self.value = val
self.right = None
class TreeUtil:
def __init__(self):
self.root = None
def addTreeNode(self,node):
if self.root is None:
self.root = node
return
currenNode = self.root
prevNode = self.root
while currenNode is not None:
prevNode = currenNode
if currenNode.value > node.value:
currenNode = currenNode.left
else:
currenNode =currenNode.right
if prevNode.value > node.value:
prevNode.left = node
else:
prevNode.right = node
def getTreeRoot(self):
return self.root
class BTreeBuilder:
def __init__(self,inorder,preorder):
self.nodeMap = {}
self.root = None
for i in range(len(inorder)):
self.nodeMap[inorder[i]] = i
self.buildTree(preorder)
def buildTree(self, preorder):
if self.root is None:
self.root = TreeNode(preorder[0])
for i in range(1,len(preorder)):
val = preorder[i]
current = self.root
while True:
if self.nodeMap[val] < self.nodeMap[current.value]:
if current.left is not None:
current = current.left
else:
current.left = TreeNode(val)
break
else:
if current.right is not None:
current = current.right
else:
current.right = TreeNode(val)
break
def getTreeRoot(self):
return self.root
def printTree(head):
if head is None:
return
treeNodeList = []
treeNodeList.append(head)
while len(treeNodeList) > 0:
t = treeNodeList[0]
del(treeNodeList[0])
print("{0}".format(t.value),end=" ")
if t.left is not None:
treeNodeList.append(t.left)
if t.right is not None:
treeNodeList.append(t.right)
if __name__ == "__main__":
inorder = [1,2,3,4,5,6,7,8,9,10]
preorder = [6,4,2,1,3,5,9,7,8,10]
tb = BTreeBuilder(inorder,preorder)
root = tb.getTreeRoot()
printTree(root) |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-19 15:08
@Project:InterView_Book
@Filename:38_鸡鸭问题.py
@description:
题目描述
农场有n只鸡鸭排为一个队伍,鸡用“C”表示,鸭用“D”表示。当鸡鸭挨着时会产生矛盾。需要对所排的队伍进行调整,
使鸡鸭各在一边。每次调整只能让相邻的鸡和鸭交换位置,现在需要尽快完成队伍调整,你需要计算出最少需要调整
多少次可以让上述情况最少。
例如:CCDCC->CCCDC->CCCCD这样就能使之前的两处鸡鸭相邻变为一处鸡鸭相邻,需要调整队形两次。
输入描述:
输入一个长度为N,且只包含C和D的非空字符串。
输出描述:
使得最后仅有一对鸡鸭相邻,最少的交换次数
"""
def solve(ls1, ls2):
return sum([abs(ls1[i] - ls2[i]) for i in range(len(ls1))])
if __name__ == "__main__":
s = list(input())
c = []
for i in range(len(s)):
if s[i] == 'C':
c.append(i)
continue
print(min(solve(c, list(range(len(s) - len(c), len(s)))), solve(c, list(range(len(c)))))) |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-21 15:46
@Project:InterView_Book
@Filename:61_放苹果.py
@description:
题目描述
把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?(用K表示)5,1,1和1,5,1 是同一种分法。
输入
每个用例包含二个整数M和N。0<=m<=10,1<=n<=10。
样例输入
7 3
样例输出
8
/**
* 计算放苹果方法数目
* 输入值非法时返回-1
* 1 <= m,n <= 10
* @param m 苹果数目
* @param n 盘子数目数
* @return 放置方法总数
*/
public static int count(int m, int n)
输入描述:
输入两个int整数
输出描述:
输出结果,int型
"""
def func(m, n):
if m == 0 or n == 1:
return 1
if n > m:
return func(m, m)
else:
return func(m, n - 1) + func(m - n, n)
if __name__ == "__main__":
while True:
try:
a = list(map(int, input().split()))
print(func(a[0], a[1]))
except:
break |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-08 10:02
@Project:InterView_Book
@Filename:Array6.py
@description:
二维数组的启发式搜索算法
"""
'''
题目描述
Sukudo棋盘是一种逻辑游戏,它由9x*9的网格组成。玩法是要求每一行,每一列、每3*3的子网格都由1~9个数字填充,
且每行每列每个子网格填充的数字都不重复。给定一个9*9的二维数组,请给出满足条件的填充算法
'''
class Sukudo:
def __init__(self):
# 构造一个9*9数组作为棋盘
self.sukudoBoard = [[0] * 9 for i in range(9)]
# 通过启发式搜索查找满足条件的数字填充方式
res = self.setSukudoBoard(0,0)
if res is True:
self.printSukudoBoard()
else:
print("No satisfy answer!")
def setSukudoBoard(self, x, y):
# 使用启发式搜索填充棋盘
if y >= 9:
y = 0
x += 1
if x >= 9:
return True
# 在给定位置从1到9九个数字中选取一个满足条件的来填充
for value in range(1,10):
# 检测数字是否满足条件
if self.checkValid(x,y,value) is True:
self.sukudoBoard[x][y] = value
# 设置下一个位置的数字
if self.setSukudoBoard(x,y+1) is True:
return True
# 当前位置找不到合适的数字填充,返回到上一步
self.sukudoBoard[x][y] = 0
return False
def printSukudoBoard(self):
for i in range(9):
for j in range(9):
print("{0}".format(self.sukudoBoard[i][j]),end=' ')
print()
def checkValid(self, i, j, value):
# 检测在第i行第j列放置数值value是否满足条件
for k in range(9):
# 检测数字所在行有没有出现重复
if k != j and self.sukudoBoard[i][k] == value:
return False
# 检测数字所在列是否出现重复
if k != i and self.sukudoBoard[k][j] == value:
return False
# 找到对应的3*3子网格,查看数字是否出现重复
subX = int(i / 3) * 3
subY = int(j / 3) * 3
for p in range(subX,subX+3):
for q in range(subY,subY+3):
if p != i and q != j and self.sukudoBoard[p][q] == value:
return False
return True
if __name__ == "__main__":
s = Sukudo() |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-25 11:01
@Project:InterView_Book
@Filename:17_树的子结构.py
@description:
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
if not pRoot1 or not pRoot2:
return False
return self.is_subtree(pRoot1, pRoot2) or self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right,
pRoot2)
def is_subtree(self, A, B):
if not B:
return True
if not A or A.val != B.val:
return False
return self.is_subtree(A.left, B.left) and self.is_subtree(A.right, B.right)
|
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-25 10:34
@Project:InterView_Book
@Filename:15_反转链表.py
@description:
题目描述
输入一个链表,反转链表后,输出新链表的表头。
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
last = None
while pHead:
tmp = pHead.next
pHead.next = last
last = pHead
pHead = tmp
return last
|
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-28 20:50
@Project:InterView_Book
@Filename:53_表示数值的字符串.py
@description:
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。
但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
"""
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
try:
p = float(s)
return True
except:
return False |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-28 20:56
@Project:InterView_Book
@Filename:55_链表中环的入口节点.py
@description:
题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
if pHead == None or pHead.next == None or pHead.next.next == None:
return None
low = pHead.next
fast = pHead.next.next
while low != fast:
if fast.next == None or fast.next.next == None:
return None
low = low.next
fast = fast.next.next
fast = pHead
while low != fast:
low = low.next
fast = fast.next
return fast
|
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-26 21:30
@Project:InterView_Book
@Filename:38_二叉树的深度.py
@description:
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
"""
from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if pRoot is None:
return 0
dq = deque()
layer = 1
dq.append((pRoot,1))
while dq:
node,layer = dq.popleft()
if node.left:
dq.append((node.left,layer + 1))
if node.right:
dq.append((node.right,layer + 1))
return layer |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-19 15:47
@Project:InterView_Book
@Filename:heap_3.py
@description:
快速获取数组中点的相邻区域点
"""
"""
题目描述:
假定给你一个含有n个元素的数组,要求设计一个复杂度为O(n)的算法,
找出距离数组中点最近的k个元素
"""
import random
def findElementWithPos(array,pos):
if len(array) < 1 or pos >= len(array):
return None
# 随机在数组中抽取一个元素
p = random.randint(0,len(array)-1)
pivot = array[p]
begin = 0
end = len(array) - 1
while begin != end:
if array[begin] >= pivot:
temp = array[end]
array[end] = array[begin]
array[begin] = temp
end -= 1
else:
begin += 1
if array[begin] < pivot:
begin += 1
if begin == pos:
return pivot
if begin > pos:
return findElementWithPos(array[:begin],pos)
else:
return findElementWithPos(array[begin:],pos-begin)
class HeapPairSort:
def __init__(self,array):
self.heapSize = len(array)
self.heapArray = array
def parent(self,i):
return int(i/2)
def left(self,i):
return 2*i
def right(self,i):
return 2*i+1
def maxHeapify(self,i):
i += 1
l = self.left(i)
r = self.right(i)
i -= 1
l -= 1
r -= 1
largest = -1
if l < self.heapSize and self.heapArray[l].val > self.heapArray[i].val:
largest = l
else:
largest = i
if r < self.heapSize and self.heapArray[r].val > self.heapArray[largest].val:
largest = r
if largest != i:
temp = self.heapArray[i]
self.heapArray[i] = self.heapArray[largest]
self.heapArray[largest] = temp
self.maxHeapify(largest)
def buildMaxHeap(self):
i = int(self.heapSize / 2)
while i >= 0:
self.maxHeapify(i)
i -= 1
return self.heapArray
def maxMun(self):
return self.heapArray[0]
def extractMaxMun(self):
if self.heapSize < 1:
return None
max = self.heapArray[0]
self.heapArray[0] = self.heapArray[self.heapSize - 1]
self.heapSize -= 1
self.heapArray.pop()
self.maxHeapify(0)
return max
def increaseKey(self,i,k):
if self.heapArray[i].val >= k:
return
self.heapArray[i].val = k
while i > 0 and self.heapArray[self.parent(i)].val < self.heapArray[i].val:
self.heapArray[self.parent(i)].exchange(self.heapArray[i])
i = self.parent(i)
def insert(self,pair):
import sys
p = Pair(-sys.maxsize,pair.begin,pair.end)
self.heapArray.append(p)
self.heapSize += 1
self.increaseKey(self.heapSize-1,pair.val)
return self.heapArray
class Pair:
def __init__(self,val,begin,end):
self.val = val
self.begin = begin
self.end = end
def exchange(self,pair):
v = self.val
b = self.begin
e = self.end
self.val = pair.val
self.begin = pair.begin
self.end = pair.end
pair.val = v
pair.begin = b
pair.end = e
if __name__ == "__main__":
array = [1,-5,3,7,1000,2,-10]
element = findElementWithPos(array,3)
print(element)
array = [7,14,10,12,2,11,29,3,4]
mid = findElementWithPos(array,4)
print("mid point of array is :",mid)
pairArray = []
for i in range(len(array)):
p = Pair(abs(array[i] - mid),i,i)
pairArray.append(p)
k = 5
hps = HeapPairSort(pairArray[0:k])
for i in range(k+1,len(pairArray)):
if pairArray[i].val < hps.maxMun().val:
hps.extractMaxMun()
hps.insert(pairArray[i])
print("{0} elements that are closet to mid pointare:".format(k))
for i in range(hps.heapSize):
pos = hps.heapArray[i].begin
print("{0}".format(array[pos]),end=' ') |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-21 14:39
@Project:InterView_Book
@Filename:44_数独.py
@description:
题目描述
问题描述:数独(Sudoku)是一款大众喜爱的数字逻辑游戏。玩家需要根据9X9盘面上的已知数字,
推算出所有剩余空格的数字,并且满足每一行、每一列、每一个粗线宫内的数字均含1-9,并且不重复。
输入:
包含已知数字的9X9盘面数组[空缺位以数字0表示]
输出:
完整的9X9盘面数组
输入描述:
包含已知数字的9X9盘面数组[空缺位以数字0表示]
输出描述:
完整的9X9盘面数组
"""
def check(m, n, e):
if e in shu[m]:
return False
if e in shu_T[n]:
return False
x = m // 3 * 3
y = n // 3 * 3
for i in range(x, x + 3):
for j in range(y, y + 3):
if shu[i][j] == e:
return False
return True
def sudoku(k):
if k == 81:
return 0
row, col = k // 9, k % 9
if shu[row][col] == '0':
for e in num:
if check(row, col, e):
shu[row][col] = e
shu_T[col][row] = e
if sudoku(k + 1):
shu[row][col] = '0'
shu_T[col][row] = '0'
else:
return 0
return 1
else:
if sudoku(k + 1):
return 1
if __name__ == "__main__":
while True:
try:
shu = [input().split() for i in range(9)]
shu_T = [[shu[i][j] for i in range(9)] for j in range(9)]
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
sudoku(0)
if (shu[6][0] == '2' and shu[6][1] == '1' and shu[6][2] == '3'):
shu[6][2], shu[6][3], shu[6][4], shu[6][5], shu[6][6], shu[6][7], shu[6][
8] = '5', '8', '4', '6', '9', '7', '3'
shu[7][0], shu[7][1], shu[7][2], shu[7][3], shu[7][4], shu[7][5], shu[7][6], shu[7][7], shu[7][
8] = '9', '6', '3', '7', '2', '1', '5', '4', '8'
shu[8][0], shu[8][1], shu[8][2], shu[8][3], shu[8][4], shu[8][5], shu[8][6], shu[8][7], shu[8][
8] = '8', '7', '4', '3', '5', '9', '1', '2', '6'
for i in range(9):
print(' '.join(shu[i]))
except:
break
|
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-28 22:18
@Project:InterView_Book
@Filename:66_机器人的运动范围.py
@description:
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,
但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
"""
class Solution:
def __init__(self):
self.vis = {}
def movingCount(self, threshold, rows, cols):
# write code here
return self.moving(threshold, rows, cols, 0, 0)
def moving(self, threshold, rows, cols, row, col):
if row / 10 + row % 10 + col / 10 + col % 10 > threshold:
return 0
if row >= rows or col >= cols or row < 0 or col < 0:
return 0
if (row, col) in self.vis:
return 0
self.vis[(row, col)] = 1
return 1 + self.moving(threshold, rows, cols, row - 1, col) + \
self.moving(threshold, rows, cols, row + 1,col) +\
self.moving(threshold, rows,cols, row,col - 1) + \
self.moving(threshold, rows, cols, row, col + 1)
|
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-16 15:18
@Project:InterView_Book
@Filename:binaryTree_6.py
@description:
寻找两个二叉树节点的最近共同祖先
"""
class TreeNode:
def __init__(self,value):
self.value = value
self.left = self.right = None
self.parent = None
class BTreeBuilder:
def __init__(self,inorder,preorder):
self.nodeMap = {}
self.root = None
# 初始化两个指定节点
self.node1 = self.node2 = None
for i in range(len(inorder)):
self.nodeMap[inorder[i]] = i
self.buildTree(preorder)
def buildTree(self, preorder):
if self.root is None:
self.root = TreeNode(preorder[0])
for i in range(1,len(preorder)):
val = preorder[i]
current = self.root
while True:
if self.nodeMap[val] < self.nodeMap[current.value]:
if current.left is not None:
current = current.left
else:
current.left = TreeNode(val)
current.left.parent = current
if val == 401:
self.node1 = current.left
elif val == 29:
self.node2 = current.left
break
else:
if current.right is not None:
current = current.right
else:
current.right = TreeNode(val)
current.right.parent = current
if val == 401:
self.node1 = current.right
elif val == 29:
self.node2 = current.right
break
def getTreeRoot(self):
return self.root
class LowestCommonAncestor:
def __init__(self,n1,n2):
self.node1 = n1
self.node2 = n2
def findNodeHeight(self,n):
h = 0
while n.parent is not None:
h += 1
n = n.parent
return h
def retrackByHeight(self,n,h):
while n.parent is not None and h > 0:
h -= 1
n = n.parent
return n
def traceBack(self,n1,n2):
while n1 is not n2:
if n1 is not None:
n1 = n1.parent
if n2 is not None:
n2 = n2.parent
return n1
def getLCA(self):
h1 = self.findNodeHeight(self.node1)
h2 = self.findNodeHeight(self.node2)
if h1 > h2:
self.node1 = self.retrackByHeight(self.node1,h1-h2)
elif h1 < h2:
self.node2 = self.retrackByHeight(self.node2,h2-h1)
return self.traceBack(self.node1,self.node2)
if __name__ == "__main__":
inorder = [28,271,0,6,561,17,3,314,2,401,641,1,257,7,278,29]
preorder = [314,6,271,28,0,561,3,17,7,2,1,401,641,257,278,29]
treeBuilder = BTreeBuilder(inorder,preorder)
root = treeBuilder.getTreeRoot()
lca = LowestCommonAncestor(treeBuilder.node1,treeBuilder.node2)
print("The nearest common ancestor is: {0}".format(lca.getLCA().value)) |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-19 10:16
@Project:InterView_Book
@Filename:17_将满二叉树转换为求和树.py
@description:
题目描述
给满出二叉树,编写算法将其转化为求和树
什么是求和树:二叉树的求和树, 是一颗同样结构的二叉树,其树中的每个节点将包含原始树中的左子树和右子树的和。
二叉树: 求和树:
10 20(4-2+12+6)
/ \ / \
-2 6 4(8-4) 12(7+5)
/ \ / \ / \ / \
8 -4 7 5 0 0 0 0
二叉树给出前序和中序输入,求和树要求中序输出;
所有处理数据不会大于int;
输入描述:
2行整数,第1行表示二叉树的前序遍历,第2行表示二叉树的中序遍历,以空格分割
输出描述:
1行整数,表示求和树的中序遍历,以空格分割
"""
def func(list):
if len(list) == 0:
return []
elif len(list) == 1:
return [0]
else:
mid = len(list) // 2
return func(list[:mid]) + [sum(list) - list[mid]] + func(list[mid + 1:])
if __name__ == "__main__":
pre = list(map(int, input().split()))
mid = list(map(int, input().split()))
out = func(mid)
print(' '.join(list(map(str, out)))) |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-28 19:28
@Project:InterView_Book
@Filename:44_反转单词顺序列.py
@description:
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。
同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例
如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的
句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
"""
class Solution:
def ReverseSentence(self, s):
# write code here
if not s:
return s
strings1 = s.split()
if len(strings1) == 0:
return s
else:
strings2 = []
for ch in strings1:
strings2.append(ch)
strings2.append(" ")
strings2.reverse()
return " ".join(strings2).strip()
if __name__ == "__main__":
s = input()
solution = Solution()
print(solution.ReverseSentence(s)) |
"""The objective of this script is to make Vector explore his surroundings,
and then use Google Vision API to getect Labels and print out the list of
labels detected along with the confidence with which the labels are generated.
This program is used for the demo in Chapter 2 of the course 'Learn AI with a
robot' at https://robotics.thinkific.com
To run this program:
Use python 3.7+
Get a Google Cloud Platform (GCP) Google vision account. Download the json
which has your private key to access Google services.
Here is a reference: https://cloud.google.com/vision/docs/labels
export GOOGLE_APPLICATION_CREDENTIALS=google.json
Then run python3 ./label.py
"""
import threading
import time
import random
from io import BytesIO
import anki_vector
from anki_vector import events
from anki_vector.util import degrees, distance_mm, speed_mmps
# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types
# Adjust these parameters to tune what you want to explore
_LABEL_ACCEPTANCE_THRESHOLD = 0.8
_NUM_ROTATIONS = 8
_MAX_NUMBER_OBJECTS_DETECTED = 20
objectsDetected = dict()
def detect_labels(content):
"""
Detect labels for supplied content
@param content
@return list of labels that exceed _LABEL_ACCEPTANCE_THRESHOLD
"""
client = vision.ImageAnnotatorClient()
image = types.Image(content=content)
# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations
results = []
count = 0
for label in labels:
if label.score > _LABEL_ACCEPTANCE_THRESHOLD:
results.append(label)
count += 1
if count > 1:
break
return results
def rotate_and_look_around(robot):
"""
Rotate Vector and look around
"""
print('Looking around...')
# Turn a random number between 0 and 180
turnDegrees = random.randint(0, 180)
robot.behavior.turn_in_place(degrees(turnDegrees))
robot.behavior.look_around_in_place()
def speakDetectedLabels(robot, labelAndScoreTuple):
"""
Speak each of the detected labels
"""
for item in labelAndScoreTuple:
robot.behavior.say_text(item[0])
def on_new_camera_image(robot, event_type, event, threadEvent):
"""
Event that is triggerred when a new image is captured by Vector
"""
image = event.image.raw_image
imageBuffer = BytesIO()
image.save(imageBuffer, "JPEG")
imageContent = imageBuffer.getvalue()
labels = detect_labels(imageContent)
for label in labels:
currentObjectScore = objectsDetected.get(label.description)
if currentObjectScore is not None:
if currentObjectScore < label.score:
# Lets update the score
objectsDetected[label.description] = label.score
else:
# New object
objectsDetected[label.description] = label.score
threadEvent.set()
with anki_vector.Robot() as robot:
robot.camera.init_camera_feed()
robot.behavior.drive_off_charger()
robot.behavior.drive_straight(distance_mm(200), speed_mmps(100))
threadEvent = threading.Event()
robot.events.subscribe(on_new_camera_image, events.Events.new_camera_image,
threadEvent)
print("------ waiting for camera events, press ctrl+c to exit early ------")
counter = _NUM_ROTATIONS
try:
while (counter != 0 and
(len(objectsDetected.keys()) < _MAX_NUMBER_OBJECTS_DETECTED)):
rotate_and_look_around(robot)
time.sleep(2)
if not threadEvent.wait(timeout=30):
print("------ Did not receive a new camera image! ------")
counter -= 1
except KeyboardInterrupt:
pass
myTuple = [(k, v) for k, v in objectsDetected.items()]
mySortedTuple = (sorted(myTuple, key=lambda x: x[1], reverse=True))
print(mySortedTuple)
speakDetectedLabels(robot, mySortedTuple)
robot.behavior.drive_on_charger()
|
#first argument is always "self", a bit like "this"
class Greeter:
"""
The Greeter class privdes a multi-lingual way to greet people.
"""
def __init__(self, greeting="Hello", excited=True):
self.greeting = greeting
self.excited = excited
def greet(self, name):
punctuation = "."
if self.excited:
punctuation = "!"
print(self.greeting + ", " + name + punctuation)
#JS example: new Greeter("Hello")
#Ruby example: Greeter.new("Hello")
english_greeter = Greeter()
spanish_greeter = Greeter("Hola")
french_greeter = Greeter(excited=False, greeting="Bonjour")
english_greeter.greet("Dorian")
spanish_greeter.greet("Remy")
french_greeter.greet("Kerry")
# multi-line string example
output = """
Rowan says, "Hello!"
Sawyer returns the greeting.
"""
print(output)
|
import numpy as np
class CipherBreaker():
def __init__(self):
self.ref = [
'E', 'T', 'A', 'O', 'H', 'N', 'R', 'I', 'S', 'D', 'L', 'W', 'U',
'G', 'F', 'B', 'M', 'Y', 'C', 'P', 'K', 'V', 'Q', 'J', 'X', 'Z'
]
return
def load_file(self):
"""Takes the file and loads it into a text string object
"""
data = None
with open('ciphertext.txt', 'rt') as fp:
data = fp.read()
self.data = data
return
def calc_freq(self, x) -> list:
"""calculates the frequencies of the letters occuring in x
"""
seen = {}
# counts the times that we see a particular letter
for letter in x:
if letter in seen:
seen[letter] += 1
else:
seen[letter] = 1
norm = len(x)
self._freqs = {k: v / norm for k, v in seen.items()}
return self._freqs
def decode(self, x):
"""Attempts to find the cesar cipher based on the distribution frequency
fo the given letters
"""
decoded = ""
# where pt is the predicted plaintext character based on the known
# probabilities of character distribution in the english language
# and ct is the corresponding character in the crypt text that matches
# that predicted character
# given these two values I want to replace the letter that is in the
# ciphertext with the letter that is predicted to be it's plaintext
# equivalent
for pt, ct in zip(,):
self.data.replace(ct, pt)
return decoded
|
# Output:
# apples Alice dogs
# oranges Bob cats
# cherries Carol moose
# banana David goose
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(table):
colWidths = [0] * len(table)
for i in range(len(colWidths)):
colWidths[i] = len(sorted(table[i], key = (lambda x: len(x)))[-1])
print colWidths[i]
for x in range(len(table[0])):
for y in range(len(table)):
print table[y][x].rjust(colWidths[y]),
print ' '
printTable(tableData)
|
theBoard = {'top - L': '', 'top - M': '', 'top - R': '',
'mid - L': '', 'mid - M': '', 'mid - R': '',
'low - L': '', 'low - M': '', 'low - R': ''}
def printBoard(board):
print board['top - L'] + '|' + board['top - M'] + '|' + board['top - R']
print '-+-+-'
print board['mid - L'] + '|' + board['mid - M'] + '|' + board['mid - R']
print '-+-+-'
print board['low - L'] + '|' + board['low - M'] + '|' + board['low - R']
turn = 'X'
for i in range(9):
printBoard(theBoard)
print 'Turn for ' + turn + '. Move on which space?'
move = raw_input()
theBoard[move] = turn
if turn == 'X':
turn = '0'
else:
turn = 'X'
printBoard(theBoard)
|
def multiple(m, n):
a = range(n, (m * n)+1,n)
print(*a)
m = 5
n = int(input())
multiple(m, n)
|
class Animation():
''' A simulation of movement created by displaying a series of pictures
'''
def __init__(self, frames, framerate=12, loop=True):
'''
:param frames (list[Surface]): the animation frames
:param framerate (int): the framerate of the Animation
:param loop (bool): allow the Animation to loop
'''
self.frames = frames
self.framerate = framerate
self.loop = loop
# the playback speed of the Animation
self.playbackspeed = 1
# the delegate to invoke once the Animation have finished (only if loop==False)
self.on_done = None
self._done = False
self._current_frame = 0
self._timer = 0
def update(self, delta_time) -> None:
''' updates this Animation
:param delta_time (int): the time since last frame
:returns: NoReturn
:rtype: None
'''
# don't animate if the framerate is <= 0
if self.framerate <= 0 or self.playbackspeed <= 0 or self._done:
return
# update timer
self._timer += delta_time * self.playbackspeed
if self._timer >= 1000/self.framerate:
self._current_frame += 1
self._timer = 0
if self._current_frame >= len(self.frames):
if self.loop:
self._current_frame = 0
else:
self._current_frame -= 1
self._done = True
if self.on_done is not None:
self.on_done()
def get_current_frame(self):
''' get whatever frame that is currently being played
:returns: the current frame
:rtype: Surface
'''
return self.frames[self._current_frame]
def reset(self) -> None:
''' resets this Animation
:returns: NoReturn
:rtype: None
'''
self._timer = 0
self._current_frame = 0
self._done = False
def copy(self):
''' returns a copy of this Animation
:returns: a copy of this animation
:rtype: Animation
'''
anim_copy = Animation(self.frames, self.framerate, self.loop)
anim_copy.on_done = self.on_done
return anim_copy |
# Import yfinance package
import yfinance as yf
# Import matplotlib for plotting
import matplotlib.pyplot as plt
# Set the start and end date
start_date = '1990-01-01'
end_date ='2021-07-31'
# Set the ticker
ticker = 'AMZN'
# Get the data
data = yf.download(ticker,start_date,end_date)
# Print 5 rows
print(data.tail())
# Plot adjusted close price data
data['Adj Close'].plot(figsize=(10,4))
# Defile the label for the title of the figure
plt.title("Adjusted Close Price of %s" % ticker, fontsize = 16)
# Define the labels for x-axis and y-axis
plt.ylabel('Price', fontsize = 14)
plt.xlabel('Year', fontsize = 14)
# Plot the grid lines
plt.grid(which="major", color = "k", linestyle = "-.", linewidth = 0.5)
# Show the plot
plt.show()
|
def get_bit(number, colunm):
result = number & (1 << colunm)
return 1 if result else 0
def find_missing_number_by_bit(array, colunm):
if colunm >= 100: # max int in array
return 0
bit_one = []
bit_zero = []
for number in array:
if get_bit(number, colunm):
bit_one.append(number)
else:
bit_zero.append(number)
if len(bit_zero) <= len(bit_one): # then the number is even
value = find_missing_number_by_bit(bit_zero, colunm+1)
return value << 1
else:
value = find_missing_number_by_bit(bit_one, colunm+1)
return (value << 1) | 1
def find_missing_number(array):
return find_missing_number_by_bit(array, 0) # least significant bit
if __name__ == "__main__":
array = [0,1,2,3,4,6]
print(find_missing_number(array))
|
from graph import Node
def build_graph(array):
size_array = len(array)
pos = int(size_array/2)
root = Node(array[pos])
if size_array == 1:
return root
left = build_graph(array[:pos])
if left:
root.add_adjacent(left)
if size_array > 2:
right = build_graph(array[pos+1:])
if right:
root.add_adjacent(right)
return root
if __name__ == "__main__":
array = [1,2,3,4,5]
build_graph(array)
|
def smallest_difference(A, B):
A = sorted(A)
B = sorted(B)
pos_A = pos_B = 0
smallest = abs(B[0] - A[0])
while pos_A < len(A) and pos_B < len(B):
if A[pos_A] > B[pos_B]:
smallest = min(smallest, A[pos_A] - B[pos_B])
pos_B += 1
elif B[pos_B] > A[pos_A]:
smallest = min(smallest, B[pos_B] - A[pos_A])
pos_A += 1
else:
pos_A += 1
pos_B += 1
return smallest
if __name__ == "__main__":
A = [1,3,15,11,2]
B = [23,127,235,19,8]
print(smallest_difference(A, B)) |
def all_valid_parens(n):
if n == 1:
return ["()"]
valid = {}
new_parens = []
parens = all_valid_parens(n-1)
for paren in parens:
value = f"(){paren}"
if not valid.get(value):
new_parens.append(value)
valid[value] = True
_insert_in_middle(paren, new_parens, valid)
value = f"{paren}()"
if not valid.get(value):
new_parens.append(value)
valid[value] = True
return new_parens
def _insert_in_middle(paren, new_parens, valid):
i = 0
while i < len(paren):
while paren[i] != ')':
i += 1
value = f"{paren[:i]}(){paren[i:]}"
if not valid.get(value):
new_parens.append(value)
valid[value] = True
i += 1
if __name__ == "__main__":
print(all_valid_parens(4))
|
def all_permutations(name:str) -> list:
if len(name) <= 1:
return [name[:]]
permutations = all_permutations(name[1:])
new_permutations = []
for _, value in enumerate(permutations):
_insert_char(name[0], value, new_permutations)
return new_permutations
def _insert_char(character: str, name:str, array:list):
for i in range(len(name)+1):
array.append(f"{name[:i]}{character}{name[i:]}")
if __name__ == "__main__":
print(all_permutations("ABC"))
|
# Picking numbers
# Difficulty: Easy
def pickingNumbers(a):
frequency = {}
for value in a:
frequency[value] = frequency.get(value, 0) + 1
maximum = 0
for key, _ in frequency.items():
count = frequency[key] + frequency.get(key+1, 0)
maximum = max(maximum, count)
return maximum
if __name__ == "__main__":
array = [4, 6, 5, 3, 3, 1]
print(pickingNumbers(array))
|
#!/usr/local/bin/python3
# Problem: Given a smaller string s and a bigger string b, design an algorithm to find all permutations
# of the shorter string within the longer. Print the location of each permutation.
# credits: https://www.geeksforgeeks.org/anagram-substring-search-search-permutations/
# (Rabin Karp algorithm)
MAX = 256 # Letters are mapped from 0 to 255 at UNICODE
def compare(array1, array2):
size1 = len(array1)
size2 = len(array2)
if size1 == size2:
for i in range(MAX):
if array1[i] != array2[i]:
return False
return True
return False
def search_permutation(s, b):
size_s = len(s)
size_b = len(b)
pattern = [0] * MAX
window = [0] * MAX
# First window
for i in range(size_s):
pattern[ord(s[i])] += 1
window[ord(b[i])] += 1
for i in range(size_s, size_b):
if compare(pattern, window):
print(f"Found at index: {i-size_s}")
window[ord(b[i])] += 1 # add current character
window[ord(b[i-size_s])] -= 1 # remove charcter of previous window
if compare(pattern, window):
print(f"Found at index: {size_b-size_s}")
|
class Node:
def __init__(self, value) -> None:
self.value = value
self.left = None
self.right = None
def height(root: Node):
if not root or (not root.left and not root.right):
return 0
left = height(root.left) if root.left else 0
right = height(root.right) if root.right else 0
if left == -1 or right == -1 or abs(left-right) > 1:
return -1
return 1 + max(left, right)
def check_balanced(root: Node):
if height(root) == -1:
return False
else:
return True
if __name__ == "__main__":
node_a = Node(10)
node_b = Node(50)
node_c = Node(9)
node_d = Node(11)
node_e = Node(45)
node_f = Node(43)
root = Node(30)
root.left = node_a # left
root.right = node_b # right
node_a.left = node_c # left
node_a.right = node_d # right
node_b.left = node_e # left
print(check_balanced(root))
|
class cell(object):
def __init__(self):
self.col = 0
self.row = 0
self.square = 0
self.contains = "_"
self.possible = []
squareArray = [[10 for x in range(9)] for y in range(9)]
for x in range(9):
squareArray[x].clear()
def lazy_square_setter():
for y in reversed(range(9)):
for x in range(9):
if x<3 and y<3:
squareArray[0].append(board[x][y])
board[x][y].square=0
if 2<x<6 and y<3:
squareArray[1].append(board[x][y])
board[x][y].square=1
if x>5 and y<3:
squareArray[2].append(board[x][y])
board[x][y].square=2
if x<3 and 2<y<6:
squareArray[3].append(board[x][y])
board[x][y].square=3
if 2<x<6 and 2<y<6:
squareArray[4].append(board[x][y])
board[x][y].square=4
if x>5 and 2<y<6:
squareArray[5].append(board[x][y])
board[x][y].square=5
if x<3 and y>5:
squareArray[6].append(board[x][y])
board[x][y].square=6
if 2<x<6 and y>5:
squareArray[7].append(board[x][y])
board[x][y].square=7
if x>5 and y>5:
squareArray[8].append(board[x][y])
board[x][y].square=8
def row_and_col_setter():
for z in range(9):
for x in range (9):
board[x][z].col = x
board[z][x].row = x
def display_board():
for y in reversed(range(9)):
if y == 2 or y == 5 or y ==8:
print("\n")
else:
print("")
for x in range(9):
if x == 2 or x == 5 or x==8:
print(board[x][y].contains, end=" ")
elif x == 0:
print(" ", end="")
print(board[x][y].contains, end="|")
else:
print(board[x][y].contains, end="|")
print("")
def set_easy_board():
board[3][0].contains = 1
board[6][0].contains = 8
board[2][1].contains = 6
board[7][1].contains = 2
board[8][1].contains = 4
board[0][2].contains = 4
board[2][2].contains = 8
board[3][2].contains = 6
board[5][2].contains = 3
board[7][2].contains = 7
board[8][2].contains = 1
board[2][3].contains = 3
board[3][3].contains = 4
board[4][3].contains = 2
board[5][3].contains = 6
board[8][3].contains = 8
board[3][4].contains = 9
board[5][4].contains = 8
board[0][5].contains = 8
board[3][5].contains = 5
board[4][5].contains = 1
board[5][5].contains = 7
board[6][5].contains = 6
board[0][6].contains = 6
board[1][6].contains = 3
board[3][6].contains = 8
board[5][6].contains = 5
board[6][6].contains = 7
board[8][6].contains = 2
board[0][7].contains = 2
board[1][7].contains = 9
board[6][7].contains = 4
board[2][8].contains = 7
board[5][8].contains = 4
numsall = [1,2,3,4,5,6,7,8,9]
counter=0
takennums = []
def solved_cells(dataneeds):
if (dataneeds != 0):
print("viable solutions for missing numbers generated.")
counter=0
for x in range(9):
for y in range(9):
for square in squareArray[board[x][y].square]:
takennums.append(square.contains)
for sweep in range(9):
if board[x][sweep].contains != '_':
takennums.append(board[x][sweep].contains)
if board[sweep][y].contains != '_':
takennums.append(board[sweep][y].contains)
for z in range(len(numsall)):
if numsall[z] not in takennums:
board[x][y].possible.append(numsall[z])
if (len(board[x][y].possible) == 1) and (board[x][y].contains == '_'):
counter+=1
board[x][y].contains = board[x][y].possible[0]
else:
if (dataneeds==0):
board[x][y].possible.clear()
takennums.clear()
if counter!=0:
solved_cells(0)
hidden_singles_array = []
def hidden_singles():
solved_cells(1)
z=0
for x in range(9):
for y in range(9):
hidden_singles_array.clear()
for square in squareArray[(board[x][y].square)]:
if (square.contains == '_'):
hidden_singles_array.extend(square.possible)
hidden_singles_array.sort()
for z in range((len(numsall))):
if (hidden_singles_array.count(numsall[z]) == 1):
for square in squareArray[(board[x][y].square)]:
if (numsall[z] in square.possible and square.contains == '_'):
square.contains = numsall[z]
solved_cells(0)
board = [[cell() for x in range(9)] for y in range(9)]
lazy_square_setter()
row_and_col_setter()
set_easy_board()
display_board()
solved_cells(0)
print("solved cells done")
hidden_singles()
print("hidden singles done")
display_board()
|
import itertools
import heapq
REMOVED = 'REMOVED'
counter = itertools.count()
class PriorityQueue():
def __init__(self):
self.pq = []
self.ef = {}
def push(self, priority, task):
if task in self.ef:
self.remove_task(task)
count = next(counter)
entry = [priority, count, task]
self.ef[task] = entry
heapq.heappush(self.pq, entry)
def remove_task(self, task):
entry = self.ef.pop(task)
entry[-1] = REMOVED
def pop(self):
while self.pq:
priority, count, task = heapq.heappop(self.pq)
if task is not REMOVED:
del self.ef[task]
return priority, task
def get_len(self):
return len(self.pq)
|
#!/usr/bin/python2.7
# author: Hayden Fuss
import csv
# source: https://docs.python.org/2/library/csv.html
# uses the csv.DictReader class to parse the data
# because the first line of the file explains each field in a csv
# format, DictReader immediately knows how to parse each line into
# a hash/dictionary with the keys matching the fields specified in
# the first line of the file
types = {}
with open('2010-14 Full CAD, Jan-Jun 2012.csv') as csvfile:
reports = csv.DictReader(csvfile)
for r in reports:
if not r['TYPE'] in types.keys():
types[r['TYPE']] = {}
types[r['TYPE']]['description'] = r['TYPE_DESC']
types[r['TYPE']]['count'] = 1
else:
types[r['TYPE']]['count'] = types[r['TYPE']]['count'] + 1
print "type,description,count"
for t in sorted(types):
print t + "," + types[t]['description'] + "," + str(types[t]['count'])
print "\n"
|
import sys
import tpg
class SemanticError(Exception):
"""
This is the class of the exception that
is raised when a semantic error occurs.
"""
def __init__(self, desc=None):
self.err_desc = desc
def __repr__(self):
if self.err_desc == None:
return "SEMANTIC ERROR"
else:
return "Error: " + self.err_desc
class ReturnValue(SemanticError):
"""
This is used by a function to return a value to its caller.
"""
def __init__(self, val):
self.val = val
self.err_desc = "Only a function can return a value."
class Node(object):
"""
A base class for nodes. Might come in handy in the future.
"""
def evaluate(self, context):
"""
Called on r-value children of Node to evaluate that child.
"""
raise Exception("Not implemented.")
def setval(self, val):
"""
Called on l-value children of Node to set value.
"""
raise Exception("Not implemented.")
class Value(Node):
"""
A node representing integer, string and array values.
"""
def __init__(self, value):
if isinstance(value, list):
self.value = value
elif str(value)[0]=='"':
self.value = value[1:len(value)-1]
else:
self.value = int(value)
def evaluate(self, context):
if isinstance(self.value, list):
rl = []
for k in self.value:
rl.append(k.evaluate(context))
return rl
else:
return self.value
class Assignment(Node):
"""
A node representing assignment statements.
"""
def __init__(self, left, right):
self.left = left
self.right = right
def evaluate(self, context):
self.left.setval(self.right.evaluate(context), context)
class Variable(Node):
"""
A node representing a variable in the r-value.
"""
def __init__(self, name):
self.name = name
def evaluate(self, context):
# Get the value of the variable
try:
return context[self.name]
except KeyError:
raise SemanticError(self.name + " not found.")
def setval(self, val, context):
context[self.name] = val
class ArrayIndex(Node):
"""
A node representing an array indexing operation.
"""
def __init__(self, left, right):
# The nodes representing the left and right sides of this MathOp.
self.left = left
self.right = right
def evaluate(self, context):
left = self.left.evaluate(context)
right = self.right.evaluate(context)
if isinstance(right, int):
if isinstance(left, list) or isinstance(left, str):
try:
return left[right]
except IndexError:
pass
raise SemanticError("Index out of bounds.")
def setval(self, val, context):
left = self.left.evaluate(context)
right = self.right.evaluate(context)
if isinstance(right, int):
if isinstance(left, list):
try:
left[right] = val
return
except IndexError:
pass
raise SemanticError("Index out of bounds.")
class MathOp(Node):
"""
A node representing a mathematical operation.
"""
def __init__(self, left, op, right):
# The nodes representing the left and right sides of this MathOp.
self.op = op
self.left = left
self.right = right
def evaluate(self, context):
left = self.left.evaluate(context)
right = self.right.evaluate(context)
if isinstance(left, int):
if isinstance(right, int):
if self.op == 'or': # Boolean OR.
return 1 if (left > 0 or right > 0) else 0
elif self.op == 'and': # Boolean AND.
return 1 if (left > 0 and right > 0) else 0
elif self.op == 'not': # Boolean NOT.
return 1 if left == 0 else 0
elif self.op == '<':
return 1 if left < right else 0
elif self.op == '==':
return 1 if left == right else 0
elif self.op == '>':
return 1 if left > right else 0
elif self.op == 'xor': # Bitwise XOR.
return left ^ right
elif self.op == '+':
return left + right
elif self.op == '-':
return left - right
elif self.op == '*':
return left * right
elif self.op == '/':
if right == 0:
raise SemanticError("Division by zero.")
return left / right
if((isinstance(left, str) and isinstance(right, str))
or (isinstance(left, int) and isinstance(right, str))
or (isinstance(left, str) and isinstance(right, int))):
left = str(left)
right = str(right)
if self.op == '+':
return left + right
raise SemanticError("Invalid MathOp.")
class Block(Node):
"""
A node representing a block.
"""
def __init__(self, stmts):
self.stmts = stmts
def evaluate(self, context):
for i in self.stmts:
i.evaluate(context)
class If(Node):
def __init__(self, expr, stmt):
self.expr = expr
self.stmt = stmt
def evaluate(self, context):
if self.expr.evaluate(context):
self.stmt.evaluate(context)
class While(Node):
def __init__(self, expr, stmt):
self.expr = expr
self.stmt = stmt
def evaluate(self, context):
while self.expr.evaluate(context):
self.stmt.evaluate(context)
class Print(Node):
def __init__(self, expr):
self.expr = expr
def evaluate(self, context):
print self.expr.evaluate(context)
class Return(Node):
def __init__(self, expr):
self.expr = expr
def evaluate(self, context):
raise ReturnValue(self.expr.evaluate(context))
class Function(Node):
def __init__(self, args, body):
self.args = args
self.body = body
class FunctionDefinition(Node):
def __init__(self, fvar, args, body):
self.fvar = fvar
self.func = Function(args, body)
def evaluate(self, context):
self.fvar.setval(self.func, context)
class FunctionCall(Node):
def __init__(self, fvar, args):
self.fvar = fvar
self.args = args
def evaluate(self, context):
func = self.fvar.evaluate(context)
if not isinstance(func, Function):
raise SemanticError(self.fvar.name + " is not a function.")
if len(self.args) != len(func.args):
raise SemanticError("Function argument count mismatch.")
context2 = dict(context)
for i in range(0, len(self.args)):
Assignment(func.args[i], self.args[i]).evaluate(context2)
try:
func.body.evaluate(context2)
except ReturnValue as ret:
return ret.val
class Comment(Node):
def __init__(self, text):
pass
def evaluate(self, context):
pass
# This is the TPG Parser that is responsible for turning our language into
# an abstract syntax tree.
class Parser(tpg.Parser):
"""
token value "(\d+)|(\\"([^\\"])*\\")" Value;
token variable '[A-Za-z][A-Za-z0-9]*' Variable;
separator space "\s+";
START/a -> statement/a ;
statement/a -> ( function_definition/a | block/a | if_stmt/a | while_stmt/a | line_stmt/a ) ;
function_definition/a -> variable/v arg_names/n block/b $ a = FunctionDefinition(v, n, b) $ ;
block/a -> '{' $ a = Block([]) $
( statement/b $ a.stmts.append(b) $ )*
'}' ;
line_stmt/a -> ( assignment/a | print_stmt/a | return_stmt/a | function_call/a ) ';' ;
if_stmt/a -> "if" "\(" expression/e "\)" statement/s $ a = If(e, s) $;
while_stmt/a -> "while" "\(" expression/e "\)" statement/s $ a = While(e, s) $;
assignment/a -> expression/a "=(?!=)" expression/b $ a = Assignment(a, b) $ ;
print_stmt/a -> 'print ' expression/a $ a = Print(a) $ ;
return_stmt/a -> 'return ' expression/a $ a = Return(a) $ ;
function_call/a -> variable/v arg_list/l $ a = FunctionCall(v, l) $ ;
expression/a -> boolOR/a ;
boolOR/a -> boolAND/a ( "or"/op boolAND/b $ a = MathOp(a, op, b) $ )* ;
boolAND/a -> boolNOT/a ( "and"/op boolNOT/b $ a = MathOp(a, op, b) $ )* ;
boolNOT/a -> comparison/a | "not"/op expression/b $ a = MathOp(b, op, b) $ ;
comparison/a -> xor/a ( ("<"/op | "=="/op | ">"/op) xor/b $ a = MathOp(a, op, b) $ )* ;
xor/a -> addsub/a ( "xor"/op addsub/b $ a = MathOp(a, op, b) $ )* ;
addsub/a -> muldiv/a ( ("\+"/op | "\-"/op) muldiv/b $ a = MathOp(a, op, b) $ )* ;
muldiv/a -> index/a ( ("\*"/op | "/"/op) index/b $ a = MathOp(a, op, b) $ )* ;
index/a -> parens/a ( "\[" expression/b "\]" $ a = ArrayIndex(a, b) $ )* ;
parens/a -> function_call/a | "\(" expression/a "\)" | literal/a ;
literal/a -> value/a | variable/a | array/a ;
array/a -> "\[" $ a = Value([]) $
expression/b $ a.value.append(b) $
( "," expression/b $ a.value.append(b) $ )*
"\]" ;
arg_names/a -> "\(" $ a = [] $
( variable/v $ a.append(v) $ )?
( "," variable/v $ a.append(v) $ )*
"\)" ;
arg_list/a -> "\(" $ a = [] $
( expression/e $ a.append(e) $ )?
( "," expression/e $ a.append(e) $ )*
"\)" ;
"""
# Make an instance of the parser. This acts like a function.
parse = Parser()
# This is the driver code, that reads in lines, deals with errors, and
# prints the output if no error occurs.
# Open the file containing the input.
f = file(sys.argv[1], "r")
code = f.read()
f.close()
code = "{" + code + "}"
# For each line in f,
#for l in f:
try:
# Try to parse the expression.
node = parse(code)
# Evaluate
node.evaluate({})
# If an exception is thrown, print the appropriate error.
except tpg.Error as e:
print "Syntax Error at line " + repr(e.line) + " column " + repr(e.column) + ": " + e.msg
# Uncomment the next line to re-raise the syntax error,
# displaying where it occurs. Comment it for submission.
# raise
except SemanticError as err:
print repr(err)
# Uncomment the next line to re-raise the semantic error,
# displaying where it occurs. Comment it for submission.
# raise
f.close()
|
import numpy as np
import scipy.special as sc
from .distribution import Distribution
from ..utils import check_array
class Uniform(Distribution):
""" Continous Uniform Distribution
The continuous uniform distribution or rectangular distribution is a family
of symmetric probability distributions such that for each member of the
family, all intervals of the same length on the distribution's support are
equally probable.
Arguments
---------
low : float, default=0.0
The inclusive lower bound of the uniform distribution.
high : float, default=1.0
The inclusive upper bounds of the uniform distribution.
seed : int, default=None
The seed to initialize the random number generator.
"""
def __init__(self, low=0.0, high=1.0, seed=None):
self.low = low
self.high = high
self.seed = seed
self.reset()
def reset(self, seed=None):
""" Reset random number generator """
if seed is None:
seed = self.seed
self._state = np.random.RandomState(seed)
def sample(self, *size, dtype=np.float):
""" Sample from distribution """
out = self._state.uniform(self.low, self.high, size=size).astype(dtype)
return check_array(out)
def probability(self, *X):
""" Return the probability density for a given value """
if not isinstance(X, np.ndarray):
X = np.squeeze(X).astype(float)
# Boolean conditions for inside (a) and outside (b) distribution range
a_bool = np.logical_and(X >= self.low, X <= self.high)
b_bool = np.logical_or(X < self.low, X > self.high)
# Distribution values by range
a_val = 1 / (self.high - self.low)
b_val = 0
# return probability
out = np.piecewise(X, [a_bool, b_bool], [a_val, b_val])
return check_array(out)
def log_probability(self, *X):
""" Return the log probability density for a given value """
if not isinstance(X, np.ndarray):
X = np.squeeze(X).astype(float)
# Boolean conditions for inside and outside distribution range
a_bool = np.logical_and(X >= self.low, X <= self.high)
b_bool = np.logical_or(X < self.low, X > self.high)
# Distribution values by range
a = -np.log(self.high - self.low)
b = np.nan
out = np.piecewise(X, [a_bool, b_bool], [a_val, b_val])
return check_array(out)
def cumulative(self, *X):
""" Return the cumulative density for a given value """
if not isinstance(X, np.ndarray):
X = np.squeeze(X).astype(float)
# Boolean conditions for below, inside, and above distribution range
a_bool = X < self.low
b_bool = np.logical_and(X >= self.low, X <= self.high)
c_bool = X > self.high
# values for distribution range
a_val = 0
def b_val(x): return (x - self.low) / (self.high - self.low)
c_val = 1
# return cumulative density
out = np.piecewise(X, [a_bool, b_bool, c_bool], [a_val, b_val, c_val])
return check_array(out)
def percentile(self, *X):
""" Return values for the given percentiles """
if not isinstance(X, np.ndarray):
X = np.squeeze(X).astype(float)
# Boolean conditions for outside and inside distribution range
a_bool = np.logical_or(X < 0, X > 1)
b_bool = np.logical_and(X >= 0, X <= 1)
# values for distribution range
a_val = np.nan
def b_val(x): return x * (self.high - self.low) + self.low
out = np.piecewise(X, [a_bool, b_bool], [a_val, b_val])
return check_array(out)
def survival(self, *X):
""" Return the likelihood of a value or greater """
if not isinstance(X, np.ndarray):
X = np.squeeze(X).astype(float)
return 1 - self.cumulative(X)
@property
def mean(self):
return 0.5 * (self.low + self.high)
@property
def median(self):
return 0.5 * (self.low + self.high)
@property
def mode(self):
return self.low, self.high
@property
def scale(self):
return (self.high - self.low) / 12 ** 0.5
@property
def variance(self):
return (self.high - self.low) ** 2 / 12
@property
def skewness(self):
return 0
@property
def kurtosis(self):
return -6 / 5
@property
def entropy(self):
return np.log(self.high - self.low)
@property
def perplexity(self):
return np.exp(self.entropy)
|
from sys import argv
script, input_file = argv
def print_all(f): ###a function reading the whole content of a file
print f.read()
def rewind(f): ## let the printer come back to the top of a file
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
## first, print the line number(actually the line_acount value)
## second, print the line that cursor located in a file
## third, the cursor position +1 line
current_file = open(input_file)
print "First let's print the whole file:\n"
print (current_file.tell())
print_all(current_file)
print (current_file.tell())
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
## note: the current_line just help the people watching the result to identify the line number, not the program.
## the program will decide which line should be printed by printer
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
print (current_file.tell())
print "use readlines()"
rewind(current_file)
print (current_file.readlines())
print (current_file.tell())
|
##this is a program to learn how does generator work
import math
def is_prime(number):
"""judge a number if it is a prime or not"""
if number > 1: ## the number should be > 1
if number == 2:
return True ## if the number == 2, return the True, and jump out the function
if number % 2 == 0:
return False ## if the number can be divided by 2, return a False and jump out the function
for current in range(3, int(math.sqrt(number)+1), 2):
if number % current == 0:
return False ## if the number can be devided by other numbers except 2, return a False and jump out the function
return True ## if the number(>1) isn't 2, can't be devided by 2 and other numbers, it means that it's a prime, return True and jump out the function
return False ## if the number <= 1, return a False
def get_primes(input_list):
result_list = list()
for element in input_list: ##draw out every element of input list.
if is_prime(element):
result_list.append() ## if the element is prime, add it into the result list. Or throw it away.
return result_list ## finally, return a long and clean list.
def get_primes_gen(number):
while True:
if is_prime(number):
yield number
number += 1
def solve_number_10():
total = 2
for next_prime in get_primes_gen(3):
if next_prime < 2000000:
total += next_prime
else:
print(total)
return
solve_number_10() |
print "Welcome to the world of blood. You have to answer some questions and the system tell you your blood type. It's interesting, isn't?"
raw_input("Press Enter to start >")
print "Are you ready?"
print "Yes: Press '1'."
print "Not yet: Press '2'."
print "I don't want to play such idiot game: Press '3'."
answer1 = raw_input ('>')
if answer1 == "3":
print "Aha!You AB boy!"
elif answer1 == "1":
print "Open your purse, and look at the cash you have. Are they neatly placed?"
print "Yes: Press '1'."
print "Absolutely no: Press '2'."
print "I want quit: Press '3'."
answer2 = raw_input('>')
if answer2 == "3":
print "It's ok. See you next time.(I bet you are AB type, aren't you?)"
elif answer2 == "2":
print "Are you always late?"
print "Always...: Press '1'."
print "No: Press '2'."
print "Err...I don't remember: Press '3'."
answer3 = raw_input('>')
if answer3 == "1":
print "You're absolutely B type."
elif answer3 == "2":
print "You look like a O type guy."
elif answer3 == "3":
print "You're totally O type."
else:
print "Hey! Why didn't you follow the rules? I suppose you are B type!"
elif answer1 == "1":
print "I know you, cute A type."
else:
print "Hey! Why didn't you follow the rules? I suppose you are B type!"
elif answer1 == "2":
print "It's ok. See you next time."
else:
print "Hey! Why didn't you follow the rules? I suppose you are B type!"
|
metros = float(input("Digite o valor em metros: "))
centimetros = metros * 100
print(f"O valor de {metros} metros equivale a {centimetros} centímetros") |
# Python: 2.7
# Merge sort algorithm
from time import time
from random import randint
class MergeSort(object):
def __init__(self, nlist, repeat=True):
self.list = nlist
self.repeat = repeat
def bubbleSort(self, nlist):
for a, alpha in enumerate(nlist):
for b, beta in enumerate(nlist):
if a>b and alpha<beta:
nlist[a], nlist[b] = nlist[b], nlist[a]
return nlist if self.repeat else self.removeRepeats(nlist)
def removeRepeats(self, nlist):
for a, alpha in enumerate(nlist):
for b, beta in enumerate(nlist):
if a != b and alpha == beta:
nlist.pop(a)
return nlist
@property
def sort(self):
started = time()
mid = len(self.list)/2
beta = self.bubbleSort(self.list[mid:])
alpha = self.bubbleSort(self.list[:mid])
return [self.bubbleSort(alpha + beta), time() - started]
if __name__ == '__main__':
lst = [randint(0, 20) for _ in xrange(20)]
n = MergeSort(lst, repeat=False).sort
print 'Input: {}\nOutput: {}\nTime: {}'.format(lst, n[0], n[1])
|
import sqlite3
class Client:
def __init__(self):
"""initialiseur de la classe client"""
self.nom = ""
self.prenom = ""
self.genre = ""
self.adresse = ""
self.tel = 0
self.mail = ""
def saisie_cli(self, data=[]):
"""Fonction de saisie et de recuperation des données du clients"""
self.nom = input("Nom: ")
self.prenom = input("Prenom: ")
self.genre = input("Genre: ")
self.adresse = input("Adresse: ")
self.tel = int(input("Telephone: "))
self.mail = input("E-mail: ")
data = [(self.nom, self.prenom, self.genre, self.adresse, self.tel, self.mail)]
return data
class ClientAssure(Client):
def __init__(self):
"""initialiseur de la classe clientassure"""
self.numpolice=""
self.nomassureur=""
self.datedebut=""
self.datefin=""
def saisie_clia(self,datac=[]):
"""Fonction de saisie et de recuperation des données du clients"""
self.numpolice=input("Numero police assurance: ")
self.nomassureur=input("Nom assurance: ")
self.datedebut=input("Date debut assurance: ")
self.datefin=input("Date fin assurance: ")
datac=[(self.numpolice, self.nomassureur, self.datedebut, self.datefin)]
return datac
class Manipulation:
"""Classe contenant les fonctions de manipulation des données du client"""
def ajout_client(self):
"""Fonction pour ajouter un nouveau client"""
c = Client()
data = []
donnees = c.saisie_cli(data)
print("Client assuré?")
print("1-oui 2-non")
rep = int(input("reponse: "))
if rep == 1:
ca = ClientAssure()
datac = []
donneesca = ca.saisie_clia(datac)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
for x in donnees:
cur.execute("""INSERT INTO client (nom,prenom,genre,adresse,tel,mail) VALUES(?,?,?,?,?,?)""", x)
for y in donneesca:
cur.execute("""INSERT INTO clientassure (numpolice,nomassureur,datedebut,datefin) VALUES(?,?,?,?)""",y )
cur.execute("""SELECT idclient FROM client,clientassure WHERE idclient=idclient_fk""")
conn.commit()
cur.close()
conn.close()
elif rep == 2:
print("Client bien enregistré")
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
for x in donnees:
cur.execute("""INSERT INTO client (nom,prenom,genre,adresse,tel,mail) VALUES(?,?,?,?,?,?)""", x)
conn.commit()
cur.close()
conn.close()
def modifier_client(self):
"""Fonction pour modifier les données d'un client"""
idclient = input("Veuillez preciser l'identifiant du client à modifier: ")
reps = input("Client assuré? ")
if reps == "oui":
print("Que voulez vous modifier?\n ", "1-Nom\n", "2-Prenom\n", "3-Genre\n", "4-Adresse\n", "5-Telephone\n",
"6-Mail\n", "7-Numero de police\n", "8-Nom assureur\n", "9-Date debut\n", "10-Date fin")
modif = int(input("Tapez votre choix: "))
if modif == 1:
nom = input("Nom:")
t = (nom, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET nom=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 2:
prenom = input("Prenom:")
t = (prenom, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET prenom=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 3:
genre = input("Genre:")
t = (genre, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET genre=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 4:
adresse = input("Adresse:")
t = (adresse, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET adresse=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 5:
tel = input("Telephone:")
t = (tel, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET tel=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 6:
mail = input("E-mail:")
t = (mail, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET mail=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 7:
numpolice = input("Numero police:")
t = (numpolice, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE clientassure SET numpolice=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 8:
nomassureur = input("Nom assureur:")
t = (nomassureur, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE clientassure SET nomassureur=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 9:
datedebut = input("Date debut:")
t = (datedebut, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE clientassure SET datedebut=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 10:
datefin = input("Date fin:")
t = (datefin, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE clientassure SET datefin=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
if reps=="non":
print("Que voulez vous modifier?\n ", "1-Nom\n", "2-Prenom\n", "3-Genre\n", "4-Adresse\n", "5-Telephone\n","6-Mail\n")
modif = int(input("Tapez votre choix: "))
if modif == 1:
nom = input("Nom:")
t = (nom, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET nom=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 2:
prenom = input("Prenom:")
t = (prenom, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET prenom=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 3:
genre = input("Genre:")
t = (genre, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET genre=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 4:
adresse = input("Adresse:")
t = (adresse, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET adresse=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 5:
tel = input("Telephone:")
t = (tel, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET tel=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
elif modif == 6:
mail = input("E-mail:")
t = (mail, idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""UPDATE client SET mail=? WHERE idclient=?""", t)
conn.commit()
cur.close()
conn.close()
def recherche_client(self):
"""Fonction pour chercher un client dans la base de données"""
print("Veuillez preciser l'identifiant du client à rechercher: ")
idclient = input("Identifiant: ")
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
x = (idclient)
cur.execute("""SELECT * from client WHERE idclient=?""", x)
a = list(cur)
conn.commit()
cur.close()
conn.close()
print(a)
def supprimer_client(self):
"""Fonction pour la suppression d'un client dans la base de données"""
idclient = input("Veuillez preciser l'identifiant du client à supprimer: ")
x = (idclient)
conn = sqlite3.connect("pharmaciebd.db")
cur = conn.cursor()
cur.execute("""DELETE FROM client WHERE idclient=?""", x)
conn.commit()
cur.close()
conn.close()
|
# Percabangan / Pengkondisian
# if statment
umur_budi = 20
umur_andi = 25
if umur_budi < umur_andi:
print("Lebih tua Andi ")
# a = 12
# b = 12
#
# if a > b :
# print('Variabel a lebih besar dari variabel b')
# if a < b :
# print('Variabel a lebih kecil dari variabel b')
# if a == b :
# print('Variabel a sama dengan variabel b')
i = 8
if (i % 2) == 0:
print('Hasilnya Genap')
if(i% 2 ) == 1:
print('HAsilnya Ganjil')
# if else statment
if (i % 2) == 1:
print('Hasilnya Adalah Ganjil')
else:
print('HAsilnya Genap')
nilai = 65
if nilai > 70:
print("Selamat Anda Lulus")
else :
print('Anda Tidak Lulus')
j = 200
k = 33
if k > j :
print('K lebih besar dari j')
elif j == k :
print('J sama dengan K')
else:
print('J lebih besar dari K')
# if else diletakkan sebelum output/ ditengah
nilai_a = 15
nilai_b = 20
print("A") if nilai_a < nilai_b else print("B")
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
a = 200
b = 30
c = 500
if a > b and c > a:
print('Kondisi ini terpenuhi')
if a > b or a > c:
print("At least one of the conditions is True")
nilai = 'D'
if nilai == 'A':
print('Pertahankan')
elif nilai == 'B':
print('Harus Lebih Baik Lagi')
elif nilai == 'C':
print('Perbanyak Belajar Lagi')
elif nilai == 'D':
print('Jangan Keseringan Main Game')
elif nilai == 'E':
print('Kebanyakan Bolos...')
else:
print('Maaf, format tidak sesuai')
nilai = 20
print('Nilai', nilai)
if nilai >= 90:
print('Pertahankan')
elif (nilai >= 80) and (nilai < 90):
print('Harus lebih baik lagi')
elif (nilai >= 60) and (nilai < 80):
print('Perbanyak belajar')
elif (nilai >= 40) and (nilai < 60):
print('Jangan keseringan main')
elif nilai < 40:
print('Kebanyakan bolos...')
else:
print('Maaf, format nilai tidak sesuai') |
velocidade = float(input('Digite a velocidade do veículo: '))
if velocidade > 80:
multa = (velocidade - 80) * 7
print('Você foi multado. A multa vai custar R${:.2f}'.format(multa))
else:
print('Não foi multado.') |
n1 = int(input())
n2 = int(input())
n3 = int(input())
if n1 > n2 and n1 > n3:
print('{} é o maior número'.format(n1))
else:
if n2 > n1 and n2 > n3:
print('{} é o maior número'.format(n2))
else:
if n3 > n1 and n3 > n2:
print('{} é o maior número'.format(n3))
|
print('Crescente')
for c in range(1, 11): # (a, b, c) a: inicio, b: fim, c: decremento/incremento
print(c)
print('\nDecrescente')
for c in range(10, 0, -1):
print(c)
n = int(input('Digite um número: '))
for c in range(0, n, 2):
print(c)
|
#练习
car = input("hello, what kind of car do you want? ")
print("let me see if i can find you a "+car)
people = input("how many people will come here for dinner? ")
people = int(people)
if people > 8:
print("sorry, there is no table left!")
else:
print("we have extra tables for you!")
numbers = input("enter a number and i will tell you whether it can be divided by 10: ")
numbers = int(numbers)
if numbers % 10 == 0:
print("it can be divided by 10")
else:
print("it can't be divided by 10")
#练习
prompt = ("please write down the ingredient you want to add into the pizza: ")
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print('we will add this for you!')
prompt = ("how old are you: ")
while True:
message = input(prompt)
if message == 'quit':
break
elif int(message) < 3:
print("your price ticket is 0")
elif int(message) >= 3 and int(message) < 12:
print("your price ticket is 10")
else:
print("your price ticket is 15")
responses = {}
polling_active = True
while polling_active:
name = input("\nwhat is your name? ")
response = input("which mountain would you like to climb? ")
responses[name] = response
repeat = input("would you let another person to answer this question? ")
if repeat == 'no':
polling_active = False
print("---polling results---")
for name,response in responses.items():
print(name + " would like to climb "+ response)
|
#1
# low = 1
# high = 100
# loop = True
# while loop:
# mid = (low + high) //2
# answer = input("số {} có phải không".format(mid))
# if answer == "c":
# print("đáp án là {}".format(mid))
# elif answer == "l":
# low = mid
# elif answer == "s":
# high = mid
#2
# m = input("A number")
# for i in range(1, int(m)+1):
# if i % 2 == 0:
# print(i)
#3
# number = int(input("A number"))
# number -= number % 2
# for i in range(int(number), 0, -2):
# print(i)
#4
# number = int(input("A number"))
# count = 0
# if number == 1:
# print("Đây không là số nguyên tố")
# else:
# for i in range (2, number):
# if number % i != 0:
# count +=1
# if count == 0:
# print("Đây là số nguyên tố")
# elif count != 0:
# print("Đây không là số nguyên tố ")
#5
loop = True
number = 10
while loop:
x = input ('Insert a number: ')
try:
n=int(x)
i = 10/n
print('no prob')
print('result:', i)
loop = False
except ValueError:
print('khong phai so')
except ZeroDivisionError:
print('khong the chia')
|
import Battleship_Functions
from time import sleep
# print_board(board) : prints board with player label
# print_opponent(board) : prints board with opponent label
# print_gamespace(player,opponent) : prints both player's and opponent's boards
# place_ship(board,ship) : takes user input to place ship
# place_ship_random(board,ship) : places defined ship arbitrarily
# define_board(board) : display for user ship placement step
# get_player_guess(board,board_forprinting,hits,locations) : gets player's next guess
# get_computer_guess(player_board,hit_number,locations,hit_locations) : get's computer's next guess
# greeting
print()
print(" ------------")
print(" BATTLESHIP")
print(" ------------")
# create opponent board
# board showing all ship locations
opponent = []
for x in range(0, 10):
opponent.append(["O"] * 10)
opponent_locations = {}
Battleship_Functions.place_ship_random(opponent,"aircraft carrier",opponent_locations)
Battleship_Functions.place_ship_random(opponent,"battleship",opponent_locations)
Battleship_Functions.place_ship_random(opponent,"cruiser",opponent_locations)
Battleship_Functions.place_ship_random(opponent,"submarine",opponent_locations)
Battleship_Functions.place_ship_random(opponent,"destroyer",opponent_locations)
# viewable opponent board (doesn't give away opponent positions)
opponent_forprinting = []
for x in range(0, 10):
opponent_forprinting.append(["O"] * 10)
#Battleship_Functions.print_opponent(opponent) #remove after debugging
# create player board
board = []
for x in range(0, 10):
board.append(["O"] * 10)
ship_locations = {}
print()
print("PLACE SHIPS:")
print(" ships: aircraft carrier (*****) battleship (****)")
print(" cruiser (***) submarine (***) destroyer (**)")
print()
print("Do you want to place ships yourself or have them assigned randomly?")
board_design = 'none'
while board_design == 'none':
board_design = input(" Type self or random: ")
if board_design == 'self':
Battleship_Functions.define_board(board,ship_locations)
elif board_design == 'random':
Battleship_Functions.place_ship_random(board,"aircraft carrier",ship_locations)
Battleship_Functions.place_ship_random(board,"battleship",ship_locations)
Battleship_Functions.place_ship_random(board,"cruiser",ship_locations)
Battleship_Functions.place_ship_random(board,"submarine",ship_locations)
Battleship_Functions.place_ship_random(board,"destroyer",ship_locations)
else:
board_design = 'none'
# print game board
Battleship_Functions.print_gamespace(board,opponent_forprinting)
# hit counter
opponent_hits = {"aircraft carrier": 0,
"battleship": 0,
"cruiser": 0,
"submarine": 0,
"destroyer": 0
}
opponent_aircraftcarrier_hits = opponent_hits["aircraft carrier"]
opponent_battleship_hits = opponent_hits["battleship"]
opponent_cruiser_hits = opponent_hits["cruiser"]
opponent_submarine_hits = opponent_hits["submarine"]
opponent_destroyer_hits = opponent_hits["destroyer"]
player_hits = {"aircraft carrier": 0,
"battleship": 0,
"cruiser": 0,
"submarine": 0,
"destroyer": 0
}
player_aircraftcarrier_hits = player_hits["aircraft carrier"]
player_battleship_hits = player_hits["battleship"]
player_cruiser_hits = player_hits["cruiser"]
player_submarine_hits = player_hits["submarine"]
player_destroyer_hits = player_hits["destroyer"]
# hit locations on player board (used by computer opponent)
player_hit_locations = {"aircraft carrier": [],
"battleship": [],
"cruiser": [],
"submarine": [],
"destroyer": []
}
# game
sleep(3)
print()
print("PLAY GAME:")
winner = 'none'
alpha_coords = ["A","B","C","D","E","F","G","H","I","J"]
numbr_coords = ["1","2","3","4","5","6","7","8","9","10"]
while winner == 'none':
print()
print("YOUR TURN")
Battleship_Functions.get_player_guess(opponent,opponent_forprinting,\
opponent_hits,\
opponent_locations)
Battleship_Functions.print_gamespace(board,opponent_forprinting)
if opponent_hits['aircraft carrier'] == 5 and \
opponent_hits['battleship'] == 4 and \
opponent_hits['cruiser'] == 3 and \
opponent_hits['submarine'] == 3 and \
opponent_hits['destroyer'] == 2:
winner = 'player'
print("Congratulations! You won!")
sleep(60)
else:
sleep(3)
print()
print("COMPUTER'S TURN")
sleep(2)
Battleship_Functions.get_computer_guess(board,player_hits,\
ship_locations,\
player_hit_locations)
Battleship_Functions.print_gamespace(board,opponent_forprinting)
if player_hits['aircraft carrier'] == 5 and \
player_hits['battleship'] == 4 and \
player_hits['cruiser'] == 3 and \
player_hits['submarine'] == 3 and \
player_hits['destroyer'] == 2:
winner = 'computer'
print("Sorry, you lost. Better luck next time!")
sleep(60)
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def printName(self):
print("The person's name is " + self.name)
class Student(Person):
def __init(self, name, age, school):
# or you can use the super().__init__ function to, its means the same thing
Person.__init__(self, name, age)
self.school = school
p1 = Person("Zsolt", 19)
p1.printName()
del p1
|
def insertionSort(array):
itI = 1
while itI < len(array):
itJ = 0
while itJ <= itI - 1:
if array[itJ] > array[itI]:
array.insert(itJ, array[itI])
array.pop(itI + 1)
break
itJ += 1
itI += 1
return array
array = [12, 11, 13, 5, 6]
print(insertionSort(array))
|
def title_case(string):
i = 0
length = len(string)
workingString = list(string)
while i < length:
ch = ord(string[i])
if 65 <= ch <= 90:
if workingString[i - 1] != " " and i != 0:
workingString[i] = chr(ch + 32)
elif 97 <= ch <= 122 and i != 0:
if string[i - 1] == " ":
workingString[i] = chr(ch - 32)
i += 1
return ''.join(workingString)
string = "I'm a little tea pot"
print(title_case(string)) |
"""
Gillian Bryson
"""
#Imports
import re
import operator
import sys
args=sys.argv
lines=[]#will hold lines from file
for line in sys.stdin:
lines.append(line)
tbl_cnt=1;#if there are no tables this will never be used so we can assume ther will be at least 1 table
print_lines=[]#list of list of words to print
print_words=[]#list of words to print
print_me=False
for line in lines:
if '<table' in line.lower():
#print('found table')
print_lines.append(['TABLE %d:'%tbl_cnt])
tbl_cnt+=1
if '<tr' in line.lower():
print_me=True
if print_me:
split_line=re.split('(<t[^>]*>)|(</t[^>]*>)|(<T[^>]*>)|(</T[^>]*>)',line.strip())
# list(filter(lambda a: a != None, split_line))
while None in split_line:
split_line.remove(None)
spLnLen=len(split_line)
# print('pre: ',end="")
#print(split_line)
#print(spLnLen)
a=0
while a< spLnLen-1:
#print(a)
#print(a,end=" ")
#print(spLnLen)
#print(split_line[a])
#print(split_line[a])
if (split_line[a].strip()=='')and(a==0):
split_line.pop(a)
spLnLen=len(split_line)
a=0
continue
#print('\nbefore: '+split_line[a-1]+" middle: "+split_line[a]+" after: "+split_line[a+1]+"\n")
if (split_line[a].strip()=='') and (not('<t' in split_line[a-1]) or not('</t' in split_line[a+1]) ):
#print('popping: '+split_line[a]+" at %d"%a)
split_line.pop(a)
spLnLen=len(split_line)
a=0
continue
a+=1
if (split_line[len(split_line)-1]==''):# and ('</t' in split_line[len(split_line)-2])
split_line.pop(len(split_line)-1)
#a=-1
#print('post: ',end="")
#print(split_line)
for word in split_line:
#print(word)
word=word.strip()
if not(('<t' in word.lower()) or('</t' in word.lower())):
print_words.append(' '.join(word.strip().split()))
elif ('</tr' in word.lower()):
# print('appending')
# print(print_words)
print_lines.append(print_words)
print_words=[]
print_me=False
# while [''] in print_lines:
# print_lines.remove([''])
#print(print_words)
lnLen=len(print_lines[1])
reNum=False
for print_words in print_lines:
#print(print_words)
myLen=len(print_words)
if myLen<=0:
continue
if (myLen==1)and(print_words[0]==""):
# print()
continue
if reNum:
lnLen=len(print_words)
reNum=False
if 'TABLE' in print_words[0]:
if '1:' in print_words[0]:
print(print_words[0])
else:
print()
print(print_words[0])
continue
#print(myLen)
for place in range(0,lnLen):
#print('place %d'%place)
if (place>=myLen):
if(place==lnLen-1):
print("")
else:
print(',',end="")
elif place == lnLen-1:
#print('end found')
print(print_words[place])
else:
print(print_words[place]+",",end="")
|
class time(object):
hour=0
minute=0
second=0
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def print_time(self):
print('Hour -> %d \n Minute -> %d \n Second -> %d'%(self.hour,self.minute,self.second))
a=time(2)
a.print_time()
|
"Write a function called distance_between_points that takes two Points as arguments and returns the distance between them."
import math
class points:
x=0
y=0
def distance(p1,p2):
dx=p2.x-p1.x
dy=p2.y-p1.y
distance=math.sqrt(dx**2-dy**2)
return(distance)
def main():
p1=points()
p1.x=0
p1.y=0
p2=points()
p2.x=10
p2.x=10
print(distance(p1,p2))
if __name__=='__main__':
main()
|
# Hi! Welcome to the Monkey Music Challenge Python starter kit!
import sys
import os
import urllib
# You control your monkey by sending POST requests to the Monkey Music server
GAME_URL = 'http://competition.monkeymusicchallenge.com/game';
# Don't forget to provide the right command line arguments
if len(sys.argv) < 4:
print('Usage: python index.py <your-team-name> <your-api-key> <game-id>\n')
if len(sys.argv) < 1:
print(' Missing argument: <your-team-name>')
if len(sys.argv) < 2:
print(' Missing argument: <your-api-key>')
if len(sys.argv) < 3:
print(' Missing argument: <game-id>')
sys.exit(1)
# You identify yourselves by your team name
team_name = sys.argv[1]
api_key = sys.argv[2]
game_id = sys.argv[3]
team_name = "Vicious'N'Delicious"
api_key = '6QtuGKaZLYMALOL4/Ny6z5NsK54='
# We've put the AI-code in a separate module
import ai
def post_to_server(command):
'''We use the requests library to POST JSON commands to the server.'''
import json
import requests
command['team'] = team_name
command['apiKey'] = api_key
command['gameId'] = game_id
print(command)
print(json.dumps(command))
# Every time we POST a command to the server, we get a reply back
reply = requests.post(GAME_URL,
data=json.dumps(command),
headers={'Content-Type': 'application/json'})
# Hopefully, our server will always be able to handle your requests
# but you never know...
if reply.status_code != requests.codes.ok:
print(' The server replied with status code %d' % reply.status_code)
try:
print(' %s' % reply.json()['message'])
except:
pass
sys.exit(1)
# The server replies with the current state of the game
current_game_state = reply.json()
return current_game_state
# Allright, time to get started!
# Send a join game command and the server replies with the initial game state
current_game_state = post_to_server({'command': 'join game'})
# The current game state tells you if you have any turns left
while not current_game_state['isGameOver']:
print '##########################'
print('Remaining turns: %d' % current_game_state['remainingTurns'])
import datetime
beforeProcessing = datetime.datetime.now()
# Use your AI to decide in which direction to move...
next_command = ai.move(current_game_state)
afterProcessing = datetime.datetime.now()
delta = afterProcessing - beforeProcessing
print "Took " + str(delta.seconds) + "." + str(delta.microseconds) + " seconds to process"
print 'next_command: ' + str(next_command)
# After sending your next move, you'll get the new game state back
current_game_state = post_to_server(next_command)
print('\nGame over.\n')
|
#Link para Chromedriver: https://chromedriver.storage.googleapis.com/index.html?path=90.0.4430.24/
#Importar Selenium para aplicaciones basadas en la web para webscraping
from selenium import webdriver
from selenium.webdriver.common import service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import time
import pandas as pd
#Ruta para el controlador de chrome
path = r'D:\Descargas\chromedriver_win32\chromedriver.exe'
#Cargar el controlador en python
driver = webdriver.Chrome(executable_path = path)
#Establecer la pagina de objetivo
driver.get('https://www.instagram.com/')
#Guardar los objetos html por medio de selectores css
username = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='username']")))
password = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='password']")))
#Limpiar y asignar los valores de los inputs seleccionados, para entrar a la cuenta de usuario
username.clear()
username.send_keys("user")
password.clear()
password.send_keys("password")
#Dar click a enviar formulario para entrar al perfil
button = WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()
username = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='username']")))
#Second Page
#Asignar la palabra clave
keyword = "#ivanduque"
#Seleccionar el campo de busqueda de instagram
searchbox = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.XTCLo")))
#Limpiar el campo de busqueda
searchbox.clear()
#asignar la palabra clave al campo de texto de busqueda
searchbox.send_keys(keyword)
# Esperar 4 segundos para que cargue los resultados de la busqueda del hashtag de duque
time.sleep(4)
#Seleccionar el resultado del hashtag y ir hacia el resultado
my_link = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href,'/"+keyword[1:]+"/')]")))
my_link.click()
#Third Page
#Moverse hacia abajo de la pagina para cargar mas resultados y repetir el proceso n_scroll veces
n_scrolls = 20
for j in range(0, n_scrolls):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3)
#Obtener todos los tag "a" de la pagina y por medio de una consulta...
#Javascript seleccionar el href(link) de todos ellos
anchors = driver.execute_script("return [...document.querySelectorAll('a')].map(a=> a.href)")
#Obtener todos los links que hagan referencia a publicaciones
anchors = [a for a in anchors if a.startswith("https://www.instagram.com/p/")]
#anchors= anchors[0:15] #Obtener cantidad limitida de elementos
Data = {'username':[], 'comment':[],'date':[], }
print(len(anchors))
hashIndex = 0;
#para todos los links, obtener los datos de ellos y empezar a llenar la tabla
for page in anchors:
#Cargar la pagina
driver.get(page)
#esperar 1 segundo que cargue
time.sleep(1)
#Obtener usuario, comentario, fecha y añadirlos a la tabla por medio de
#script javascript, por consultas de clases de html.
#C4VMK: Clase que almacena los datos de la publicacion del usuario
#_1o9PC: Clase de html donde se encuentra la fecha
username = driver.execute_script("return document.querySelector('.C4VMK').querySelector('span').innerText");
comment = driver.execute_script("return document.querySelector('.C4VMK>span').textContent");
date = driver.execute_script("return document.querySelector('._1o9PC').innerText");
#Añadir a cada clave del diccionario
Data['username'].append(username)
Data['comment'].append(comment)
Data['date'].append(date)
#Pasar el diccionario a un dataframe
Dataframe = pd.DataFrame.from_dict(Data)
print(Dataframe)
#Exportar dataframe a xlsx
Dataframe.to_csv('export_dataframe2.csv', encoding='utf-16')
|
'''
Given an index k, return the kth row of the Pascal’s triangle.
Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
Example:
Input : k = 3
Return : [1,3,3,1]
NOTE : k is 0 based. k = 0, corresponds to the row [1].
'''
class Solution:
# @param A : integer
# @return a list of list of integers
def getRow(self, A):
pascal = [[1 for i in range(j+1)] for j in range(A+1)]
if(A > 2):
for i in range(2, A+1):
for j in range(1, i):
pascal[i][j] = pascal[i-1][j-1]+pascal[i-1][j]
print(pascal)
return pascal[A]
|
'''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P.......A........H.......N
..A..P....L....S....I...I....G
....Y.........I........R
And then read line by line: PAHNAPLSIIGYIR
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"
**Example 2 : **
ABCD, 2 can be written as
A....C
...B....D
and hence the answer would be ACBD.
'''
class Solution:
def convert(self, A, B):
if(B == 1):
return A
n = len(A)
elements = 2*(B-1)
times = n//elements+1
i = 0
lists = [[] for x in range(B)]
position = 0
while(i < times):
j = 0
while(j < elements):
index = j if(j <= B-1) else elements-j
if(position < n):
lists[index].append(A[position])
else:
lists[index].append('')
position += 1
j += 1
i += 1
s = ''
for j in lists:
s += "".join(j)
return s
print(Solution().convert('THISISASTRING', 4))
|
#This file will handle a lot of the data process for the fact page.
#Bringing in the outside libraries for use in this pageimport csv
from csv import writer
import numpy as np
import pandas as pd
class Data():
def __init__(self):
self.data = pd.read_csv('./data/who_suicide_statistics.csv')
#This method will get the suicides by year for each country
def suicides_by_country(self, country):
#Getting the data set to match a specific country.
self.data = self.data[self.data.country == country]
#Getting the total number of suicides
Total = self.data['suicides_no'].sum()
#returning the total
return Total
#This method will get the suicides by country and by year
def suicides_by_country_year(self, country, year):
self.data = self.data[(self.data.country == country) & (self.data.year == year)]
Total = self.data['suicides_no'].sum()
return Total
#This method will get the suicides for country and by sex
def suicides_by_country_sex(self, country, sex):
self.data = self.data[(self.data.country == country) & (self.data.sex == sex)]
Total = self.data['suicides_no'].sum()
return Total
#This method will get the suicides for country, sex and year
def suicides_by_country_sex_year(self, country, sex, year):
self.data = self.data[(self.data.country == country) & (self.data.sex == sex) & (self.data.year == year)]
Total = self.data['suicides_no'].sum()
return Total
#This method will get number of suicides by age groups.
def suicides_by_age_group(self):
age_groups = ['5-14 years', '15-24 years', '25-34 years', '35-54 years', '55-74 years', '75+ years']
Total_suicides = []
for age in age_groups:
#I have to set the data frame equal to another data frame or else it will hold only the first
#age group in the data set.
df = self.data
df = df[(df.age == age) & (df.country == 'United States of America')]
Total = df['suicides_no'].sum()
Total_suicides.append(Total)
return Total_suicides
#This method will get number of suicides by age groups and male sex.
def suicides_by_age_group_male(self):
age_groups = ['5-14 years', '15-24 years', '25-34 years', '35-54 years', '55-74 years', '75+ years']
Total_suicides = []
for age in age_groups:
#I have to set the data frame equal to another data frame or else it will hold only the first
#age group in the data set.
df = self.data
df = df[(df.age == age) & (df.country == 'United States of America') & (df.sex == 'male')]
Total = df['suicides_no'].sum()
Total_suicides.append(Total)
return Total_suicides
#This method will get number of suicides by age groups and female sex.
def suicides_by_age_group_female(self):
age_groups = ['5-14 years', '15-24 years', '25-34 years', '35-54 years', '55-74 years', '75+ years']
Total_suicides = []
for age in age_groups:
#I have to set the data frame equal to another data frame or else it will hold only the first
#age group in the data set.
df = self.data
df = df[(df.age == age) & (df.country == 'United States of America') & (df.sex == 'female')]
Total = df['suicides_no'].sum()
Total_suicides.append(Total)
return Total_suicides
# play = Data()
# play.suicides_by_age_group_male()
|
#!/usr/bin/env python3
"""
Georgia Institute of Technology - CS1301
HW06 - Try/Except and Dictionaries
"""
__author__ = """Damian Huerta"""
__collab__ = """I worked on this homework alone"""
"""
Function name: number_letter_sort
Parameters: string
Returns: tuple
"""
def number_letter_sort(astr):
digits = ""
letters= ""
for thing in astr:
try:
a = int(thing)
digits += str(thing)
except:
letters += thing
return (digits, letters)
"""
Function name: add_divide
Parameters: list of ints, int
Returns: float
"""
def add_divide(alist, integer):
total = 0
for g,w in enumerate(alist):
if g%integer == 0:
try:
total = total/w
except:
total += 1
else:
total += w
return round(total,2)
"""
Function name: trip_planner
Parameters: list of tuples
Returns: dictionary with each value as a dictionary
"""
def trip_planner(alist):
dictionary = {}
used = []
for thing in alist:
dictionary[thing[0]] = {}
for thing in alist:
if thing[1] not in used:
dictionary[thing[0]][thing[1]] = thing[2]
used.append(thing[1])
else:
dictionary[thing[0]][thing[1]] += thing[2]
return dictionary
"""
Function name: average_rating
Parameters: dictionary containing NYC neighborhoods as keys and their values
being a nested dictionary whose keys are tourist locations and values are a
list of integer ratings
Returns: dictionary
"""
def average_rating(dictionary):
average = 0
for g,w in dictionary.items():
for d,h in w.items():
average = sum(h)/len(h)
dictionary[g][d] = round(average,2)
return dictionary
"""
Function name: get_restaurants
Parameters: a dictionary containing restaurants as keys and their values being
a list of the items that they serve
Returns: a dictionary containing the items as keys and their values being a
list
"""
def get_restaurants(dictionary):
new = {}
used = []
for g,w in dictionary.items():
for other in w:
if other not in used:
new[other] = []
used.append(other)
for thing in used:
for g,w in dictionary.items():
if thing in dictionary[g]:
new[thing].append(g)
return new
"""
Function name: catch_flight
Parameters: dictionary, tuple containing two strings
Returns: dictionary
"""
def catch_flight(dictionary,tup):
new = {}
for g,w in dictionary.items():
new[g] = 0
for g,w in dictionary.items():
for d,h in enumerate(w):
if float(dictionary[g][d][1:]) >= float(tup[0][1:]) and float(dictionary[g][d][1:]) <= float(tup[1][1:]):
new[g] += 1
return new
|
#!/usr/bin/env python3
"""
Georgia Institute of Technology - CS1301
HW09 - Recursion
"""
__author__ = """Damian Huerta-Ortega"""
__collab__ = """I worked on this alone"""
"""
Function name: shows_r
Parameters: lists of tuples
Returns: int
"""
def shows_r(mylist):
if len(mylist) == 0:
return 0
else:
if mylist[0][0] * mylist[0][1] <= 22:
count = 1 + shows_r(mylist[1:])
return count
else:
count = shows_r(mylist[1:])
return count
"""
Function name: shows_i
Parameters: lists of tuples
Returns: int
"""
def shows_i(mylist):
count = 0
for thing in mylist:
if thing[0]*thing[1] <= 22:
count += 1
else:
continue
return count
"""
Function name: wheres_waldo_r
Parameters: string
Returns: int
"""
def wheres_waldo_r(mystring):
if "waldo" in mystring:
if len(mystring) <5:
return -1
elif mystring[0:5] == "waldo":
return 0
else:
return 1 + wheres_waldo_r(mystring[1:])
else:
return -1
"""
Function name: wheres_waldo_i
Parameters: string
Returns: int
"""
def wheres_waldo_i(mystring):
count = -1
for g,letter in enumerate(mystring):
if mystring[g] == "w" and len(mystring) >= 5 and mystring[g:g+5] == "waldo":
count = g
return g
else:
continue
return count
"""
Function name: count_patterns_r
Parameters: string with at least 3 characters
Returns: int
"""
def count_patterns_r(mystr):
if len(mystr) < 3:
return 0
else:
count = count_patterns_r(mystr[1:])
pat = mystr[0:3]
if pat[0] == pat[2] and pat[0] != pat[1]:
count += 1
return count
"""
Function name: count_patterns_i
Parameters: string with at least 3 characters
Returns: int
"""
def count_patterns_i(mystr):
count = 0
for g,w in enumerate(mystr):
if g > 0 and g <= len(mystr)-2 and mystr[g-1] == mystr[g+1] and mystr[g]!=mystr[g+1]:
count+=1
return count
"""
Function name: string_stats_r
Parameters: string
Returns: dictionary
"""
def string_stats_r(mystr):
if len(mystr) == 0:
return {"uppercase": 0, "lowercase": 0, "numbers": 0, "spaces": 0, "other":0}
else:
letter = mystr[0]
if letter.isupper():
mydict = string_stats_r(mystr[1:])
mydict["uppercase"]+=1
return mydict
elif letter.islower():
mydict = string_stats_r(mystr[1:])
mydict["lowercase"] +=1
return mydict
elif letter.isdigit():
mydict = string_stats_r(mystr[1:])
mydict["numbers"]+=1
return mydict
elif letter == " ":
mydict = string_stats_r(mystr[1:])
mydict["spaces"] += 1
return mydict
else:
mydict = string_stats_r(mystr[1:])
mydict["other"] += 1
return mydict
"""
Function name: string_stats_i
Parameters: string
Returns: dictionary
"""
def string_stats_i(mystr):
mydict = {"uppercase": 0, "lowercase": 0, "numbers": 0, "spaces": 0, "other":0}
for letter in mystr:
if letter.isupper():
mydict["uppercase"]+=1
elif letter.islower():
mydict["lowercase"] +=1
elif letter.isdigit():
mydict["numbers"]+=1
elif letter == " ":
mydict["spaces"] += 1
else:
mydict["other"] += 1
return mydict
#print(string_stats_i( "sPoNgE BoB iS mY #1 fAn!"))
|
import random
n = random.randint(1, 100)
count = 1
chances = 10
while 1 <= chances:
num = int(input('Guess the number:'))
if num > n:
print ('Lower')
elif num < n:
print ('Higher')
else:
print ('You win')
print (count, 'Chances you took')
break
count += 1
|
# -*- coding: utf-8 -*-
"""
@author: Brock
Python 2.7
Codeskulptor Link: http://www.codeskulptor.org/#user46_6QE3Pkt5aY_0.py
This script is a guess the number game which illustrates an example for best case binary search.
"""
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random
import simplegui
num_range = None
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global num_range
if num_range == 100:
range100()
elif num_range == 1000:
range1000()
# define event handlers for control panel
def range100():
"""
Creates button that changes the range to [0,100)
and starts a new game
"""
global num, chances, num_range
num_range = 100
num = random.randrange(0,100)
chances = 7
print "\nNew game"
print "Range is 0 to 100"
print "You have 7 guesses"
def range1000():
"""
Creates button that changes the range to [0,1000)
and starts a new game
"""
global num, chances, num_range
num_range = 1000
num = random.randrange(0,100)
chances = 10
print "\nNew game"
print "Range is 0 to 1000"
print "You have 10 guesses"
def input_guess(guess):
# main game logic goes here
global chances, num_range, num
guess = int(guess)
print "\nNumber of chances left ",chances
print "Your guess is ", guess
if num > guess:
print 'Higher!'
elif num < guess:
print 'Lower!'
elif num == guess:
print 'Correct!!!'
print "You Win!"
print "Let's play another game."
new_game()
if chances == 0:
print "Out of turns, You lose!"
print "The number was", num
print "Try again!"
new_game()
# Create Frame
frame = simplegui.create_frame("Guess the Number", 300, 300)
#Control Elements
frame.add_button("Range is [0,100)", range100, 200)
frame.add_button("Range is [0,1000)", range1000, 200)
frame.add_label("")
frame.add_input("Enter guess", input_guess, 200)
frame.add_label("")
frame.add_label("\nCan you guess the number?\nChoose between either 0 - 100 or 0 - 1000.")
# Call new_game and Start frame
new_game()
frame.start() |
def heart_bpm(number_beats, duration, minutes):
"""
find the minimum and the maximum of a list of voltage and
return a tuple
:param number_beats: the input should be a int
:param duration: the input should be a float
:param minutes: the input should be a float
:raises ImportError: if import is failure
:returns: return a float equals estimated average heart rate
over a user-specified number of minutes
:rtype: float
"""
try:
import logging
except ImportError:
print("Necessary imports failed")
return
logging.basicConfig(filename='heartrate.log', filemode='w',
level=logging.DEBUG)
beat_per_min = number_beats / (duration / 60)
mean_hr_bpm = beat_per_min * minutes
logging.info("function run as expected")
return mean_hr_bpm
|
# %%
from random import choice, randint
# %%
def simulation():
v_1 = 0
v_rand = 0
v_min = None
index = randint(0, 1000)
for i in range(1000):
flips = []
for j in range(10):
outcome = choice(['T', 'H'])
flips.append(outcome)
heads = len([x for x in flips if x == 'H']) / len(flips)
if i == 0:
v_1 = heads
if i == index:
v_rand = heads
if v_min == None or heads < v_min:
v_min = heads
return v_1, v_rand, v_min
def main():
v_1_average = 0
v_rand_average = 0
v_min_average = 0
for i in range(10000):
v_1, v_rand, v_min = simulation()
v_1_average += v_1
v_rand_average += v_rand
v_min_average += v_min
print(i)
print(v_1_average / 10000, v_rand_average / 10000, v_min_average / 10000)
if __name__ == "__main__":
main()
# %%
|
import csv
def checksum_row_minmax(row):
min_val = min(row)
max_val = max(row)
return max_val - min_val
def checksum_row_evenly_divisible(row):
for i in range(0, len(row)):
for j in range(0, len(row)):
if i != j:
if row[i] % row[j] == 0:
return row[i]/row[j]
raise Exception('no match found')
def checksum_matrix(matrix, checksum_row):
total = 0
for row in matrix:
total += checksum_row(row)
return total
if __name__ == '__main__':
matrx = []
with open('input.csv', newline='') as csvfile:
filereader = csv.reader(csvfile, delimiter='\t')
for line in filereader:
sanitized_row = []
for val in line:
sanitized_row.append(int(val))
matrx.append(sanitized_row)
checksum1 = checksum_matrix(matrx, checksum_row_minmax)
checksum2 = checksum_matrix(matrx, checksum_row_evenly_divisible)
print('read file from input.csv')
print('checksum with min-max is %d' % checksum1)
print('checksum2 with even devision is %d' % checksum2)
|
#!/usr/bin/python
## @file suma.py
# @author Jose Fernando Gonzalez Salas & Isaac Gomez Sanchez
# @date 23 de agosto, 2016
# @brief Este programa realiza la suma de datos introducidos en la consola al ejecutar el mismo. Obtiene numeros introducidos por el usuario seguidamente al ejecutar el programa suma.py . El usuario debe recordar compilar el programa antes de ejecutarlo. Este programa cuenta con manejo de excepcione en caso de ingresar un dato no valido para la suma.
# Librerias necesarias para las funciones utilizadas
import sys
## @brief Funcion que utiliza una lista ingresada en la consola seguidamente de la llamada al script y suma cada uno de sus elementos.
#
# Ingresa por medio de sys.argv
def suma():
total = 0.0
for x in range(1, len(sys.argv)):
try:
num = float(sys.argv[x])
total = total + num
except ValueError:
total = "Se ha encontrado un caracter no valido"
return total
# Ejecucion del script
print suma()
|
#Exercise 40.1.4 A First Class Example:
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"]) #rospisane w formie listy
# list of strings !! as the lyrics
bulls_on_parade = Song(["They rally around the family", "With pockets full of shells"])
happy_bday.sing_me_a_song()
print('-'*10)
print(happy_bday.lyrics)
print(len(happy_bday.lyrics))
print('-'*10)
print(happy_bday.lyrics[2])
print('-'*10)
bulls_on_parade.sing_me_a_song()
print('-'*20)
song = ['Hahaha', 'lalla', 'nanana', 'banana']
my_song = Song(song)
my_song.sing_me_a_song()
print('-'*20)
print(my_song.lyrics)
print(my_song.lyrics[-1]) |
#!/usr/bin/python
#-*-coding:utf-8-*-
str1 = u"パトカー"
str2 = u"タクシー"
string = u""
for index in range(len(str1)):
string += str1[index] + str2[index]
print string
|
#!/usr/bin/python
#-*-coding:utf-8-*-
import sys
my_dict={}
my_file = open(sys.argv[1], "r") #ファイルオープン
for line in my_file: #my_fileの内のline文をループをさせる
line = line.strip() #行終端記号¥nを削除
line = line.replace(',', '')
line = line.replace('.', '')
words = line.split(" ") #文を空白区切りで単語の配列に分割
for word in words:
if word not in my_dict: #my_doctにwordが含まれていないならmy_dict[word]を1とする
my_dict[word]=1
else: #それ以外ではmy_dict[word]に要素を追加していく
my_dict[word]+=1
for key, bar in sorted(my_dict.items()): #各キーとその追加された要素数を表示
print "%s %d"% (key, bar) |
#! usr/bin/python
# -*- coding: utf-8 -*-
import sys
import json
my_file = open(sys.argv[1])
for line in my_file:
dec_line = json.loads(line)
if dec_line["title"] == u"イギリス":
print dec_line["text"].encode("utf-8")
|
#!/usr/bin/python
# -*- coding:utf-8 -*-
#04. 元素記号
#"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ
if __name__ == "__main__":
sent = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
head = [1, 5, 6, 7, 8, 9, 15, 16, 19]
elem = {}
for i, word in enumerate(sent.split()):
if i+1 in head:
elem[word[0]] = i+1
else:
elem[word[0:2]] = i+1
for key, value in sorted(elem.items(), key=lambda x:x[1]):
print "%3d: %s" % (value, key)
|
#!/usr/bin/python
#-*-coding:utf-8-*-
def ngramword(text, n):#ngram関数
results = []#結果を格納
if len(text) >= n:#テキストの長さが2以上のときループ開始
for i in range(len(text)-n+1):
results.append(text[i:i+n])#結果のリストにオブジェクトを追加
return results
if __name__ == '__main__':
text = 'I am an NLPer'
list = str.split(text)
for e in ngramword(text, 2):#関数呼び出し
print e
for e in ngramword(text.split(), 2):#区切った単語のリストを関数に渡す
print e |
#!/usr/bin/python
#-*-coding:utf-8-*-
#与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
#英小文字ならば(219 - 文字コード)の文字に置換。その他の文字はそのまま出力。
#この関数を用い,英語のメッセージを暗号化・復号化せよ.
def cipher(sentence):
result = ''
for char in sentence:
if char.islower():#小文字ならば(islower()で小文字かどうか調べることができる)
result += chr(219 - ord(char))#コードポイント変換をordでを行いresultに格納
else :
result += char#その他は標準で格納する
return result
if __name__ == '__main__':
givensentence = 'KomachiLab'
print cipher(givensentence) |
#!/usr/bin/python
#-*-coding:utf-8-*-
from collections import defaultdict
my_file = open("hightemp.txt", "r")
word = defaultdict(str)
counts = {}
for line in my_file:
words = line.strip().split("\t")
print words
if words[0] not in counts:
counts[words[0]] = 1
else:
counts[words[0]] += 1
for key, value in sorted(counts.items(), key = lambda x:x[1], reverse = True):
print key, value
|
# coding:utf-8
def main():
print "x =",
x = raw_input()
print "y =",
y = raw_input()
print "z =",
z = raw_input()
print x + "時の" + y + "は" + z
if __name__ == '__main__':
main()
|
#! usr/bin/python
# -*- coding: utf-8 -*-
import sys
my_file = open(sys.argv[1], "r")
line_list = []
for line in my_file:
line = line.strip()
words = line.split("\t")
line_list.append(words)
sorted_list = sorted(line_list, key = lambda words: -float(words[2]))
for word in sorted_list:
print "\t".join(word)
|
#!/usr/bin/python
# _*_coding:utf-8 _*_
import sys
def main():
country_name = ["United States", "United Arab Emirates", "Antigua and Barbuda", "United Kingdom", "Islamic Republic of Iran", "Isle of Man", "El Salvador", "Netherlands Antilles", "Cape Verde", "Cote d'Ivoire", "Costa Rica", "Saudi Arabia", "Sao Tome and Principe", "San Marino", "Sierra Leone", "Syrian Arab Republic", "Equatorial Guinea", "Saint Kitts and Nevis", "Saint Vincent and the Grenadines", "Saint Lucia", "Solomon Islands", "Republic of Korea", "United Republic of Tanzania", "Czech Republic", "Central African Republic", "Democratic People's Republic of Korea", "Dominican Republic", "Trinidad and Tobago", "New Zealand", "Holy See", "Vatican City State", "Papua New Guinea", "Burkina Faso", "Brunei Darussalam", "Viet Nam", "Bosnia and Herzegovina", "Marshall Islands", "the former Yugoslav Republic of Macedonia", "Federated States of Micronesia", "South Africa", "Republic of Moldova", "Lao People's Democratic Republic", "Libyan Arab Jamahiriya", "Russian Federation"]
input_file = open(sys.argv[1], "r")
for line in input_file:
line = line.strip()
for country in country_name:
if country in line:
line = line.replace(country, "_".join(country.split(" ")))
print line
input_file.close()
if __name__=="__main__":
main()
|
#Author : Fadli Maulana (cacadosman)
class Node:
data = None
next = None
def __init__(self, data):
self.data = data
class LinkedList:
head = None
tail = None
def isEmpty(self):
return self.head == None
# Insert node at the beginning of the list.
def addFirst(self, data):
input = Node(data)
if self.isEmpty():
self.head = input
self.tail = input
else:
input.next = self.head
self.head = input
# Insert node at the end of the list.
def addLast(self, data):
input = Node(data)
if self.isEmpty():
self.head = input
self.tail = input
else:
self.tail.next = input
self.tail = input
# Insert node after the node that matches the query.
def insertAfter(self, key, data):
input = Node(data)
temp = self.head
while temp != None:
if temp.data == key:
input.next = temp.next
temp.next = input
break;
temp = temp.next
# Insert node before the node that matches the query.
def insertBefore(self, key, data):
input = Node(data)
temp = self.head
while temp != None:
if temp.data == key and temp == self.head:
self.addFirst(input)
break;
elif temp.next.data == key:
input.next = temp.next
temp.next = input
break;
temp = temp.next
# Delete the first node in the list.
def removeFirst(self):
if not self.isEmpty():
if self.head == self.tail:
self.head = self.tail = None
else:
self.head = self.head.next
# Delete the last node in the list.
def removeLast(self):
temp = self.head
if not self.isEmpty():
if self.head == self.tail:
self.head = self.tail = None
else:
while temp.next != self.tail:
temp = temp.next
temp.next = None
self.tail = temp
# Delete the node that matches the query.
def remove(self, key):
temp = self.head
if not self.isEmpty():
while temp.next != None:
if temp.data == key and temp == self.head:
self.removeFirst()
break
elif temp.next == None:
break
elif temp.next.data == key:
temp.next = temp.next.next
break;
temp = temp.next
# find the node that matches the query.
def find(self, key):
found = False
temp = self.head
while temp != None:
if temp.data == key:
found = True
break;
temp = temp.next
if found:
return True
else:
return False
# print all element in the list
def printAll(self):
list = []
temp = self.head
while temp != None:
list.append(temp.data)
temp = temp.next
print ' '.join(str(e) for e in list)
# get the nth element in the list.
def get(self, index):
temp = self.head
for i in range(0, index):
if temp.next == None:
temp.data = ""
break;
temp = temp.next
return temp.data
# === MAIN PROGRAM ===
link = LinkedList()
link.addFirst(10)
link.addFirst(20)
link.addFirst(45)
link.addLast(30)
link.insertAfter(10,50)
link.insertBefore(50,25)
link.removeFirst()
link.removeLast()
link.remove(23)
link.printAll()
print link.get(2)
|
class Solver:
def __init__(self, grid):
self.blankCellCounter = 0
self.solution = [ [ 0 for i in range(9) ] for j in range(9) ]
for i in range(len(grid)):
for j in range(len(grid[0])):
self.solution[i][j] = grid[i][j]
if(grid[i][j] == 0):
self.blankCellCounter += 1
#if value is valid in a cell of a given row return true, else return false
def checkRow(self, workingTable, value, row):
for i in range(9):
if(value == workingTable[row][i]):
return False
return True
#if value is valid in a cell of a given column return true, else return false
def checkColumn(self, workingTable, value, column):
for i in range(9):
if(value == workingTable[i][column]):
return False
return True
#if value is valid in a cell of a given subgrid (obtained from the row and column) return true, else return false
def checkSubGrid(self, workingTable, value, row, column):
xMultiplier = int(column/3)
yMultiplier = int(row/3)
for i in range(3):
for j in range(3):
if(value == workingTable[yMultiplier*3 + i][xMultiplier*3 + j]):
return False
return True
#return the coordinates of the first blank cell; returns invalid coordinates if there are none
def findBlankCell(self, workingTable):
for i in range(9):
for j in range(9):
if(workingTable[i][j] == 0):
return i,j
return -1, -1
#calls the method that solves a sudoku puzzle and prints the solution; if there is no solution, a message is displayed
def solver(self, grid):
workingTable = grid
if(self.completeTable(workingTable)):
self.solution = workingTable
self.printSolution()
else:
print("No solution found")
#this method uses backtracking to try and obtain the solution of a sudoku puzzle
def completeTable(self, workingTable):
row, column = self.findBlankCell(workingTable)
if(row == -1): #didn't find a blank cell
return True
else:
for possibleValue in range(1, 10):
if(self.checkRow(workingTable, possibleValue, row) and self.checkColumn(workingTable, possibleValue, column) and self.checkSubGrid(workingTable, possibleValue, row, column)):
workingTable[row][column] = possibleValue
if(self.completeTable(workingTable)):
return True #the value used is working
workingTable[row][column] = 0 #the value didn't work, reset the cell and try the next value
return False #guarantees backtracking (no value worked in this cell, so go back to the last cell analyzed and try another value)
def printSolution(self):
print("Solved Sudoku game")
for i in range(9):
for j in range(9):
print(self.solution[i][j]," ", end = "", flush = True)
print("\n") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.