text stringlengths 37 1.41M |
|---|
thisTuple=("apple","banana","lemon","cherry","mango") #create Tuple
print(thisTuple) #print Tuple
print(thisTuple[1]) #print a index
print(thisTuple[-2]) #negative index
print(thisTuple[2:5]) #range index
y=list(thisTuple)
y[2]="orange" #update tuple
thisTuple=tuple(y)
print(thisTuple)
if "orange" in thisTuple: #present check
print("yes present")
print(len(thisTuple)) #tuple Length
l1=(1,2,3)
l2=(4,5,6)
l3=l1+l2 #join
print(l3)
|
class emp:
def __init__(self,id,name,dob):
self.id=id
self.name=name
self.dob=dob
def display(abc):
print("ID:"+abc.id)
print("Name:"+abc.name)
print("DOB:"+abc.dob)
obj=emp("A02","Supriyo","15Dec1998")
obj.display()
|
x=["Apple","Mango","Lemon"]
y=["Orange","Apple","Grapes"]
for a in x:
if a in y:
print(a," is present");
|
import tensorflow as tf
import tensorflowvisu
import math
from tensorflow.examples.tutorials.mnist import input_data as mnist_data
print("Tensorflow version " + tf.__version__)
tf.set_random_seed(0)
# neural network with 6 layers of relu neurons and final softmax layer
#
# · · · · · · · · · · (input data, flattened pixels) X [batch, 784] # 784 = 28 * 28
# \x/x\x/x\x/x\x/x\x/ -- fully connected layer (softmax) W [784, 10] b[10]
# · · · · · · · · Y [batch, 10]
# The model is:
#
# Y = softmax( X * W + b)
# X: matrix for 100 grayscale images of 28x28 pixels, flattened (there are 100 images in a mini-batch)
# W: weight matrix with 784 lines and 10 columns
# b: bias vector with 10 dimensions
# +: add with broadcasting: adds the vector to each line of the matrix (numpy)
# softmax(matrix) applies softmax on each line
# softmax(line) applies an exp to each value then divides by the norm of the resulting line
# Y: output matrix with 100 lines and 10 columns
# Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels)
mnist = mnist_data.read_data_sets("data", one_hot=True, reshape=False, validation_size=0)
# input X: 28x28 grayscale images, the first dimension (None) will index the images in the mini-batch
X = tf.placeholder(tf.float32, [None, 28, 28, 1])
# correct answers will go here
Y_ = tf.placeholder(tf.float32, [None, 10])
# Variable (decaying) learning rate
learning_rate = tf.placeholder(tf.float32)
# Number of neurons in each layer - 7 total layers (Last layer has 10 softMax neurons)
A = 400
B = 200
C = 200
D = 100
E = 60
F = 30
# Sigmoid Layers
Wa = tf.Variable(tf.truncated_normal([784, A], stddev = 0.1))
Ba = tf.Variable(tf.zeros([A]))
Wb = tf.Variable(tf.truncated_normal([A, B], stddev = 0.1))
Bb = tf.Variable(tf.zeros([B]))
Wc = tf.Variable(tf.truncated_normal([B, C], stddev = 0.1))
Bc = tf.Variable(tf.zeros([C]))
Wd = tf.Variable(tf.truncated_normal([C, D], stddev = 0.1))
Bd = tf.Variable(tf.zeros([D]))
We = tf.Variable(tf.truncated_normal([D, E], stddev = 0.1))
Be = tf.Variable(tf.zeros([E]))
Wf = tf.Variable(tf.truncated_normal([E, F], stddev = 0.1))
Bf = tf.Variable(tf.zeros([F]))
# Last layer with softMax neurons
W = tf.Variable(tf.truncated_normal([F, 10], stddev = 0.1))
B = tf.Variable(tf.zeros([10]))
# flatten the images into a single line of pixels
# -1 in the shape definition means "the only possible dimension that will preserve the number of elements"
XX = tf.reshape(X, [-1, 784])
# The model
Ya = tf.nn.relu(tf.matmul(XX, Wa) + Ba)
Yb = tf.nn.relu(tf.matmul(Ya, Wb) + Bb)
Yc = tf.nn.relu(tf.matmul(Yb, Wc) + Bc)
Yd = tf.nn.relu(tf.matmul(Yc, Wd) + Bd)
Ye = tf.nn.relu(tf.matmul(Yd, We) + Be)
Yf = tf.nn.relu(tf.matmul(Ye, Wf) + Bf)
Ylogits = tf.matmul(Yf, W) + B
Y = tf.nn.softmax(Ylogits)
# loss function: cross-entropy = - sum( Y_i * log(Yi) )
# Y: the computed output vector
# Y_: the desired output vector
# cross-entropy
# log takes the log of each element, * multiplies the tensors element by element
# reduce_mean will add all the components in the tensor
# so here we end up with the total cross-entropy for all images in the batch
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=Ylogits, labels=Y_)
cross_entropy = tf.reduce_mean(cross_entropy)*100
# accuracy of the trained model, between 0 (worst) and 1 (best)
correct_prediction = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# training, learning rate is variable and decaying
train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)
# matplotlib visualisation
allweights = tf.concat([tf.reshape(Wa, [-1]),
tf.reshape(Wb, [-1]),
tf.reshape(Wc, [-1]),
tf.reshape(Wd, [-1]),
tf.reshape(We, [-1]),
tf.reshape(Wf, [-1])
], 0)
allbiases = tf.concat([tf.reshape(Ba, [-1]),
tf.reshape(Bb, [-1]),
tf.reshape(Bc, [-1]),
tf.reshape(Bd, [-1]),
tf.reshape(Be, [-1]),
tf.reshape(Bf, [-1])
], 0)
I = tensorflowvisu.tf_format_mnist_images(X, Y, Y_) # assembles 10x10 images by default
It = tensorflowvisu.tf_format_mnist_images(X, Y, Y_, 1000, lines=25) # 1000 images on 25 lines
datavis = tensorflowvisu.MnistDataVis()
# init
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
# You can call this function in a loop to train the model, 100 images at a time
def training_step(i, update_test_data, update_train_data):
# training on batches of 100 images with 100 labels
batch_X, batch_Y = mnist.train.next_batch(100)
# Learning rate decay
lr_min = 0.0001
lr_max = 0.003
decay_speed = 2000
lr= lr_min + (lr_max - lr_min) * math.exp(-1/2000)
# compute training values for visualisation
if update_train_data:
a, c, im, w, b = sess.run([accuracy, cross_entropy, I, allweights, allbiases], feed_dict={X: batch_X, Y_: batch_Y})
datavis.append_training_curves_data(i, a, c)
datavis.append_data_histograms(i, w, b)
datavis.update_image1(im)
print(str(i) + ": accuracy:" + str(a) + " loss: " + str(c))
# compute test values for visualisation
if update_test_data:
a, c, im = sess.run([accuracy, cross_entropy, It], feed_dict={X: mnist.test.images, Y_: mnist.test.labels})
datavis.append_test_curves_data(i, a, c)
datavis.update_image2(im)
print(str(i) + ": ********* epoch " + str(i*100//mnist.train.images.shape[0]+1) + " ********* test accuracy:" + str(a) + " test loss: " + str(c) + " learning rate: " + str(lr))
# the backpropagation training step
sess.run(train_step, feed_dict={X: batch_X, Y_: batch_Y, learning_rate: lr})
datavis.animate(training_step, iterations=5000+1, train_data_update_freq=10, test_data_update_freq=50, more_tests_at_start=True)
# to save the animation as a movie, add save_movie=True as an argument to datavis.animate
# to disable the visualisation use the following line instead of the datavis.animate line
# for i in range(2000+1): training_step(i, i % 50 == 0, i % 10 == 0)
print("max test accuracy: " + str(datavis.get_max_test_accuracy()))
# final max test accuracy = 0.9268 (10K iterations). Accuracy should peak above 0.92 in the first 2000 iterations.
|
from Utilities.utility import FunctionalCode
f1 = FunctionalCode
class QuestionToFindYourNumber:
try:
my_list = []
print("Enter the N value")
num = int(input())
while num < 0:
print("Please Provide Positive Number(only)")
num = int(input())
for i in range(1, pow(2, num-1)):
my_list.append(i)
print("think of a number between 0 and ", len(my_list)-1)
print(my_list)
low = 0
high = len(my_list)-1
f1.guessNumber(my_list, low, high)
except RuntimeError:
print(".....................oops Something Went Wrong.........") |
"""
******************************************************************************
* Purpose: Takes a date as input and prints the day of the week that date.
* @author: Krishna Murthy A V
* @version: 1.2
* @since: 28-1-2019
*
******************************************************************************
"""
from Utilities.utility import FunctionalCode
obj =FunctionalCode
class DayOfWeek:
try:
print("Enter Value for Month:")
m = int(input())
while m <= 0:
m = int(input("Please Provide Valid Value(Month)\n"))
print("Enter Value for Day:")
d = int(input())
while d <= 0:
d = int(input("Please Provide Valid Value(Day)\n"))
print("Enter Value for Year:")
y = int(input())
while y <= 999:
y = int(input("Please Provide Valid Value(Year)\n"))
obj.dayOfTheWeek(m, d, y)
except ValueError:
print("-------Please Provide Valid input(Positive Number)") |
"""
******************************************************************************
* Purpose: compute the square root of a nonnegative number c given in the
input using Newton's method
* @author: Krishna Murthy A V
* @version: 1.2
* @since: 28-2-2019
*
******************************************************************************
"""
from Utilities.utility import FunctionalCode
obj =FunctionalCode
class SquareRoot:
try:
print("Enter The Non-Negative Number:")
num = int(input())
while num <= 0:
num = int(input("Please Provide Valid Value(Positive Number)\n"))
obj.findSquareRoot(num)
except ValueError:
print("-------Please Provide Valid input(Positive Number)") |
"""
******************************************************************************
* Purpose: Write static functions to return all permutation of a String
using Recursion method.
*@author: Krishna Murthy A V
* @version: 1.1
* @since: 27-2-2019
*
******************************************************************************
"""
from Utilities.utility import FunctionalCode
u = FunctionalCode
def permut():
word = list(input("Enter the string \n")) # take string input
for p in u.permutation(word):
print(p) # print the permutation
u.permutation(word)
if __name__ == "__main__":
permut()
|
for letra in "Python":
if letra =="h":
continue #saltea las siguientes instrucciones del bucle
print("Letra: " + letra)
# Pass se suele usar para declarar una clase e implementarla más adelante. Ej_
# Class MiClase:
#pass
email = input("Ingrese un Email: ")
for i in email:
if i =="@":
arroba = True
break;
else: # este else forma parte del bucle for (podría ser de un while)
# se ejecuta cuando el bucle haya completado todas sus vueltas
arroba = False
print(arroba)
|
i=1
while i<=5: #la tabulación determina el alcance del while salvo que aparezca break
print(f"El valor de i es: {i}")
i=i+1
edad=int(input("Introduce una edad: "))
intentos = 3
while edad < 0 or edad > 100 :
intentos = intentos - 1
if intentos:
if intentos == 1:
print(f"Edad incorrecta, te resta {intentos} intento.")
else:
print(f"Edad incorrecta, te restan {intentos} intentos.")
edad=int(input("Introduce una edad válida: "))
else:
break;
if not intentos:
print("Has perdido las 3 oportunidades")
else:
print(f"{edad} años, bien. Puedes pasar")
|
for i in ["Ingeniería", "Informática", 3]: #recorre tantas veces como elementos hay en una lista
print("Hola", end=" ") # se usa para evitar saltos de línea y se puede concatenar un string
for i in "Francisco": #si lo hago contra un string recorre caracter por caracter
print(i)
personas = ["Rodrigo", "Rocío"]
def verificar_email(email):
valido=False
print("Vericación del Email: " + email)
for i in email:
if(i == "@"):
valido = True
if valido:
print("El Email es correcto")
else:
print("El Email es incorrecto")
for i in personas:
verificar_email(input("Ingrese un Email para verificar: "))
|
# .upper(), .lower(), .capitalize(), .count(), .find(), .rfind(),
# .isdigit(), .isalum(), .isalpha(), .split(), .strip(), .replace()
# COSULTAR: http://pyspanishdoc.sourceforge.net/lib/module-string.html
nombreUsuario=input("Nombre de usuario: ")
print("Tu nombre de usuario es: ", nombreUsuario.capitalize())
|
#!python
def is_sorted(list_in):
for index, item in enumerate(list_in):
if index == len(list_in) - 1:
return True
if list_in[index + 1] is not None:
if item > list_in[index + 1]:
return False
return True
def bubble_sort(items, descending=False, comparison=lambda a, b: a > b):
"""Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
Running time: O(n) when sorted, O(n^2) average and worst(when reverse sorted)
Memory usage: O(n) always, it's in place"""
finished = False
while finished is False:
has_swapped = False
for index, item in enumerate(items):
if index is 0:
continue
if descending:
if comparison(item, items[index-1]): # What does DRY stand for, anyway?
items[index] = items[index-1]
items[index-1] = item
has_swapped = True
else:
if comparison(items[index-1], item): # What does DRY stand for, anyway?
items[index] = items[index-1]
items[index-1] = item
has_swapped = True
if has_swapped is False:
finished = True
def cocktail_shaker_sort(items, descending=False, comparison=lambda a, b: a > b):
"""Sort given items by shaking the list really hard.
Running time: O(n) when sorted, O(n^2) average and worst(when reverse sorted)
Memory usage: O(n) always, it's in place"""
finished = False
while finished is False:
has_swapped = False
for index, item in enumerate(items):
if index is 0:
continue
if descending:
if comparison(item, items[index-1]): # What does DRY stand for, anyway?
items[index] = items[index-1]
items[index-1] = item
has_swapped = True
else:
if comparison(items[index-1], item): # What does DRY stand for, anyway?
items[index] = items[index-1]
items[index-1] = item
has_swapped = True
for index in range(len(items) -1, -1, -1):
item = items[index]
if index is 0:
continue
if descending:
if comparison(item, items[index-1]): # What does DRY stand for, anyway?
items[index] = items[index-1]
items[index-1] = item
has_swapped = True
else:
if comparison(items[index-1], item): # What does DRY stand for, anyway?
items[index] = items[index-1]
items[index-1] = item
has_swapped = True
if has_swapped is False:
finished = True
def selection_sort(items, descending=False, comparison=lambda a, b: a > b):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
Running time: O(n^2) always, needs to check rest of list every time
Memory usage: O(n) always, it's in place"""
if descending: # What does DRY stand for, anyway?
for index in range(len(items)):
maximum_ndx = index
for p_index in range(index+1, len(items)):
if comparison(items[p_index], items[maximum_ndx]):
maximum_ndx = p_index
items[index], items[maximum_ndx] = items[maximum_ndx], items[index]
else: # What does DRY stand for, anyway?
for index in range(len(items)):
minimum_ndx = index
for p_index in range(index+1, len(items)):
if comparison(items[minimum_ndx], items[p_index]):
minimum_ndx = p_index
items[index], items[minimum_ndx] = items[minimum_ndx], items[index]
def insertion_sort(items, descending=False, comparison=lambda a, b: a > b):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order.
O(n) when sorted, O(n^2) average and worst(reverse sort)
Memory usage: O(n) always, it's in place"""
for index in range(1, len(items)):
_insertion_helper(items, index, items[index], descending, comparison)
def _insertion_helper(list_in, sublist_index, item, descending=False, comparison=lambda a, b: a > b):
'''
Handles insertion into sorted sublist during insertion sort.
sublist_index should equal working index.
'''
insert_index = _binary_locator(list_in, 0, sublist_index, item, descending, comparison)
slide_index = sublist_index
while slide_index is not insert_index and slide_index is not 0:
list_in[slide_index] = list_in[slide_index-1]
slide_index -= 1
list_in[insert_index] = item
def _binary_locator(list_in, lower_index, upper_index, item, descending=False, comparison=lambda a, b: a > b):
'''
Helper helper... recursive binary search for index
'''
if upper_index == lower_index:
return upper_index
if descending:
center = (lower_index + upper_index) // 2 # stable for descending
if comparison(item, list_in[center]): # What does DRY stand for, anyway?
upper_index = center - 1
elif comparison(list_in[center], item):
lower_index = center
else:
return center
else:
center = (lower_index + upper_index) // 2 # not stable for ascending, make it round up
if comparison(list_in[center], item): # What does DRY stand for, anyway?
upper_index = center
elif list_in[center] == item:
return center
else:
lower_index = center + 1
return _binary_locator(list_in, lower_index, upper_index, item, descending)
|
class Recommender():
'''
What is this class all about - write a really good doc string here
'''
def __init__(self):
'''
what do we need to start out our recommender system
'''
pass
def read_dataset(self, movies_path='./data/movies_clean.csv', reviews_path='./data/train_data.csv'):
'''
INPUTS:
------------
movies_path - (string) file path to the movies, default='./movies_clean.csv'
reviews_path - (string) file path to the reviews, default='./train_data.csv'
OUTPUTS:
------------
movies - (dataframe) movie dataframe
reviews - (dataframe) review dataframe
'''
# Read in the datasets
movies = pd.read_csv(movies_path)
reviews = pd.read_csv(reviews_path)
del movies['Unnamed: 0']
del reviews['Unnamed: 0']
print('movies')
print(movies.head())
print(movies.shape)
print('------------------------')
print(' ')
print('reviews')
print(reviews.head())
print(reviews.shape)
print('------------------------')
print(' ')
return movies, reviews
def create_train_test(self,reviews, order_by, train_size_prct=0.8):
'''
INPUTS:
------------
reviews - (pandas df) dataframe to split into train and test
order_by - (string) column name to sort by
train_size_prct - (float) - percentage of data used for training, default=0.8
OUTPUTS:
------------
training_df - (pandas df) dataframe of the training set
validation_df - (pandas df) dataframe of the test set
'''
# Define the train and test data size via train_size_prct
training_size = int(reviews.shape[0] * train_size_prct)
testing_size = reviews.shape[0] - training_size
# Sort the reviews by date before splitting
# use old data for training, new data for validation
reviews_new = reviews.sort_values(order_by)
training_df = reviews_new.head(training_size)
validation_df = reviews_new.iloc[training_size:training_size+testing_size]
print('reviews_new')
print(reviews_new.head())
print(reviews_new.shape)
print('------------------------')
print(' ')
print('training_df')
print(training_df.head())
print(training_df.shape)
print('------------------------')
print(' ')
print('validation_df')
print(validation_df.head())
print(validation_df.shape)
print('------------------------')
print(' ')
return training_df, validation_df
def fit(self,
movies_path='./data/movies_clean.csv',
reviews_path='./data/train_data.csv',
order_by='date',
train_size_prct=0.8,
latent_features=15,
learning_rate=0.005,
iters=10):
''' Fit the recommender engine to the dataset and
save the results to pull from when you need to make predictions
INPUTS:
------------
movies_path - (string) file path to the movies, default='./movies_clean.csv'
reviews_path - (string) file path to the reviews, default='./train_data.csv'
order_by - (string) column name to sort by
train_size_prct - (float) - percentage of data used for training, default=0.8
latent_features - (int) the number of latent features used, default=15,
learning_rate - (float) the learning rate, default=0.005
iters - (int) the number of iterations, default=10
OUTPUTS:
-------------
user_mat - (numpy array) a user by latent feature matrix
movie_mat - (numpy array) a latent feature by movie matrix
'''
# Read in movie and review DataFrames
movies, reviews = self.read_dataset(movies_path,reviews_path)
# Hyperparameters: Number of latent features, lr, epochs
latent_features = latent_features
learning_rate = learning_rate
iters = iters
training_df, validation_df = self.create_train_test(reviews, order_by, train_size_prct)
# Create user-by-item matrix as np array
train_user_item = training_df[['user_id', 'movie_id', 'rating', 'timestamp']]
train_data_df = train_user_item.groupby(['user_id', 'movie_id'])['rating'].max().unstack()
ratings_mat = np.array(train_data_df)
self.ratings_mat = ratings_mat
print('user-by-item matrix')
print(ratings_mat)
print(ratings_mat.shape)
print('------------------------')
print(' ')
# Number of users and movies in the user-by-item matrix
self.n_users = ratings_mat.shape[0]
self.n_movies = ratings_mat.shape[1]
self.num_ratings = np.count_nonzero(~np.isnan(ratings_mat))
print('number of users: ', self.n_users)
print('number of movies: ', self.n_movies)
print('number of non nan ratings: ', self.num_ratings)
# Initialize the user and movie matrices with random values
user_mat = np.random.rand(self.n_users, latent_features)
movie_mat = np.random.rand(latent_features, self.n_movies)
print('U matrix (users) before training')
print(user_mat)
print(user_mat.shape)
print('------------------------')
print(' ')
print('Vt matrix (movies) before training')
print(movie_mat)
print(movie_mat.shape)
print('------------------------')
print(' ')
# Initialize sse at 0 for first iteration
sse_accum = 0
# keep track of iteration and MSE
print("Optimizaiton Statistics")
print("Iterations | Mean Squared Error ")
# for each iteration
for iteration in range(iters):
# update our sse
old_sse = sse_accum
sse_accum = 0
# For each user-movie pair
for i in range(self.n_users):
for j in range(self.n_movies):
# if the rating exists
if ratings_mat[i, j] > 0:
# compute the error as the actual minus the dot product of the user and movie latent features
diff = ratings_mat[i, j] - np.dot(user_mat[i, :], movie_mat[:, j])
# Keep track of the sum of squared errors for the matrix
sse_accum += diff**2
# update the values in each matrix in the direction of the gradient
for k in range(latent_features):
user_mat[i, k] += learning_rate * (2*diff*movie_mat[k, j])
movie_mat[k, j] += learning_rate * (2*diff*user_mat[i, k])
# print results
print("%d \t\t %f" % (iteration+1, sse_accum / self.num_ratings))
# Validation
print('Start validation ...')
rmse, perc_rated, actual_v_pred, preds, acts = self.validation_comparison(validation_df, user_mat=user_mat, movie_mat=movie_mat)
print('rmse: ', rmse)
print('perc_rated: ', perc_rated)
print('actual_v_pred: ', actual_v_pred)
self.plot_validation_results(rmse, perc_rated, actual_v_pred, preds, acts)
print(' ')
print('Saving user-by-item matrix as pickle ...')
with open('ratings_mat.pkl','wb') as f:
pickle.dump(ratings_mat, f)
print('...done')
print('------------------------')
print(' ')
print(' ')
print('Saving user_mat as pickle ...')
with open('user_mat.pkl','wb') as f:
pickle.dump(user_mat, f)
print('...done')
print('------------------------')
print(' ')
print(' ')
print('Saving movie_mat as pickle ...')
with open('movie_mat.pkl','wb') as f:
pickle.dump(movie_mat, f)
print('...done')
print('------------------------')
print(' ')
return user_mat, movie_mat, ratings_mat
def predict_rating(self, user_matrix, movie_matrix, user_id, movie_id, load_mat=False):
''' makes predictions of a rating for a user on a movie-user combo
INPUTS:
------------
user_matrix - user by latent factor matrix
movie_matrix - latent factor by movie matrix
user_id - the user_id from the reviews df
movie_id - the movie_id according the movies df
OUTPUTS:
------------
pred - the predicted rating for user_id-movie_id according to FunkSVD
'''
if load_mat==True:
ratings_mat, user_mat, movie_mat, ratings_mat = self.load_matrices()
# Create series of users and movies in the right order
user_ids_series = np.array(ratings_mat.index)
movie_ids_series = np.array(ratings_mat.columns)
# User row and Movie Column
user_row = np.where(user_ids_series == user_id)[0][0]
movie_col = np.where(movie_ids_series == movie_id)[0][0]
# Take dot product of that row and column in U and V to make prediction
pred = np.dot(user_matrix[user_row, :], movie_matrix[:, movie_col])
return pred
def validation_comparison(self, val_df, user_mat, movie_mat):
'''
INPUTS:
------------
val_df - the validation dataset created in create_train_test
user_mat - U matrix in FunkSVD
movie_mat - V matrix in FunkSVD
OUTPUTS:
------------
rmse - RMSE of how far off each value is from it's predicted value
perc_rated - percent of predictions out of all possible that could be rated
actual_v_pred - a 10 x 10 grid with counts for actual vs predicted values
'''
val_users = np.array(val_df['user_id'])
val_movies = np.array(val_df['movie_id'])
val_ratings = np.array(val_df['rating'])
sse = 0
num_rated = 0
preds, acts = [], []
actual_v_pred = np.zeros((10,10))
print(len(len(val_users)))
for idx in range(len(val_users)):
print(idx)
try:
print('idx not null ', idx)
pred = self.predict_rating(user_mat, movie_mat, val_users[idx], val_movies[idx])
sse += (val_ratings[idx] - pred)**2
num_rated+=1
preds.append(pred)
acts.append(val_ratings[idx])
actual_v_pred[11-int(val_ratings[idx]-1), int(round(pred)-1)]+=1
except:
continue
rmse = np.sqrt(sse/num_rated)
perc_rated = num_rated/len(val_users)
return rmse, perc_rated, actual_v_pred, preds, acts
def plot_validation_results(self, rmse, perc_rated, actual_v_pred, preds, acts):
# How well did we do?
print(rmse, perc_rated)
sns.heatmap(actual_v_pred);
plt.xticks(np.arange(10), np.arange(1,11));
plt.yticks(np.arange(10), np.arange(1,11));
plt.xlabel("Predicted Values");
plt.ylabel("Actual Values");
plt.title("Actual vs. Predicted Values");
def load_matrices(self, ratings_mat_path='ratings_mat.pkl', user_mat_path='user_mat.pkl', movie_mat_path='movie_mat.pkl'):
with open(ratings_mat_path,'rb') as f:
ratings_mat = pickle.load(f)
print('Shape of user_mat')
print(ratings_mat.shape)
print('------------------------')
print(' ')
with open(user_mat_path,'rb') as f:
user_mat = pickle.load(f)
print('Shape of user_mat')
print(user_mat.shape)
print('------------------------')
print(' ')
with open(movie_mat_path,'rb') as f:
movie_mat = pickle.load(f)
print('Shape of user_mat')
print(movie_mat.shape)
print('------------------------')
print(' ')
return ratings_mat, user_mat, movie_mat
def find_similar_movies(self, movie_id):
'''
INPUTS:
------------
movie_id - a movie_id
OUTPUTS:
------------
similar_movies - an array of the most similar movies by title
'''
# find the row of each movie id
movie_idx = np.where(movies['movie_id'] == movie_id)[0][0]
# find the most similar movie indices - to start I said they need to be the same for all content
similar_idxs = np.where(dot_prod_movies[movie_idx] == np.max(dot_prod_movies[movie_idx]))[0]
# pull the movie titles based on the indices
similar_movies = np.array(movies.iloc[similar_idxs, ]['movie'])
return similar_movies
def get_movie_names(self, movie_ids):
'''
INPUTS:
------------
movie_ids - a list of movie_ids
OUTPUT:
------------
movies - a list of movie names associated with the movie_ids
'''
movie_lst = list(movies[movies['movie_id'].isin(movie_ids)]['movie'])
return movie_lst
def create_ranked_df(self, movies, reviews):
'''
INPUTS:
------------
movies - the movies dataframe
reviews - the reviews dataframe
OUTPUT:
------------
ranked_movies - a dataframe with movies that are sorted by highest avg rating, more reviews,
then time, and must have more than 4 ratings
'''
# Pull the average ratings and number of ratings for each movie
movie_ratings = reviews.groupby('movie_id')['rating']
avg_ratings = movie_ratings.mean()
num_ratings = movie_ratings.count()
last_rating = pd.DataFrame(reviews.groupby('movie_id').max()['date'])
last_rating.columns = ['last_rating']
# Add Dates
rating_count_df = pd.DataFrame({'avg_rating': avg_ratings, 'num_ratings': num_ratings})
rating_count_df = rating_count_df.join(last_rating)
# merge with the movies dataset
movie_recs = movies.set_index('movie_id').join(rating_count_df)
# sort by top avg rating and number of ratings
ranked_movies = movie_recs.sort_values(['avg_rating', 'num_ratings', 'last_rating'], ascending=False)
# for edge cases - subset the movie list to those with only 5 or more reviews
ranked_movies = ranked_movies[ranked_movies['num_ratings'] > 4]
return ranked_movies
def popular_recommendations(self, user_id, n_top, ranked_movies):
'''
INPUT:
------------
user_id - the user_id (str) of the individual you are making recommendations for
n_top - an integer of the number recommendations you want back
ranked_movies - a pandas dataframe of the already ranked movies based on avg rating, count, and time
OUTPUTS:
------------
top_movies - a list of the n_top recommended movies by movie title in order best to worst
'''
top_movies = list(ranked_movies['movie'][:n_top])
return top_movies
def start_prediction(self):
user_mat, movie_mat = self.load_matrices()
def make_recs(self, _id, train_data, train_df, movies, user_mat, _id_type='movie', rec_num=5):
'''
INPUTS:
------------
_id - either a user or movie id (int)
_id_type - "movie" or "user" (str)
train_data - dataframe of data as user-movie matrix
train_df - dataframe of training data reviews
movies - movies df
user_mat - the U matrix of matrix factorization
movie_mat - the V matrix of matrix factorization
rec_num - number of recommendations to return (int)
OUTPUTS:
------------
recs - (array) a list or numpy array of recommended movies like the
given movie, or recs for a user_id given
'''
# if the user is available from the matrix factorization data,
# I will use this and rank movies based on the predicted values
# For use with user indexing
val_users = train_data_df.index
rec_ids = create_ranked_df(movies, train_df)
if _id_type == 'user':
if _id in train_data.index:
# Get the index of which row the user is in for use in U matrix
idx = np.where(val_users == _id)[0][0]
# take the dot product of that row and the V matrix
preds = np.dot(user_mat[idx,:],movie_mat)
# pull the top movies according to the prediction
indices = preds.argsort()[-rec_num:][::-1] #indices
rec_ids = train_data_df.columns[indices]
rec_names = get_movie_names(rec_ids)
else:
# if we don't have this user, give just top ratings back
rec_names = popular_recommendations(_id, rec_num, ranked_movies)
# Find similar movies if it is a movie that is passed
else:
rec_ids = find_similar_movies(_id)
rec_names = get_movie_names(rec_ids)
return rec_ids, rec_names
if __name__ == '__main__':
# test different parts to make sure it works
pass
|
def delete_string(array, string):
if string in array:
array.remove(string)
return array
else:
return False
print (delete_string(["a", "b", "c", "d", "e"], "c"))
|
def create_dict(number):
dictionary = {}
for i in range(number):
dictionary[i + 1] = (i+1) * (i+1)
print (dictionary)
create_dict(5)
|
def addup_dictionary(dictionary):
total = 0
for key, value in dictionary.items():
total += value
return total
print (addup_dictionary({1:2,2:6,3:5}))
|
# 元组是一个不可变的序列
# 它和列表的操作方式基本一致
# 创建元组使用()
my_tuple = () # 创建了一个空元组
print(my_tuple, ",", type(my_tuple)) # <class 'tuple'>
# 当元组不是一个空元组是,括号可以省略
# 如果元组不是空元组,它需要包含至少一个元素
my_tuple = 1, 2, 3, 4, 5, 6, 7 # 定义一个包含多个元素的元组
# print(my_tuple)
# my_tuple = 40, # 定义一个只包含一个元素的元组
# print(my_tuple)
# 序列的解包(解构)
# 将序列中的元素依次按顺序赋值给a,d,f等三个元素,f前带*表示将序列中除前两个以外的所有元素组成一个列表赋值给f
a, d, *f = my_tuple
print("a:", a)
print("d:", d)
print("f:", f)
q = 100
w = 200
# 通过解包来将q、w 两个变量的值进行交换,而不需要一个临时变量接收
q, w = w, q
print("q:", q, ",w:", w)
my_list = [11, 22, 33, 44, 55, 66, 77]
z, *x, c = my_list
print("z:", z, ",x:", x, ",c:", c)
|
"""
实现一个连续浮点数发生器FloatRange(类似range),
根据你给定范围和步长值产生一个列连续浮点数。
如:迭代FloatRange(2.0,4.0,0.2)可产生序列:
正向:3.0 -> 3.2 -> 3.4 -> 3.6 -> 3.8 -> 4.0
反向:4.0 -> 3.8 -> 3.6 -> 3.4 -> 3.2 -> 3.0
"""
class FloatRange:
def __init__(self, start, end, step=0.1):
self.start = start
self.end = end
self.step = step
def __iter__(self):
"""
实现正向迭代器
:return: 生成器
"""
t = self.start
while t <= self.end:
yield t
t += self.step
def __reversed__(self):
"""
实现反向迭代
:return: 生成器
"""
t = self.end
while t >= self.start:
yield t
t -= self.step
# 正向
for x in FloatRange(2.0, 4.0, 0.2):
print(x)
print("—" * 20)
# 反向
for x in reversed(FloatRange(2.0, 4.0, 0.2)):
print(x)
|
"""
某软件要求,从网络抓取各个城市气温信息,并依次显示:
北京:25~20
天津:17~22
长春:12~18
...
如果依次抓取所有城市田七在显示,显示第一个城市气温时,有很高的延时,
并且浪费存储空间。我们期望以‘用时访问’的策略,并且能把所有城市气温封装到一个对象里,
可用for语句进行迭代,如何解决?
解决方案:
1、实现一个迭代器对象WeatherIterator,next方法每次返回一个城市气温
2、实现一个可迭代对象WeatherIterable,__iter__方法返回一个迭代器对象
"""
import requests
from collections import Iterable, Iterator
class WeatherIterator(Iterator):
"""
自定义迭代器
"""
def __init__(self, cities):
self.cities = cities
self.index = 0
def __next__(self):
if self.index == len(self.cities):
raise StopIteration
city = self.cities[self.index]
self.index += 1
return WeatherIterator.get_weather(city)
@staticmethod
def get_weather(city):
response = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=%s" % city)
data = response.json()["data"]["forecast"][0]
return "%s: %s , %s" % (city, data["low"], data["high"])
class WeatherIterable:
def __init__(self, cities):
self.cities = cities
def __iter__(self):
"""
实现自定义迭代器
:return: 返回一个可迭代的自定义迭代器
"""
return WeatherIterator(self.cities)
for i in WeatherIterable(["上海", "长沙", "邵阳"]):
print(i)
|
# 编写一个程序,获取一个用户输入的整数,然后通过程序显示这个数是奇数还是偶数
# input_str=input("请输入一个整数:")
# to_int=int(input_str)
# if to_int % 2 ==0 :
# print("这是一个偶数:",to_int)
# else:
# print("这是一个奇数:",to_int)
# 编写一个程序,检查任意一个年份是否是闰年,如果一个年份可以被4整除不能被100整除,或者可以被400整除,这个年份就是闰年
# year=2016
# if (year % 4 ==0 and year % 100 !=0 ) or year % 400 ==0 :
# print("闰年")
# else:
# print("平年")
# 从键盘输入一个分数,等于100,奖励一辆BMW,80-99,奖励一台iPhone,60-79,奖励一本参考书,其他的,什么都没有
# score_input=input("输入分数:")
# score_int=int(score_input)
# if score_int==100:
# print("奖励一辆BMW")
# elif score_int>=80 and score_int<=99 :
# print("奖励一台iPhone")
# elif score_int>=60 and score_int<=79:
# print("奖励一本参考书")
# else:
# print("还需努力")
# 求100以内所有奇数之和
# sum_=0
# i=0
# while i<100:
# if i%2!=0 :
# sum_+=i
# i+=1
# print(sum_)
# 求100以内所有7的倍数之和,以及个数
# sum_=0
# count_sum=0
# i=0
# while i<100:
# if i%7==0:
# count_sum+=1
# sum_+=i
# i+=1
# print("个数:",count_sum,",和:",sum_)
# 打印乘法表
i = 1;
while i < 10:
j = 1
while j < 10:
if j > i: break
print(str(i), "*", str(j), "=", str((i * j)), end=" ")
j += 1
print()
i += 1
|
# 闭包就是能够读取其他函数内部变量的函数
# 形成闭包的条件
# 1、函数嵌套
# 2、将内部函数作为返回值返回
# 3、内部函数必须要使用到外部函数的变量
def make_averager():
# 创建一个列表,用来保存数值
nums = []
# 创建一个内部函数,用于计算平均值
def averager(n):
# 将n添加到列表中
nums.append(n)
print(nums)
# 求平均值
return sum(nums) / len(nums)
return averager;
# 调用外部函数
averager = make_averager()
print(averager(10)) # 10.0
print(averager(20)) # 15.0
print(averager(30)) # 20.0
print(averager(40)) # 25.0
print(averager(50)) # 30.0
# 使用 nonlocal 声明变量为父函数变量
def fn():
a = 10
def fn1(x):
nonlocal a
a = 20
def fn2():
nonlocal a
a = 30
return a * x
return fn2()
return fn1
f = fn()
print(f(20))
print(f(20))
|
"""
There is one way to reach the first step (One 1-weighted step).
There are two ways to reach the second step (Two 1-weighted steps or one 2-weighted step).
For step number n, we can reach it from step number n - 1 or step n - 2. This is a straightforward recursive solution.
"""
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
memo = {}
memo[1] = 1
memo[2] = 2
def helper(m):
if m not in memo:
memo[m] = helper(m - 1) + helper(m - 2)
return memo[m]
return helper(n) |
"""
Similar to staircase/steps problem - Store solution to each subproblem and add the parts to get the whole.
"""
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
memo = {}
memo[0] = 1
def tgt(n):
#print(n)
if n < 0:
return 0
if n in memo:
return memo[n]
else:
steps = [tgt(n - x) for x in nums]
memo[n] = sum(steps)
return memo[n]
return tgt(target)
|
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
def get_counts(word):
counts = [0] * 26
for c in word:
counts[ord(c) - ord('a')] += 1
return tuple(counts)
counts = defaultdict(list)
for word in strs:
cts = get_counts(word)
counts[cts].append(word)
return list(counts.values()) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def traverse(node):
if node == None:
return []
left = traverse(node.left)
right = traverse(node.right)
return left + [node.val] + right
inorder = traverse(root)
return all(inorder[i] < inorder[i + 1] for i in range(len(inorder) - 1))
|
"""A multi-producer, multi-consumer queue."""
from collections import deque
from time import time as _time
from pyuv import thread as _thread
__all__ = ['Empty', 'Full', 'Queue']
class Empty(Exception):
"""Exception raised by Queue.get(block=0)/get_nowait()."""
pass
class Full(Exception):
"""Exception raised by Queue.put(block=0)/put_nowait()."""
pass
class Queue(object):
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self.queue = deque()
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _thread.Mutex()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _thread.Condition()
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _thread.Condition()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.lock()
n = len(self.queue)
self.mutex.unlock()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.lock()
n = not len(self.queue)
self.mutex.unlock()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.lock()
n = 0 < self.maxsize == len(self.queue)
self.mutex.unlock()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.mutex.lock()
try:
if self.maxsize > 0:
if not block:
if len(self.queue) == self.maxsize:
raise Full
elif timeout is None:
while len(self.queue) == self.maxsize:
self.not_full.wait(self.mutex)
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while len(self.queue) == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.timedwait(self.mutex, remaining)
self.queue.append(item)
self.not_empty.signal()
finally:
self.mutex.unlock()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.mutex.lock()
try:
if not block:
if not len(self.queue):
raise Empty
elif timeout is None:
while not len(self.queue):
self.not_empty.wait(self.mutex)
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while not len(self.queue):
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.timedwait(self.mutex, remaining)
item = self.queue.popleft()
self.not_full.signal()
return item
finally:
self.mutex.unlock()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
|
# Truth test
#
# THE PROBLEM
#
# Assume the following value has already been entered into the
# Python interpreter, representing your trustworthiness
# and how old you purport to be
honest = False
age = 21
# Write an expression, or expressions, to create a string
# declaring your age, and whether you are telling the truth or not
# For example the string produced might be: 'My claim that I am 21 is False'
|
# Binary interpreter
#
# THE PROBLEM
#
# Assume the following list of binary digits (bits) has already been
# entered into the Python interpreter, representing a binary number
binary_number = [1, 0, 1, 0, 1]
# Write an expression, or expressions, to calculate the decimal value of that
# binary number and output it to screen
#
# NB: in decimal (aka base 10), each digit represents (from right to left):
# Ones, Tens, Hundreds ... eg 193:
# H | T | O
# 1 | 9 | 3
# or in other words:
# 10^2|10^1|10^0 ie 10 raised to a power
# 1 | 9 | 3
#
# which is (1 x 10^2) + (9 x 10^1) + (3 x 10^0) = 193
#
# Binary (aka base 2) numbers are all about 2 raised to a power eg 110:
# 2^2|2^1|2^0 ie 2 raised to a power
# 1 | 1 | 0
#
# 110 in binary therefore = (1 x 2^2) + (1 x 2^1) + (0 x 2^0) = 6 in decimal
|
"""
Artificial neural network
Using Python 3.6.2 64-bit
"""
# Perceptron (Threshold Logic Unit)
'''
Example of training a single TLU -
Taking iris preset from scikit package
'''
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import Perceptron
iris = load_iris()
X = iris.data[:, (2, 3)] # petal length, petal width
Y = (iris.target == 0).astype(np.int)
per_clf = Perceptron()
per_clf.fit(X, Y)
y_pred = per_clf.predict([[2, 0.5]])
# MLP (Multi-Layer Perceptron)
'''
Application could be in classifying products automatically -
We will use an example from MNIST dataset to classify objects
'''
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
print(keras.__version__)
'''
using keras to load the dataset.
every image is represented as a 28x28 array
pixel intensities are represented as integers from 0 to 255
'''
fashion_mnist = keras.datasets.fashion_mnist
(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()
X_train_full.shape
X_train_full.dtype
'''
we must scale the input features first by
splitting the dataset in to validation/train set, and scale the pixel intensity.
'''
X_valid, X_train = X_train_full[:5000] / 255.0, X_train_full[5000:] / 255.0
y_valid, y_train = y_train_full[:5000], y_train_full[5000:]
class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
class_names[y_train[0]]
'''
building the neural network
'''
model = keras.models.Sequential() # creating sequential model
model.add(keras.layers.Flatten(input_shape=[28, 28])) # flatten layer to convert each input image into 1D array
model.add(keras.layers.Dense(300, activation="relu")) # dense layer with 300 neurons with ReLU activation function
model.add(keras.layers.Dense(100, activation="relu")) # 100
model.add(
keras.layers.Dense(10, activation="softmax")) # 10 with softmax activation function (because classes are exclusive)
# checking out the model details
print(model.summary())
print(model.layers)
hidden1 = model.layers[1]
print(hidden1.name)
print(model.get_layer('dense') is hidden1)
# checking the weights and the biases within
weights, biases = hidden1.get_weights()
print(weights)
print(weights.shape)
print(biases)
print(biases.shape)
'''
compiling the model -
sparse_categorical_crossentropy because we have sparse labels (for each instance, there is just a target class index, 0 to 9)
sgd because we will train the model using simple Stochastic Gradient Descent
and since this is a classifier, we will measure the accuracy during train/eval.
'''
model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"])
history = model.fit(X_train, y_train, epochs=30, validation_data=(X_valid, y_valid))
model.evaluate(X_test, y_test)
'''
using the model to make the predictions
'''
X_new = X_test[:3]
y_proba = model.predict(X_new)
print(y_proba.round(2))
y_pred = model.predict_classes(X_new)
print(y_pred)
print(np.array(class_names)[y_pred])
y_new = y_test[:3]
print(y_new)
|
"""
# 짝수와 홀수
* 문제 설명
정수 num이 짝수일 경우 "Even"을 반환하고 홀수인 경우 "Odd"를 반환하는 함수, solution을 완성해주세요.
* 제한 조건
num은 int 범위의 정수입니다.
0은 짝수입니다.
"""
# 입출력 예
# +--------------+
# | num | return |
# |-----|--------|
# | 3 | "Odd" |
# | 4 | "Even" |
# +--------------+
def solution(num):
if num % 2 == 0: # num을 2로 나누었을 때 나머지가 0이라면
return "Even" # "Even"을 리턴
return "Odd" # 위의 if 문에 걸리지 않았다면 "Odd"을 리턴
|
secret_word = ["MACEDONIA", "SINGAPORE"]
blanks = ["********", "*********"]
lives = 5
def replace(secret_word, blanks, letter):
for i in range(len(secret_word)):
if letter == secret_word[i]:
blanks = blanks[0:i] + letter + blanks[i+1:]
return blanks
def guess():
answer = input("type your guess: ")
print("your guess is " + answer + "!")
return answer
def guess_result(secret_word, guess, blanks):
if guess == secret_word:
blanks = guess
print(blanks)
input("Your guess is correct! puzzle solved\n(press any key to continue)")
return blanks
elif (guess in list(secret_word)):
blanks = replace(secret_word, blanks, guess)
print(blanks)
input("Your letter guess is correct!\n(press any key to continue)")
return blanks
else:
print(blanks)
input("Incorrect guess!\n(press any key to continue)")
return blanks
def playgame(secret_word, blanks):
print(blanks)
for i in range(lives):
player_guess = guess()
blanks = guess_result(secret_word, player_guess, blanks)
if (blanks == secret_word):
input("-----PUZZLE SOLVED-----")
break
if (blanks != secret_word):
input("-----NO MORE LIVES-----\ngame over")
#######################################################################
for i in range(2):
print("\nPUZZLE " + str(i+1) + ": Guess the Country!")
playgame(blanks = blanks[i], secret_word = secret_word[i])
|
import json
def check_number():
"""Checking if the number is inside the favorite number file"""
filename = 'favorite_number.json'
try:
with open(filename) as f:
number = json.load(f)
except FileNotFoundError:
return None
else:
return number
def new_number():
filename = 'favorite_number.json'
number = input("What is your favorite number: ")
with open(filename, 'w') as f2:
json.dump(number, f2)
return number
def favorite_number():
number = check_number()
if number:
print(f"I know your favorite number! It's {number}!")
else:
fav_number = new_number()
print(f"Your favorite number is {fav_number}")
favorite_number() |
from random import randint, choice
class Die():
"""Rolls a dice."""
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
"""Rolling a dice fro 10 times between 1 and sides"""
for roll_num in range(10):
print(randint(1, self.sides))
# results = []
# d10 = Die(sides=10)
# d10.roll_die()
# for roll_num in range(10):
# result = d10.roll_die()
# results.append(result)
# print(results)
lottery = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 'l', 'a', 'u', 'r', 'e')
number = 0
print("Following letters or numbers are selected: ")
while number < 4:
number += 1
random = choice(lottery)
print(f"\t{random}")
|
with open('text_files/learning_python.txt') as file_object:
lines = file_object.readlines()
print("First:")
for line in lines:
line = line.strip()
print(f"\t{line.replace('python', 'java')}")
python_list = ''
for line in lines:
python_list += line.strip()
# # print("\nSecond:")
# # # print(lines)
# print("\nThird:")
# # print(python_list)
print(python_list.replace('python', 'java')) |
# name = input("Please enter your name: ")
# print(f"\nHello, {name}!")
prompt = "Tell us who you are, and we send a personalized message."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")
|
filename = 'guest.txt'
filename_2 = 'guest_book.txt'
poll = 'programming_poll.txt'
name = input("Please enter your name: ")
with open(filename, 'w') as file_object:
file_object.write(name)
with open(filename_2, 'w') as file_object_2:
print("\nWelcome in the Holiday Inn, please enter your name: ")
print("Write 'exit' to exit program.")
active = True
while active:
name = input("\tYour name: ")
if name == 'exit':
active = False
else:
file_object_2.write(f"{name}\n")
with open(poll, 'a') as file_poll:
print("\nWelcome to the poll! ** TO QUIT, TYPE 'stop' **")
print("What do you like about programming?")
active = True
while active:
answer = input("\tAnswer: ")
if answer == 'stop':
active = False
else:
file_poll.write(f"{answer}\n")
|
def make_shirt(size='large', text='I love python'):
print(f"The size of your shirt will be {size}, and have the text '{text}' written on it.")
make_shirt('medium', 'hello world!')
def describe_city(city, country="fairyland"):
print(f"{city} is in {country}.")
describe_city('brugge')
describe_city('sao paulo', 'brazil')
describe_city('berlin', 'germany') |
#Interfaz para Calculadora
#Importar funciones desde otro archivo
from funcionescalculadora import * #puedes seleccionar la funcion especifica
from raices import raices
print("Calculadora SAM\nIntroduce el numero de la operacion a hacer, o presiona Q para salir:")
print("[1.-Suma] [2.-Resta] [3.-Multiplicacion]\n[4.-Division] [5.-Pontencia] [6.-Modulo]\n[7.-Raices polinomio segundo grado]")
x = input("X= ")
while x != "Q":
if x == "1":
suma(x)
break
elif x == "2":
resta(x)
break
elif x == "3":
Multiplicacion(x)
break
elif x == "4":
divide(x)
break
elif x == "5":
Potencia(x)
break
elif x == "6":
modulo(x)
break
elif x == "7":
raices()
break
else:
print(f"{x} VALOR NO VALIDO")
print("-------------------------------------------")
x1 = input("Quieres reintentarlo? (y/n) ")
while x1 != "y" or "n":
if x1 == "y":
x = input("Introduce el numero de la operacion a hacer, o presiona Q para salir:")
break
elif x1 == "n":
print("Gracias por usar SAM")
x = "Q"
break
else:
print(f"{x1} valor no valido")
x1 = input("Quieres reintentarlo? (y/n) ")
print("End")
|
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run expand-intervals
# An interval of consecutive positive integers can be succinctly described as a tuple that contains first and last values. For example, the interval that contains the numbers 5, 6, 7, 8, 9 can be described as (5,9). Multiple intervals can be united together into iterable. Given an an iterable with intervals (guaranteed not to overlap with each other and to be listed in a sorted ascending order), create and return the list that contains all the integers contained by these intervals.
#
# Input:The iterable of tuples of two integers.
#
# Output:The iterable of integers.
#
# Precondition:Each element in the interval is an integer and
#
# The mission was taken from Python CCPS 109 Fall 2018. It’s being taught for Ryerson Chang School of Continuing Education byIlkka Kokkarinen
#
# See also:Create IntervalsMerge Intervals
#
#
# END_DESC
from typing import Iterable
def expand_intervals(items: Iterable) -> Iterable:
# your code here
return []
if __name__ == '__main__':
print("Example:")
print(list(expand_intervals([(1, 3), (5, 7)])))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(expand_intervals([(1, 3), (5, 7)])) == [1, 2, 3, 5, 6, 7]
assert list(expand_intervals([(1, 3)])) == [1, 2, 3]
assert list(expand_intervals([])) == []
assert list(expand_intervals([(1, 2), (4, 4)])) == [1, 2, 4]
print("Coding complete? Click 'Check' to earn cool rewards!") |
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run follow-instructions
# You’ve received a letter from a friend whom you haven't seen or heard from for a while. In this letter he gives you instructions on how to find a hidden treasure.
#
# In this mission you should follow a given list of instructions which will get you to a certain point on the map. A list of instructions is a string, each letter of this string points you in the direction of your next step.
#
# The letter "f" - tells you to move forward, "b" - backward, "l" - left, and "r" - right.
#
# It means that if the list of your instructions is "fflff" then you should move forward two times, make one step to the left and then again move two times forward.
#
# Now, let's imagine that you are in the position (0,0). If you move forward your position will change to (0, 1). If you move again it will be (0, 2). If your next step is to the left then your position will become (-1, 2). After the next two steps forward your coordinates will be (-1, 4)
#
# Your goal is to find your final coordinates. Like in our case they are (-1, 4)
#
# Input:A string.
#
# Output:A tuple (or list) of two ints
#
# Precondition:only chars f,b,l and r are allowed
#
#
# END_DESC
def follow(instructions):
x = 0
y = 0
regulations = {
'f': 1,
'b': -1,
'r': 1,
'l': -1
}
for c in instructions:
if c == 'r' or c == 'l':
x += regulations[c]
else:
y += regulations[c]
return x, y
if __name__ == '__main__':
print("Example:")
print(follow("fflff"))
# These "asserts" are used for self-checking and not for an auto-testing
assert follow("fflff") == (-1, 4)
assert follow("ffrff") == (1, 4)
assert follow("fblr") == (0, 0)
print("Coding complete? Click 'Check' to earn cool rewards!")
|
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run caps-lock
# Joe Palooka has fat fingers, so he always hits the “Caps Lock” key whenever he actually intends to hit the key “a” by itself. (When Joe tries to type in some accented version of “a” that needs more keystrokes to conjure the accents, he is more careful in the presence of such raffinated characters ([Shift] + [Char]) and will press the keys correctly.) Compute and return the result of having Joe type in the given text. The “Caps Lock” key affects only the letter keys from “a” to “z” , and has no effect on the other keys or characters. “Caps Lock” key is assumed to be initially off.
#
# Input:A string. The typed text.
#
# Output:A string. The showed text after being typed.
#
# The mission was taken from Python CCPS 109 Fall 2018. It is taught for Ryerson Chang School of Continuing Education byIlkka Kokkarinen
#
#
# END_DESC
def caps_lock(text: str) -> str:
result = ''
for idx, elem in enumerate(text.split('a')):
if idx % 2 == 0:
result += elem
else:
result += elem.upper()
return result
if __name__ == '__main__':
print("Example:")
print(caps_lock("Why are you asking me that?"))
# These "asserts" are used for self-checking and not for an auto-testing
assert caps_lock("Why are you asking me that?") == "Why RE YOU sking me thT?"
assert caps_lock("Always wanted to visit Zambia.") == "AlwYS Wnted to visit ZMBI."
print("Coding complete? Click 'Check' to earn cool rewards!")
|
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run counting-tiles
# Stephan needs some help building a circular landing zone using the ice square tiles for their new Ice Base. Before he converts the area to a construction place, Stephan needs to figure out how many square tiles he will need.
#
# Each square tile has size of 1x1 meters. You need to calculate how many whole and partial tiles are needed for a circle with a radius of N meters. The center of the circle will be at the intersection of four tiles. For example: a circle with a radius of 2 metres requires 4 whole tiles and 12 partial tiles.
#
# Input:The radius of a circle as a float
#
# Output:The quantities whole and partial tiles as a list with two integers -- [solid, partial].
#
# Precondition:
# 0 < radius ≤ 4
#
#
#
# END_DESC
def checkio(radius):
"""count tiles"""
return [0, 0]
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(2) == [4, 12], "N=2"
assert checkio(3) == [16, 20], "N=3"
assert checkio(2.1) == [4, 20], "N=2.1"
assert checkio(2.5) == [12, 20], "N=2.5" |
"""
622. Frog Jump
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.
If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.
Example
Example 1:
Given stones = [0,1,3,5,6,8,12,17]
Input:
[0,1,3,5,6,8,12,17]
Output:
true
Explanation:
There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,third stone at the 3rd unit, and so on...The last stone at the 17th unit.
Return true. The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:
Given stones = `[0,1,2,3,4,8,9,11]`
Input:
[0,1,2,3,4,8,9,11]
Output:
false
Explanation:
Return false. There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
Notice
The number of stones is ≥ 2 and is < 1100.
Each stone's position will be a non-negative integer < 2^31.
The first stone's position is always 0.
"""
class Solution:
def canCross(self, stones):
dp = {}
for s in stones:
dp[s] = set()
dp[0].add(0)
for s in stones:
for k in dp[s]:
if k - 1 > 0 and s + k - 1 in dp:
dp[s + k - 1].add(k - 1)
if k > 0 and s + k in dp:
dp[s + k].add(k)
if s + k + 1 in dp:
dp[s + k + 1].add(k + 1)
return len(dp[stones[-1]]) > 0
|
"""
544. Top k Largest Numbers
Given an integer array, find the top k largest numbers in it.
Example
Example1
Input: [3, 10, 1000, -99, 4, 100] and k = 3
Output: [1000, 100, 10]
Example2
Input: [8, 7, 6, 5, 4, 3, 2, 1] and k = 5
Output: [8, 7, 6, 5, 4]
"""
import heapq
class Solution:
def topk(self, nums, k):
heap = []
for n in nums:
if len(heap) == k:
heapq.heappushpop(heap, -n)
else:
heapq.heappush(heap, -n)
result = []
while heap:
result.append(heapq.heappop(heap))
result.reverse()
return result
|
"""
109. Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Example
Example 1:
Input the following triangle:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
Output: 11
Explanation: The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Example 2:
Input the following triangle:
[
[2],
[3,2],
[6,5,7],
[4,4,8,1]
]
Output: 12
Explanation: The minimum path sum from top to bottom is 12 (i.e., 2 + 2 + 7 + 1 = 12).
Notice
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
"""
class Solution:
def minimumTotal(self, triangle):
if not triangle:
return 0
i = len(triangle) - 1
memo = triangle[i][:]
while i > 0:
i -= 1
for j in range(i + 1):
memo[j] = triangle[i][j] + min(memo[j], memo[j + 1])
return memo[0]
if __name__ == '__main__':
triangle = [
[2],
[3, 2],
[6, 5, 7],
[4, 4, 8, 1]
]
print(Solution().minimumTotal(triangle))
|
"""
57. 3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Example
Example 1:
Input:[2,7,11,15]
Output:[]
Example 2:
Input:[-1,0,1,2,-1,-4]
Output: [[-1, 0, 1],[-1, -1, 2]]
Notice
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
"""
class Solution:
def threeSum(self, numbers):
numbers.sort()
result = []
for i in range(len(numbers) - 1):
if i and numbers[i - 1] == numbers[i]:
continue
self.twoSum(numbers, i + 1, len(numbers) - 1, -numbers[i], result)
return result
def twoSum(self, numbers, start, end, target, result):
while start < end:
if numbers[start] + numbers[end] == target:
result.append([-target, numbers[start], numbers[end]])
start += 1
end -= 1
while start < end and numbers[start - 1] == numbers[start]:
start += 1
while start < end and numbers[end + 1] == end:
end -= 1
elif numbers[start] + numbers[end] > target:
end -= 1
else:
start += 1
def main():
s = Solution()
numbers = [-1,0,1,2,-1,-4]
print(s.threeSum(numbers))
if __name__ == '__main__':
main()
|
"""
153. Combination Sum II
Given an array num and a number target. Find all unique combinations in num where the numbers sum to target.
Example
Example 1:
Input: num = [7,1,2,5,1,6,10], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
Example 2:
Input: num = [1,1,1], target = 2
Output: [[1,1]]
Explanation: The solution set must not contain duplicate combinations.
Notice
Each number in num can only be used once in one combination.
All numbers (including target) will be positive integers.
Numbers in a combination a1, a2, … , ak must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak)
Different combinations can be in any order.
The solution set must not contain duplicate combinations.
"""
class Solution:
def combinationSum2(self, num, target):
num.sort()
result = []
self.helper(num, 0, [], target, result)
return result
def helper(self, num, i, prev, target, result):
if i == len(num):
return
prev_sum = sum(prev)
if prev_sum + num[i] == target:
result.append(prev + [num[i]])
elif prev_sum + num[i] < target:
next_non_dup = i
while next_non_dup < len(num) and num[i] == num[next_non_dup]:
next_non_dup += 1
cur = list(prev)
cur_sum = prev_sum
while i < next_non_dup:
cur_sum = cur_sum + num[i]
cur = cur + [num[i]]
if cur_sum == target:
result.append(cur)
break
if cur_sum < target:
self.helper(num, next_non_dup, cur, target, result)
i += 1
else:
break
self.helper(num, next_non_dup, prev, target, result)
def main():
s = Solution()
num = [1, 1, 1, 2, 2, 2, 2, 3, 3]
target = 7
print(s.combinationSum2(num, target))
if __name__ == '__main__':
main()
|
"""
159. Find Minimum in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
Example
Example 1:
Input:[4, 5, 6, 7, 0, 1, 2]
Output:0
Explanation:
The minimum value in an array is 0.
Example 2:
Input:[2,1]
Output:1
Explanation:
The minimum value in an array is 1.
Notice
You can assume no duplicate exists in the array.
"""
from typing import List
class Solution:
"""
@param nums: a rotated sorted array
@return: the minimum number in the array
"""
def findMin(self, nums: List[int]) -> int:
if not nums:
return -1
start, end = 0, len(nums) - 1
while start < end - 1:
print(start, end)
mid = (end + start) // 2
if nums[mid] > nums[end]:
start = mid
else:
end = mid
return min(nums[start], nums[end])
def main():
s = Solution()
x = [1, 2]
print(s.findMin(x))
if __name__ == "__main__":
main()
|
"""
71. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
Example
Example 1:
Input:{1,2,3}
Output:[[1],[3,2]]
Explanation:
1
/ \
2 3
it will be serialized {1,2,3}
Example 2:
Input:{3,9,20,#,#,15,7}
Output:[[3],[20,9],[15,7]]
Explanation:
3
/ \
9 20
/ \
15 7
it will be serialized {3,9,20,#,#,15,7}
"""
from typing import List
from collections import deque
"""
Definition of TreeNode:
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: A Tree
@return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
"""
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
tree_queue = deque()
tree_queue.append(root)
tree_queue.append('#')
res = []
zigzag = True
cur_queue = deque()
while tree_queue:
cur = tree_queue.popleft()
if cur == '#':
res.append(list(cur_queue))
cur_queue = deque()
zigzag = not zigzag
if tree_queue:
tree_queue.append('#')
else:
if zigzag:
cur_queue.append(cur.val)
else:
cur_queue.appendleft(cur.val)
if cur.left:
tree_queue.append(cur.left)
if cur.right:
tree_queue.append(cur.right)
return res
def main():
s = Solution()
graph = []
dict = {}
string = "-20,-2,6#-19,13#-18#-17,1,2,-10,-11#-16,1#-15,-13,11,1,-7#-14,-13,-9,3,18#-13,-15,-14#-12,-2#-11,-17,5#-10,-17#-9,5,-14,-1,0#-8,2#-7,16,-5,-15#-6#-5,14,7,-7#-4,-2#-3,14#-2,-12,-20,8,-4,12#-1,-9#0,-9#1,-16,-17,-15#2,12,-8,-17#3,-14,13#4,4,4#5,-9,17,-11#6,-20,15,8#7,-5#8,-2,6,11#9,17#10,16#11,18,-15,8#12,2,-2#13,-19,3#14,-5,-3#15,6#16,-7,10#17,9,5#18,11,-14#19"
for i in string.split('#'):
items = i.split(',')
cur = UndirectedGraphNode(int(items[0]))
dict[cur.label] = cur
for i in string.split('#'):
items = i.split(',')
for j in items[1:]:
# print(items)
dict[int(items[0])].neighbors.append(dict[int(j)])
graph = list(dict.values())
print(s.connectedSet(graph))
if __name__ == '__main__':
main()
|
"""
32. Minimum Window Substring
Given two strings source and target. Return the minimum substring of source which contains each char of target.
Example
Example 1:
Input: source = "abc", target = "ac"
Output: "abc"
Example 2:
Input: source = "adobecodebanc", target = "abc"
Output: "banc"
Explanation: "banc" is the minimum substring of source string which contains each char of target "abc".
Example 3:
Input: source = "abc", target = "aa"
Output: ""
Explanation: No substring contains two 'a'.
Challenge
O(n) time
Notice
If there is no answer, return "".
You are guaranteed that the answer is unique.
target may contain duplicate char, while the answer need to contain at least the same number of that char.
"""
from typing import Dict
class Solution:
"""
@param source : A string
@param target: A string
@return: A string denote the minimum window, return "" if there is no such a string
"""
def get_string_dict(self, s: str) -> Dict:
result = {}
for c in s:
if c in result:
result[c] += 1
else:
result[c] = 1
return result
def check_if_valid(self, dic_s: Dict, dic_t: Dict) -> bool:
for k in dic_t:
if k not in dic_s or dic_t[k] > dic_s[k]:
return False
return True
def minWindow(self, source: str, target: str) -> str:
if not source or not target:
return ""
dic_source = self.get_string_dict(source)
dic_target = self.get_string_dict(target)
if not self.check_if_valid(dic_source, dic_target):
return ""
n = len(source)
result = (0, n)
for i in range(n - len(target) + 1):
if source[i] not in dic_target:
continue
if not self.check_if_valid(dic_source, dic_target):
break
j = n
while i + len(target) - 1 < j <= n:
if source[j - 1] not in dic_target:
j -= 1
continue
dic_source[source[j - 1]] -= 1
if not self.check_if_valid(dic_source, dic_target):
if j - i < result[1] - result[0]:
result = (i, j)
while j <= n:
if source[j - 1] in dic_target:
dic_source[source[j - 1]] += 1
j += 1
break
j -= 1
dic_source[source[i]] -= 1
return source[result[0]: result[1]]
def main():
s = Solution()
source = "adobecodebanc"
target = "abc"
print(s.minWindow(source, target))
if __name__ == '__main__':
main()
|
"""
585. Maximum Number in Mountain Sequence
Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top.
Example
Example 1:
Input: nums = [1, 2, 4, 8, 6, 3]
Output: 8
Example 2:
Input: nums = [10, 9, 8, 7],
Output: 10
"""
from typing import List
class Solution:
"""
@param nums: An integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def mountainSequence(self, nums: List[int]) -> int:
if not nums:
return -1
i, j = 0, len(nums)
while i < j:
mid_ind = (i + j) // 2
if mid_ind == 0 or mid_ind == len(nums) - 1\
or (nums[mid_ind] > nums[mid_ind - 1] and nums[mid_ind] > nums[mid_ind + 1]):
return nums[mid_ind]
if nums[mid_ind - 1] > nums[mid_ind]:
j = mid_ind
else:
i = mid_ind + 1
def main():
s = Solution()
nums = [60]
print(s.mountainSequence(nums))
if __name__ == '__main__':
main()
|
"""
Given a string(Given in the way of char array) and an offset, rotate the string by offset in place. (rotate from left to right).
Example
Example 1:
Input: str="abcdefg", offset = 3
Output: str = "efgabcd"
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes "efgabcd".
Example 2:
Input: str="abcdefg", offset = 0
Output: str = "abcdefg"
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes "abcdefg".
Example 3:
Input: str="abcdefg", offset = 1
Output: str = "gabcdef"
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes "gabcdef".
Example 4:
Input: str="abcdefg", offset =2
Output: str = "fgabcde"
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes "fgabcde".
Example 5:
Input: str="abcdefg", offset = 10
Output: str = "efgabcd"
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes "efgabcd".
Challenge
Rotate in-place with O(1) extra memory.
Notice
offset >= 0
the length of str >= 0
"""
class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, s, offset):
if not s:
return s
offset = offset % len(s)
temp = s[len(s) - offset:] + s[:len(s) - offset]
s = temp
return s
def main():
s = Solution()
print(s.rotateString('abcdefg', 3))
print(s.rotateString('abcdefg', 0))
print(s.rotateString('abcdefg', 1))
print(s.rotateString('abcdefg', 2))
print(s.rotateString('cppjavapy', 25))
if __name__ == '__main__':
main()
|
"""
115. Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
Example
Example 1:
Input: [[0]]
Output: 1
Example 2:
Input: [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Explanation:
Only 2 different path.
Notice
m and n will be at most 100.
"""
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
if not obstacleGrid or not obstacleGrid[0] or obstacleGrid[0][0] == 1:
return 0
m, n = len(obstacleGrid), len(obstacleGrid[0])
if obstacleGrid[m - 1][n - 1] == 1:
return 0
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 1:
obstacleGrid[i][j] = 0
elif i == 0 and j == 0:
obstacleGrid[i][j] = 1
else:
obstacleGrid[i][j] = (obstacleGrid[i - 1][j] if i - 1 >= 0 else 0) + (obstacleGrid[i][j - 1] if j - 1 >= 0 else 0)
return obstacleGrid[m - 1][n - 1]
print(Solution().uniquePathsWithObstacles([[0,0],[0,0],[0,0],[1,0],[0,0]]))
|
"""
685. First Unique Number in Data Stream
Given a continuous stream of data, write a function that returns the first unique number (including the terminating number) when the terminating number arrives. If the unique number is not found, return -1.
Example
Example1
Input:
[1, 2, 2, 1, 3, 4, 4, 5, 6]
5
Output: 3
Example2
Input:
[1, 2, 2, 1, 3, 4, 4, 5, 6]
7
Output: -1
Example3
Input:
[1, 2, 2, 1, 3, 4]
3
Output: 3
"""
class LinkedNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def helpPrinter(self, dummy, n):
print('----------', n, '---------')
cur = dummy
while cur.next:
print(cur.next.val)
cur = cur.next
def firstUniqueNumber(self, nums, number):
dummy = LinkedNode(-1)
unique_map_to_prev = {}
tail = dummy
visited = set()
for n in nums:
if n not in visited:
node = LinkedNode(n)
tail.next = node
unique_map_to_prev[n] = tail
tail = tail.next
visited.add(n)
elif n in unique_map_to_prev:
node = unique_map_to_prev[n].next
if node == tail:
tail = unique_map_to_prev[n]
tail.next = None
else:
unique_map_to_prev[node.next.val] = unique_map_to_prev[n]
unique_map_to_prev[n].next = node.next
del unique_map_to_prev[n]
if n == number:
return dummy.next.val
# self.helpPrinter(dummy, n)
# print([unique_map_to_prev[u].val for u in unique_map_to_prev])
return -1
|
"""
138. Subarray Sum
Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.
Example
Example 1:
Input: [-3, 1, 2, -3, 4]
Output: [0, 2] or [1, 3].
Explanation: return anyone that the sum is 0.
Example 2:
Input: [-3, 1, -4, 2, -3, 4]
Output: [1,5]
Notice
There is at least one subarray that it's sum equals to zero.
"""
class Solution:
def subarraySum(self, nums):
n = len(nums)
sum = 0
dict = {}
for i in range(n):
sum += nums[i]
if sum == 0:
return [0, i]
if sum in dict:
return [dict[sum] + 1, i]
dict[sum] = i
|
"""
86. Binary Search Tree Iterator
Design an iterator over a binary search tree with the following rules:
Elements are visited in ascending order (i.e. an in-order traversal)
next() and hasNext() queries run in O(1) time in average.
Example
Example 1
Input: {10,1,11,#,6,#,12}
Output: [1, 6, 10, 11, 12]
Explanation:
The BST is look like this:
10
/\
1 11
\ \
6 12
You can return the inorder traversal of a BST [1, 6, 10, 11, 12]
Example 2
Input: {2,1,3}
Output: [1,2,3]
Explanation:
The BST is look like this:
2
/ \
1 3
You can return the inorder traversal of a BST tree [1,2,3]
Challenge
Extra memory usage O(h), h is the height of the tree.
Super Star: Extra memory usage O(1)
"""
from typing import List
"""
Definition of TreeNode:
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class BSTIterator:
"""
@param: root: The root of binary tree.
"""
def __init__(self, root):
self.stack = []
node = root
while node:
self.stack.append(node)
node = node.left
"""
@return: True if there has next node, or false
"""
def hasNext(self):
return bool(self.stack)
"""
@return: return next node
"""
def next(self):
temp = self.stack.pop()
self.helper(temp)
return temp
def helper(self, node):
node = node.right
while node:
self.stack.append(node)
node = node.left
def main():
s = Solution()
A = [1, 2, 3, 4, 5, 6, 7, 8, 10, 100, 150, 156, 179]
target = 9
k = 12
print(s.kClosestNumbers(A, target, k))
if __name__ == '__main__':
main()
|
"""
192. Wildcard Matching
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example
Example 1
Input:
"aa"
"a"
Output: false
Example 2
Input:
"aa"
"aa"
Output: true
Example 3
Input:
"aaa"
"aa"
Output: false
Example 4
Input:
"aa"
"*"
Output: true
Explanation: '*' can replace any string
Example 5
Input:
"aa"
"a*"
Output: true
Example 6
Input:
"ab"
"?*"
Output: true
Explanation: '?' -> 'a' '*' -> 'b'
Example 7
Input:
"aab"
"c*a*b"
Output: false
"""
class Solution:
def isMatch(self, s, p):
memo = {}
result = self.helper(s, 0, p, 0, memo)
return result
def helper(self, s, i, p, j, memo):
if (i, j) in memo:
return memo[(i, j)]
if j >= len(p):
result = i >= len(s)
elif i >= len(s) and j < len(p):
result = True
while j < len(p):
if p[j] != '*':
result = False
break
j += 1
else:
if p[j] == '*':
result = self.helper(s, i, p, j + 1, memo) or self.helper(s, i + 1, p, j, memo)
else:
result = (s[i] == p[j] or p[j] == '?') and self.helper(s, i + 1, p, j + 1, memo)
memo[(i, j)] = result
return result
if __name__ == '__main__':
print(Solution().isMatch('bbabacccbcbbcaaab', '*a*b??b*b'))
|
"""
597. Subtree with Maximum Average
Given a binary tree, find the subtree with maximum average. Return the root of the subtree.
Example
Example 1
Input:
{1,-5,11,1,2,4,-2}
Output:11
Explanation:
The tree is look like this:
1
/ \
-5 11
/ \ / \
1 2 4 -2
The average of subtree of 11 is 4.3333, is the maximun.
Example 2
Input:
{1,-5,11}
Output:11
Explanation:
1
/ \
-5 11
The average of subtree of 1,-5,11 is 2.333,-5,11. So the subtree of 11 is the maximun.
Notice
LintCode will print the subtree which root is your return node.
It's guaranteed that there is only one subtree with maximum average.
"""
from typing import List
from collections import deque
"""
Definition of TreeNode:
"""
import sys
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
def findSubtree2(self, root):
if not root:
return None
else:
return self.helper(root)[3]
# return (cur_count, cur_sum, max_avg, node)
def helper(self, root):
if not root.left and not root.right:
return 1, root.val, root.val, root
cur_avg, cur_sum, cur_count = root.val, root.val, 1
(left_count, left_sum, left_max, left_node) = self.helper(root.left) if root.left else (0, 0, -sys.maxsize, None)
(right_count, right_sum, right_max, right_node) = self.helper(root.right) if root.right else (0, 0, -sys.maxsize, None)
cur_count += left_count + right_count
cur_sum += left_sum + right_sum
cur_avg = cur_sum / cur_count
result_node = root if cur_avg > left_max and cur_avg > right_max else left_node if left_max > right_max else right_node
return cur_count, cur_sum, max(left_max, right_max, cur_avg), result_node
def main():
s = Solution()
n = 1
edges = []
print(s.validTree(n, edges))
if __name__ == '__main__':
main()
|
"""
545. Top k Largest Numbers II
Implement a data structure, provide two interfaces:
add(number). Add a new number in the data structure.
topk(). Return the top k largest numbers in this data structure. k is given when we create the data structure.
Example
Example1
Input:
s = new Solution(3);
s.add(3)
s.add(10)
s.topk()
s.add(1000)
s.add(-99)
s.topk()
s.add(4)
s.topk()
s.add(100)
s.topk()
Output:
[10, 3]
[1000, 10, 3]
[1000, 10, 4]
[1000, 100, 10]
Explanation:
s = new Solution(3);
>> create a new data structure, and k = 3.
s.add(3)
s.add(10)
s.topk()
>> return [10, 3]
s.add(1000)
s.add(-99)
s.topk()
>> return [1000, 10, 3]
s.add(4)
s.topk()
>> return [1000, 10, 4]
s.add(100)
s.topk()
>> return [1000, 100, 10]
Example2
Input:
s = new Solution(1);
s.add(3)
s.add(10)
s.topk()
s.topk()
Output:
[10]
[10]
Explanation:
s = new Solution(1);
>> create a new data structure, and k = 1.
s.add(3)
s.add(10)
s.topk()
>> return [10]
s.topk()
>> return [10]
"""
import heapq
class Solution:
def __init__(self, k):
self.data = []
self.capacity = k
def add(self, num):
if len(self.data) == self.capacity:
heapq.heappushpop(self.data, num)
else:
heapq.heappush(self.data, num)
def topk(self):
return heapq.nlargest(self.capacity, self.data)
|
"""
603. Largest Divisible Subset
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
Example
Example 1:
Input: nums = [1,2,3],
Output: [1,2] or [1,3]
Example 2:
Input: nums = [1,2,4,8],
Output: [1,2,4,8]
Notice
If there are multiple solutions, return any subset is fine.
"""
class Solution:
def largestDivisibleSubset(self, nums):
nums.sort()
dp = [[_] for _ in nums]
max_array = [] if not dp[0] else dp[0]
for i in range(len(nums) - 1, -1, -1):
for j in range(i + 1, len(nums)):
if nums[j] % nums[i] == 0 and len(dp[i]) - 1 < len(dp[j]):
dp[i] = [dp[i][0]] + dp[j]
max_array = dp[i] if len(dp[i]) > len(max_array) else max_array
return max_array
print(Solution().largestDivisibleSubset([3,6,9,27,81,22,24,56,243,486,726,18,36,72])) |
"""
539. Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example
Example 1:
Input: nums = [0, 1, 0, 3, 12],
Output: [1, 3, 12, 0, 0].
Example 2:
Input: nums = [0, 0, 0, 3, 1],
Output: [3, 1, 0, 0, 0].
Notice
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
class Solution:
"""
@param nums: an integer array
@return: nothing
"""
def moveZeroes(self, nums):
i, j = 0, 0
while i < len(nums):
while i < len(nums) and nums[i] != 0:
i += 1
if i >= len(nums) - 1:
break
j = i + 1 if i >= j else j
while j < len(nums) and nums[j] == 0:
j += 1
if j == len(nums):
break
nums[i] = nums[j]
nums[j] = 0
i += 1
def main():
s = Solution()
A = [5, 4, 3, 2, 1]
print(s.findPeak(A))
if __name__ == '__main__':
main()
|
"""
495. Implement Stack
Implement a stack. You can use any data structure inside a stack except stack itself to implement it.
Example
Example 1:
Input:
push(1)
pop()
push(2)
top() // return 2
pop()
isEmpty() // return true
push(3)
isEmpty() // return false
Example 2:
Input:
isEmpty()
"""
class Stack:
stack = []
def push(self, x):
self.stack.append(x)
def pop(self):
self.stack.pop()
def top(self):
return self.stack[-1]
def isEmpty(self):
return not self.stack
|
# anthor: zhangwei time:2020/11/26
# 内置函数range()
r = range(10)
print(r)
print(list(r))
r = range(1, 10) # 不包含10
print(list(r))
r = range(1, 10, 3)
print(list(r))
print(10 in r)
print(7 in r)
# 关于range类型的优点:不管range对象表示的整数序列有多长,所有对象占用的内存空间都是相同的,只需要最多存储3个数据
# 只有当用到range对象时,才会去计算序列中的相关元素 |
# -*- coding: utf-8 -
#
# This file is part of offset. See the NOTICE for more information.
import multiprocessing
import os
import time
def getmaxthreads():
if 'OFFSET_MAX_THREADS' in os.environ:
return int(os.environ['OFFSET_MAX_THREADS'])
n = 0
try:
n = multiprocessing.cpu_count()
except NotImplementedError:
pass
# use a minimum of 2 threads
return max(n, 2)
def nanotime(s=None):
""" convert seconds to nanoseconds. If s is None, current time is
returned """
if s is not None:
return s * 1000000000
return time.time() * 1000000000
def from_nanotime(n):
""" convert from nanotime to seconds """
return n / 1.0e9
# TODO: implement this function with libc nanosleep function when
# available.
def nanosleep(n):
time.sleep(from_nanotime(n))
|
import time
# MERGE SORT
def metricas_mergesort(vetor, ordem):
inicio = time.time()
mergesort(vetor)
fim = time.time()
print("Tempo (ms) vetor " + ordem + ": " + str(round(fim-inicio, 6)))
def mergesort(vetor):
if len(vetor)>1:
meio = len(vetor)//2
esquerda = vetor[:meio]
direita = vetor[meio:]
mergesort(esquerda)
mergesort(direita)
i, j, k = 0, 0, 0
while i < len(esquerda) and j < len(direita):
if esquerda[i] < direita[j]:
vetor[k]=esquerda[i]
i=i+1
else:
vetor[k]=direita[j]
j=j+1
k=k+1
while i < len(esquerda):
vetor[k]=esquerda[i]
i=i+1
k=k+1
while j < len(direita):
vetor[k]=direita[j]
j=j+1
k=k+1 |
def avg(x):
total = 0
try:
for i in range(0, len(x)):
total = total + x[i]
return total / len(x)
except ZeroDivisionError:
return "No values."
except:
return "Error, not all numbers"
|
import numpy as np
from l5_data_prep import features, targets, features_test, targets_test
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1 / (1 + np.exp(-x))
# Use to same seed to make debugging easier
np.random.seed(42)
n_records, n_features = features.shape
last_loss = None
# Initialize weights
weights = np.random.normal(scale=1 / n_features**.5, size=n_features)
# Neural Network hyperparameters
epochs = 1000
learnrate = 0.25
for e in range(epochs):
del_w = np.zeros(weights.shape)
for x, y in zip(features.values, targets):
# Loop through all records, x is the input, y is the target
# Making a forward pass along with the activation function
output = sigmoid(np.dot(x,y))
# Calculating MSE
error = (y - output)
# Calculating Error term as error * f(h)*(1-f(h))
# Sigmoid prime: f(h)*(1-f(h)
error_term = error * (output * (1-output))
# Calculating delta Weights
del_w += error_term * x
# Update weights using the learning rate and the average change in weights
weights += (learnrate * del_w) / len(x)
# Printing out the mean square error on the training set
if e % (epochs / 10) == 0:
out = sigmoid(np.dot(features, weights))
loss = np.mean((out - targets) ** 2)
if last_loss and last_loss < loss:
print("Train loss: ", loss, " WARNING - Loss Increasing")
else:
print("Train loss: ", loss)
last_loss = loss
# Calculate accuracy on test data
tes_out = sigmoid(np.dot(features_test, weights))
predictions = tes_out > 0.5
accuracy = np.mean(predictions == targets_test)
assert round(accuracy,1) == 0.7
print("Prediction accuracy: {:.3f}".format(accuracy)) |
"""
Odd or Even?
https://www.codewars.com/kata/5949481f86420f59480000e7/train/python
Given a list of integers, determine whether the sum of its elements is odd or even.
Give your answer as a string matching "odd" or "even".
If the input array is empty consider it as: [0] (array with a zero).
Input: [0]
Output: "even"
Input: [0, 1, 4]
Output: "odd"
Input: [0, -1, -5]
Output: "even"
"""
def odd_or_even(arr):
return "odd" if sum(arr)&1 else "even"
print(odd_or_even([0, 1, 2]))
# odd
print(odd_or_even([0, 1, 3]))
# even
print(odd_or_even([1023, 1, 2]))
# even
print(odd_or_even([0, -1, -5]))
# even |
"""
Grasshopper- Grade book
https://www.codewars.com/kata/55cbd4ba903825f7970000f5/train/python
Complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.
Numerical Score Letter Grade
90 <= score <= 100 'A'
80 <= score < 90 'B'
70 <= score < 80 'C'
60 <= score < 70 'D'
0 <= score < 60 'F'
Tested values are all between 0 and 100. Theres is no need to check for negative values or values greater than 100.
"""
#round takes a number, required and an optional second argument digits/decimals to return
#round(number, digits)
#mean() functoion is used to calculate mean/avg from a LIST of numbers
import statistics
def get_grade(s1, s2, s3):
# Code here
# first solution using round
# score = round((s1 + s2 + s3)/3,2)
#second solution using mean() from statistics
score_list = [s1,s2,s3]
score = statistics.mean(score_list)
if 90 <= score <= 100:
return 'A'
elif 80 <= score < 90:
return 'B'
elif 70 <= score < 80:
return 'C'
elif 60 <= score < 70:
return 'D'
else:
return 'F'
def get_grade2(s1,s2,s3):
score_list = [s1,s2,s3]
score = statistics.mean(score_list)
return 'A' if 90 <= score <= 100 else 'B' if 80 <= score < 90 else 'C' if 70 <= score < 80 else 'D' if 60 <= score < 70 else 'F'
print(get_grade(95, 90, 93)) #A
print(get_grade(100, 85, 96)) #A
print(get_grade2(95, 90, 93)) #A
print(get_grade2(100, 85, 96)) #A
# CODEWAR SOLUTIONS
# def get_grade(s1, s2, s3):
# return {6:'D', 7:'C', 8:'B', 9:'A', 10:'A'}.get((s1 + s2 + s3) / 30, 'F')
# The get() method returns the value of the item with the specified key from a dictionary
# keyname is required; value is optionl
# Syntax: dictionary.get(key, value)
# def get_grade(*s):
# return 'FFFFFFDCBAA'[sum(s)//30]
# def get_grade(*args):
# mean = sum(args) / len(args)
# return scores.get(mean // 10, 'F') |
"""
The Old Switcheroo
https://www.codewars.com/kata/55d410c492e6ed767000004f/train/python
Write a function vowel_2_index
that takes in a string and replaces all the vowels [a,e,i,o,u] with their respective positions within that string.
E.g:
vowel_2_index('this is my string') == 'th3s 6s my str15ng'
vowel_2_index('Codewars is the best site in the world') == 'C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld'
vowel_2_index('') == ''
Your function should be case insensitive to the vowels.
"""
"""
enumerate() function assigns an index to each item in an iterable object that can be used to reference
the item later
Syntax: enumerate(iterable, start=0)
"""
"""
index() function searched for a given element from start of LIST and returns the lowest index where element appears
Syntax: list_name.index(element, start, end)
element - element whose lowest index will be returned
start (optional) - position where search begins
end (optional) - position where search ends
"""
def vowel_2_index(string):
result = []
for index in range(len(string)):
if string[index] in 'aeiouAEIOU':
result.append(str(index+1))
else:
result.append(string[index])
return ''.join(result)
print(vowel('this is my string'))
# CODEWARS SOLUTIONS
# def vowel_2_index(string):
# vowels = 'aeiouAEIOU'
# return ''.join(x if x not in vowels else str(n + 1) for n,x in enumerate(string))
# import re
# def vowel_2_index(string):
# return re.sub("[aeiou]",lambda m:str(m.end()),string,0,re.I) |
"""
Highest and Lowest
https://www.codewars.com/kata/554b4ac871d6813a03000035/train/python
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
Example:
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"
Notes:
All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space, and highest number is first.
"""
# map(function, iterable)
# map: function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple, etc)
# function: a function map passes on each element of given iterable
# iterable: iterable that is mapped
# Note: You can pass one or more iterable to the map() function
def high_and_low(numbers):
#split string into list to make iterable
#interpolate min and max of list_num and convert to integer
return f"{max([int(num) for num in numbers.split()])} {min([int(num) for num in numbers.split()])}"
print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
# def high_and_low(numbers): #z.
# nn = [int(s) for s in numbers.split(" ")]
# return "%i %i" % (max(nn),min(nn))
# def high_and_low(numbers):
# n = map(int, numbers.split(' '))
# return "{} {}".format(max(n), min(n))
# def high_and_low(numbers):
# return " ".join(x(numbers.split(), key=int) for x in (max, min)) |
"""
Return Odd No Matter What
https://www.codewars.com/kata/5f882dcc272e7a00287743f5/train/python
Given the integer n return odd numbers as they are, but subtract 1 from even numbers.
Note: Your solution should be 36 or less characters long.
"""
# Question: what is a shorter way to check odd/even numbers?
"""
bitwise 'and' operator if x is odd, x&1 returns true/1
if x is even, x&1 returns false/0
If last bit is 1 then number is odd, otherwise always even.
input : 5 // odd
00000101
& 00000001
--------------
00000001
--------------
input : 8 //even
00001000
& 00000001
--------------
00000000
--------------
"""
# Question: Is there a way to return a value without using return keyword?
# Use lambda AKA "anonymous function"
# Syntax: function_name = lambda argument:expression if condition else False
always_odd=lambda n:n if n&1else n-1
# refactor code: always_odd=lambda n: n-1-(n&1)
print(always_odd(2), 1)
print(always_odd(8), 7)
#CODEWARS SOLUTION
# always_odd=lambda n:n-(n%2==0)
# def always_odd(n): return n-(1-n%2)
# def always_odd(n):return n-(not n%2)
# always_odd=lambda n:n-1|1
# always_odd=lambda n:n-~n%2
# always_odd=lambda _:[_-1,_][_%2]
# always_odd=lambda n:n-(n&1<1)
num = lambda x: x&1
print(bool(num(3))) |
"""
Recursion 101
https://www.codewars.com/kata/5b752a42b11814b09c00005d/train/python
You are given two positive integers a and b.
Your task will be to apply the following operations:
i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii);
ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to step (iii);
iii) If b ≥ 2*a, set b = b - 2*a, and repeat step (i). Otherwise, return [a,b].
a and b will both be lower than 10E8.
"""
def solve(a,b):
if a == 0 or b == 0:
return [a,b]
elif a >= (2 * b):
a = a - (2 * b)
solve(a-1, b)
elif b >= (2 * a):
b = b - (2 * a)
solve(a, b-1)
return [a, b]
print(solve(6,19))
# [6,7]
print(solve(2,1))
#[ 0,1]
print(solve(22,5))
# [0,1] |
"""
Quarter of The Year
https://www.codewars.com/kata/5ce9c1000bab0b001134f5af/train/python
Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer number.
For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter.
"""
# break down the months (as numbers) into quarters & save inside variable
# if argument passed in matches number inside quarter, return quarter
def quarter_of(month):
# if month == any number inside quarter, return that quarter
# save breakdown of months and quarters inside dictionary
# quarters = {quarter (keys): month (values)}
quarters = {1:[1,2,3], 2:[4,5,6], 3:[7,8,9], 4:[10,11,12]}
quarter_of(3)
quarter_of(8)
quarter_of(11) |
class Node(object):
def __init__(self, value, index=0):
self.value = value
self.children = []
self.index = index
class SetSuffixTree(object):
"""
From Skiena on Data Structures, given a reference string S
this is useful for finding all the places where an
arbitrary query string q is a substring of S. Also
War Story: String 'em up. The example trees generated
are taken from the book.
"""
def __init__(self):
pass
def print_children(self, children):
"""
Accepts list of children, and prints their values.
"""
for c in children:
print c.value
def construct_trie(self, trie, words):
chars=[]
for word in words:
chars.append(word[0])
chars=list(set(chars))
for char in chars:
trie.children.append(Node(char))
words_dict = {}
for char in chars:
words_dict[char] = []
for key in words_dict.keys():
for word in words:
if word[0] == key:
if len(word) > 1:
words_dict[key].append(word[1:])
else:
return
self.print_children(trie.children)
for child in trie.children:
print words_dict[child.value]
self.construct_trie(child, words_dict[child.value])
def walk_tree(self, new_trie, space):
"""
Cheap and cheerful way of printing the trees.
"""
print space+new_trie.value
for child in new_trie.children:
self.walk_tree(child,space+'\t')
if __name__=='__main__':
words = ['there', 'their', 'was', 'when']
trie = Node('')
suffix = SetSuffixTree()
suffix.construct_trie(trie, words)
suffix.walk_tree(trie,'\t')
words = ['ACAC','CACT']
trie = Node('')
suffix = SetSuffixTree()
suffix.construct_trie(trie, words)
suffix.walk_tree(trie,'\t')
|
def is_matched(expression):
from collections import deque
open_b = deque()
if len(expression)%2 != 0:
return False
for s in expression:
try:
if s =='}':
a = open_b.pop()
if a != '{':
return False
elif s ==')':
a = open_b.pop()
if a != '(':
return False
elif s ==']':
a = open_b.pop()
if a != '[':
return False
else:
open_b.append(s)
except IndexError:
return False
if len(open_b) > 0:
return False
else:
return True
|
from collections import deque
class Vertex(object):
def __init__(self, id_, parent=None):
self.id_ = id_
self.neighbours = []
self.discovered = False
self.parent = parent
self.distance = 0
class Graph(object):
def __init__(self, N):
self.vertices = {}
self.distances = []
self.edge_weight = 6
self.distances = {}
for i in range(N):
self.vertices[i] = Vertex(i)
def connect(self, x, y):
self.vertices[x].neighbours.append(self.vertices[y])
self.vertices[y].neighbours.append(self.vertices[x])
def find_all_distances(self, s):
#initialize search queue:
vertices_to_find = [v for v in self.vertices.keys()]
vertices_to_find.remove(s)
for v in vertices_to_find:
self.distances[v] = 0
for vertex in self.vertices[s].neighbours: #no self directed edges
vertex.discovered = False
vertex.parent = self.vertices[s]
self.vertices[s].discovered = True
vertices_to_search = deque()
vertices_to_search.append(self.vertices[s])
while vertices_to_search:
root = vertices_to_search.popleft()
for search_vertex in root.neighbours:
if not search_vertex.discovered:
search_vertex.discovered = True
search_vertex.parent = self.vertices[root.id_]
vertices_to_search.append(search_vertex)
search_vertex.distance = self.vertices[search_vertex.parent.id_].distance + 6
self.distances[search_vertex.id_] = self.vertices[search_vertex.parent.id_].distance + 6
self.print_distances()
def print_distances(self):
distances = []
for k,v in self.distances.items():
distances.append((k,v))
p_dist = []
for v_d in sorted(distances, key=lambda x:x[0]):
if v_d[1] == 0:
distance = -1
else:
distance = v_d[1]
p_dist.append(distance)
print ' '.join(map(str, p_dist))
with open('input.txt','r') as f:
raw_lines = f.read().split('\n')
t = int(raw_lines[0])
for i in range(t):
n,m = map(int, raw_lines[1].split(' '))
print n,m
graph = Graph(n)
for i in xrange(m):
for line in raw_lines[2:-2]:
x,y = [int(x) for x in line.split()]
graph.connect(x-1,y-1)
s = int(raw_lines[-2])
graph.find_all_distances(s-1)
|
def lonely_integer(a):
while a:
test = a.pop()
try:
a.remove(test)
except ValueError:
return test
def lonely_integer(a):
"""
XOR will evaluate to 0 if two identical numbers are present bit wise
in the list, other wise 0000000^number = number.
"""
lonely_integer = reduce(lambda x, y: x ^ y, a)
return lonely_integer
|
class Node(object):
def __init__(self, price):
self.id_ = 0
self.price = price
self.right_child = None
self.left_child = None
def build_tree(seq):
if len(seq) == 0:
return None
med = len(seq)//2
left = seq[:med]
right = seq[med+1:]
node = Node(seq[med])
node.left_child = build_tree(left)
node.right_child = build_tree(right)
return node
if __name__=='__main__':
a = [1,4,5,3,2]
root = build_tree(a)
print root.price
|
# PhotoFolderFinder.py
"""
Prints an absolute path to a folder that appears to be a photo-folder.
A folder is considered a photo-folder if the number of photos inside
is greater that the number of files.
"""
import os
from PIL import Image
for dirpath, dirnames, filenames in os.walk('C:\\'):
photo_counter = 0
nonphoto_counter = 0
for filename in filenames:
if not (filename.lower().endswith('.png') or filename.lower().endswith('.jpg')):
nonphoto_counter += 1
continue
try:
img = Image.open(filename)
width, height = img.size
except FileNotFoundError as exc:
continue
if width > 500 and height > 500:
photo_counter += 1
else:
nonphoto_counter += 1
if photo_counter > nonphoto_counter:
print(f'The folder is a photo-folder and its destination is {os.path.abspath(dirpath)}')
|
cont_impar = 0
cont_par = 0
num = int(input("Entre com um número [999 para encerrar]: "))
while (num != 999):
num = int(input("Entre com um número [999 para encerrar]: "))
if (num % 2 == 0):
cont_par += 1
else:
cont_impar += 1
print('Contagem dos pares:', cont_par)
print('Contagem dos impares:', cont_impar) |
def fibonacci():
l = []
n = 1
n1 = 1
l.append(n)
l.append(n1)
x = int(input('Digite o numero:'))
for i in range(2, x):
l.append(n + n1)
n1 = l[i]
n = l[i - 1]
return(l)
print(fibonacci()) |
texto = input("Digite seu nome;")
print("Seu nome tem {0} letras".format(len(texto)))
|
titulo = 'Jogo da Advinhação!'
linha = '-' * 28
linha1 = "_" * 40
linha2 = '—' * 50
y = 1
print(linha)
print(titulo.center(25))
print(linha)
print()
usuario = input('\t\tDigite seu nome: ')
print('\t\tBem Vindo {0} ao Jogo!'.format(usuario))
print()
print(linha1.center(20))
print('Digite (0) FACIL (1) MEDIO (2) DIFICIL!'.center(20))
x = int(input('Qual sua dificuldade? '))
print(linha1.center(20))
print()
def funcao(a, b, c, d, e):
from random import randint
y = randint
h = (y(0, 10 * b))
pontos = 1000 * b
print('Seus pontos = ', pontos)
for i in range(d):
print()
c = int(input('Diga qual o seu chute: '))
if c > h:
pontos -= a
print('Seu poder de Advinhação está muito fraco, tente NOVAMENTE!')
print('Numero chutado MAIOR que o numero secreto')
elif c < h:
pontos -= a
print('Seu poder de Advinhação está muito fraco, tente NOVAMENTE!')
print('Numero chutado MENOR que o numero secreto')
else:
print()
print(linha2)
print('Parabéns {0} jovem gafanhoto! Número acertado!'.format(usuario))
print(linha2)
print('{0} Você fez: {1} pontos '.format(e, pontos))
break
while y != 0:
if x == 0:
funcao(100, 1, 0, 10, usuario)
elif x == 1:
funcao(150, 10, 0, 15, usuario)
else:
funcao(250, 100, 0, 20, usuario)
print()
y = int(input('Quer continuar {0} vacilão? (0)NÃO e (1)SIM: '.format(usuario))) |
quantidade = 0
codigo = 0
p = 0
while True:
n = int(input("Digite o codigo:"))
a = int(input("Digite a quantidade:"))
quantidade = a + quantidade
if n == 1:
p = p + 0.50
p = p * a
if n == 2:
p = p + 1.00
p = p * a
if n == 3:
p = p + 4.00
p = p * a
if n == 5:
p = p + 7.00
p = p * a
if n == 9:
p = p + 8.00
p = p * a
if n == 0 :
print("Total a pagar:",preco)
else:
print("Código inválido")
|
#MEDIA IFPA
linha = '-' * 60
titulo = 'INSTITUTO FEDERAL DE EDUCAÇÃO, CIÊNCIA E TECNOLOGIA DO PARÁ \nCampus Altamira\nAUTOR: Jobs-TI'
print(linha)
print(titulo.center(60))
print(linha)
linha = '-' * 60
titulo = 'MÉDIA DE APROVAÇÃO'
print(linha)
print(titulo.center(60))
print(linha)
nota1 = float(input('Digite sua primeira nota: '))
nota2 = float(input('Digite sua segunda nota: '))
media = (nota1 + nota2)/2
if media >= 7:
print('PARABÉNS!!! Aprovado, sua média é: ', media)
elif media < 7:
print('Sua média foi', media)
nota_exame = float(input('Infelizmente você NÃO atingiu a media 7. \nPor favor Digite a nota da RECUPERAÇÃO: '))
nova_media = (media + nota_exame) / 2
if nova_media >= 7:
print('PARABÉNS !!! Aprovado em exame, sua média é: ', nova_media)
else:
print('REPROVADO, sua média é: ', nova_media) |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#文件或目录创建脚本
import os
#用户选择新建目录还是文件
def panDuan():
b = int(input('1.创建文件 2.创建文件夹 [1/or/2]'))
#接收用户的输入如果文件运行函数creatFile,如果是文件夹运行函数creatDir
if b == 1:
creatFile()
elif b == 2:
creatDir()
else:
print("别闹!")
def creatDir():
a = input("文件夹名称:")
#判断文件名是否存在
if os.path.exists(a):
print("已存在!")
#创建文件夹
os.makedirs(a)
def creatFile():
a = input("文件名称:")
#拆分文件名防止用户在没有的文件夹中创建文件
b = os.path.split(a)
if os.path.exists(b[0]):
os.mknod(b[1])
else:
os.makedirs(b[0])
os.mknod(b[1])
panDuan() |
# -*- coding: utf-8 -*-
"""
@author: Saras
Problem Set 1 for MITx: 6.00.1x Introduction to Computer Science and Programming Using Python
"""
'''
Problem 2
10.0/10.0 points (graded)
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2
'''
counter = 0
c = len(s)
final = 0
while counter < c-2:
letter = s[counter]
if (s[counter] == 'b'and s[counter+1] == 'o'and s[counter+2] == 'b'):
final += 1
counter += 1
print('Number of times bob occurs is: ' + str(final)) |
# READ ME:
# Input file: create a possible state by swapping pieces (even swaps) and eliminate pieces by writing 0
# Start by checking what the input cube state looks like using inpstate()
# Use listates([draw]) to output all the possible cube states (listates(1) to output images)
########################################################################################################################
# Show the input state
def inpstate():
with open('inpcube.txt','r') as f:
for i in range(19):
commstr = f.readline() # Ignore comment in text file
cubestate = [[int(x) for x in line.split()] for line in f] # Read cube state from input file
print(cubestate)
drawcube(cubestate, 0)
########################################################################################################################
# TO DO: Input checks; along with: is the cube state possible for trivial inputs?
# Consider known permutations but unknown orientations and vice versa.
# List all possible states from input
def listates(draw): # draw = 1 means draw all output cube states
# INPUT
with open('inpcube.txt','r') as f:
for i in range(19):
commstr = f.readline() # Ignore comment in text file
cubestate = [[int(x) for x in line.split()] for line in f] # Read cube state from input file
# SET-UP
outno = 0 # To label, and to count the number of, output cube states
# Arrange into seperate corner and edge arrays
# Corner Arrays
cperm = cubestate[0][0:8]
corient = cubestate[1][0:8]
# Edge Arrays
eperm = cubestate[0][8:20]
eorient = cubestate[1][8:20]
# Check the number of gray "open" corners/edges and act accordingly:
open_corners = cperm.count(0) # Find the number of open corners
open_edges = eperm.count(0) # Find the number of open edges
# Find index position of zeros in cperm and eperm
cindex, eindex = find_zero_index_arrays(open_corners, open_edges, cperm, eperm)
# PERMUTATIONS
# Find the current number of swaps from given (non-open) pieces; and deal with lost pieces while at it
swaps = 0
swaps, lostc = find_current_corner_swaps(swaps, cperm, open_corners)
swaps, loste = find_current_edge_swaps(swaps, eperm, open_edges)
# Sort through all possible cases systematically and draw into output file
ce_perms = even_swaps(lostc, loste, swaps) # Returns list of [corner perms, edge perms] arrays
# ORIENTATIONS
# Find current orientation number; simply sum the orientation numbers for corners and edges
current_corient = sum(corient)
current_eorient = sum(eorient)
# Find and store all possible orientations for open pieces
list_orients_c = find_possible_corner_orientations(open_corners, current_corient, corient, cindex)
list_orients_e = find_possible_edge_orientations(open_edges, current_eorient, eorient, eindex)
# Form full orientation arrays
list_orients = []
for cor in list_orients_c:
for eor in list_orients_e:
totor = cor + eor # totor = total orientations
list_orients.append(totor[:]) # List of orientations for corners and edges
# OUTPUT
# Combine permutations and orientations, to form cubestates to then draw to file (also list cubestates in single text file)
# Have lists of: which pieces are lost, the number of open pieces, where the open pieces are, possible perms and possible orients
with open("outstates.txt", "w") as f:
list_perms = cubestate[0][:] # To form final corner and edge perms
for i in range(len(ce_perms)):
lc_perm = ce_perms[i][0] # Lost corner perms
le_perm = ce_perms[i][1] # Lost edge perms
# First form permutation row; use zero_index arrays and combine the current cube state with ce_perms
# Corners
j = 0
for zind in cindex: # zind = zero index
list_perms[zind] = lc_perm[j]
j += 1
# Edges
j = 0
for zind in eindex: # +8 since referring to cubestate
list_perms[zind + 8] = le_perm[j]
j += 1
# For each permutation found above, loop through the orientations and form cube states to draw
for ceo in list_orients: # ceo = corner edge orient
outno += 1
if draw == 1: # then draw cube state
outcube = [list_perms[:], ceo[:]]
drawcube(outcube, outno)
# Also, output cubestate in form given in input
print("Cube State", outno, file=f)
print(list_perms, file=f)
print(ceo, end="\n\n", file=f)
print("Number of output cube states =", outno)
########################################################################################################################
def find_current_corner_swaps(swaps, cperm, open_corners): # Corners
lostc = []
if open_corners > 1: # Need to deal with swaps and lost pieces
for i in range(1,9):
# Check if number exists; if does then find its index; else find index of first zero above finished numbers
num_exists = cperm.count(i)
if num_exists == 1:
swapno = cperm.index(i)
else: # Found missing number; deal with next zero
lostc.append(i)
swapno = cperm.index(0)
swaps = swaps + swapno
# Update swap_arr; remove i or 0 to focus on rest of array
cperm.pop(swapno)
elif open_corners == 1: # Only need to deal with a single lost piece
for i in range(1,9):
cubie_set = cperm.count(i)
if cubie_set == 0:
lostc.append(i)
break # Found only lost corner so can break for loop
return swaps, lostc
########################################################################################################################
def find_current_edge_swaps(swaps, eperm, open_edges):
loste = []
if open_edges > 1: # Need to deal with swaps and lost pieces
for i in range(9,21):
# Check if number exists; if does then find its index; else find index of first zero above finished numbers
num_exists = eperm.count(i)
if num_exists == 1:
swapno = eperm.index(i)
else: # Found missing number; deal with next zero
loste.append(i)
swapno = eperm.index(0)
swaps = swaps + swapno
# Update swap_arr; remove i or 0 to focus on rest of array
eperm.pop(swapno)
elif open_edges == 1: # Only need to deal with a single lost piece
for i in range(9,21):
cubie_set = eperm.count(i)
if cubie_set == 0:
loste.append(i)
break # Found only lost corner so can break for loop
return swaps, loste
########################################################################################################################
def find_zero_index_arrays(open_corners, open_edges, cperm, eperm):
# Corners
cindex = []
start = 0
for i in range(open_corners):
zero_index = cperm.index(0, start)
cindex.append(zero_index)
start = zero_index + 1
# Edges
eindex = []
start = 0
for i in range(open_edges):
zero_index = eperm.index(0, start)
eindex.append(zero_index)
start = zero_index + 1
return cindex, eindex
########################################################################################################################
def find_possible_corner_orientations(open_corners, current_corient, corient, cindex):
list_orients_c = []
imax = 3**open_corners # Max i is such that all possibilities are gone through
for i in range(imax):
trial = [] # Trial array for orientation
for j in range(open_corners):
orient = (int(i/(3**j)))%3
trial.append(orient)
orient_poss = (current_corient + sum(trial))%3 # Orientation is possible if the sum of all orientations is 0 (modulo 3)
if orient_poss == 0: # Possible
j = 0
for zind in cindex: # zind = zero index
corient[zind] = trial[j]
j += 1
list_orients_c.append(corient[:]) # Add orientation array to list
return list_orients_c
########################################################################################################################
def find_possible_edge_orientations(open_edges, current_eorient, eorient, eindex):
list_orients_e = []
imax = 2**open_edges
for i in range(imax):
trial = []
for j in range(open_edges):
orient = (int(i/(2**j)))%2
trial.append(orient)
orient_poss = (current_eorient + sum(trial))%2
if orient_poss == 0:
j = 0
for zind in eindex: # zind = zero index
eorient[zind] = trial[j]
j += 1
list_orients_e.append(eorient[:])
return list_orients_e
########################################################################################################################
# Function to systematically sort through possible permutations (defined by an even number of swaps only), with the list ouput
def even_swaps(perm_arr, carry_arr, swaps): # Array to permute, array to carry through, the number of swaps applied to perm_arr
tot_arrs = [] # Total arrays
length = len(perm_arr)
if length > 2:
for i in range(length):
index = length - i - 1 # Index at which to insert before
next_arr = perm_arr[0:length-1] # The next array to process is the current array minus the entry (always at the end) just permuted
last_ent = perm_arr[length-1] # The last entry, which is permuted here
new_swaps = swaps + i # i = no. of swaps just done
out_arrs = even_swaps(next_arr, carry_arr, new_swaps) # Output list of permutations; using a function within itself allows arbitrary for loops
for j in range(len(out_arrs)):
out_arrs[j][0].insert(index, last_ent) # Insert last entry at index of each altered "next_arr"
tot_arrs.append(out_arrs[j][:]) # Add the two arrays (modified perm_arr and carry_arr) to the final array to be output
elif length == 2:
if len(carry_arr) > 2:
# Apply the function, swapping the current roles of perm_arr and carry_arr
tot_arrs = even_swaps(carry_arr, perm_arr, swaps)
for j in range(len(tot_arrs)):
tot_arrs[j].reverse()
elif len(carry_arr) == 2:
# Two pairs of both corners and edges
if swaps%2 == 0: # If swaps is even, do nothing or swap both
tot_arrs.append([perm_arr[:], carry_arr[:]])
perm_arr.reverse()
carry_arr.reverse()
tot_arrs.append([perm_arr[:], carry_arr[:]])
else: # If swaps is odd, swap one and not the other (both ways)
perm_arr.reverse()
tot_arrs.append([perm_arr[:], carry_arr[:]])
perm_arr.reverse()
carry_arr.reverse()
tot_arrs.append([perm_arr[:], carry_arr[:]])
else: # length of carry_arr < 2
# Just do one pair of corners/edges
if swaps%2 == 0: # If swaps is even, do not swap
tot_arrs = [[perm_arr, carry_arr]]
else: # If swaps is odd, swap
perm_arr.reverse()
tot_arrs = [[perm_arr, carry_arr]]
else: # If length of perm array < 2
if len(carry_arr) > 2:
# Apply the function, swapping the current roles of perm_arr and carry_arr
tot_arrs = even_swaps(carry_arr, perm_arr, swaps)
for j in range(len(tot_arrs)):
tot_arrs[j].reverse()
elif len(carry_arr) == 2:
# Just do one pair of corners/edges
if swaps%2 == 0: # If swaps is even, do not swap
tot_arrs = [[perm_arr, carry_arr]]
else: # If swaps is odd, swap
carry_arr.reverse()
tot_arrs = [[perm_arr, carry_arr]]
else:
tot_arrs = [[perm_arr, carry_arr]]
return tot_arrs
########################################################################################################################
# Draw the cube state
def drawcube(cubestate, outno):
# Import Libraries
from matplotlib import pyplot as plt
from shapely.geometry.polygon import Polygon
from descartes import PolygonPatch
# Set up face arrays
# centre sticker colours = [W, B, R, G, Y, O]
mult = [[1,0,0,1], [1,0,0,1], [1,0,0,1], [0.707,0,0.707,1], [1,0.707,0,0.707], [1,0,0,1]] # mulitpliers for sticker coordinates; [xhm, xvm, yhm, yvm]
init_coords = [[4,1], [1,4], [4,4], [7,4], [4,7], [9.12,6.12]] # initial (x,y) coordinates for each face in final drawing
# Set key array to convert cubie coordinates to sticker coordinates: [face coordinate, sticker coordinate]
# U R F
URF = [[4,2],[3,6],[2,8]]
UFL = [[4,0],[2,6],[1,8]]
UBR = [[4,8],[5,6],[3,8]]
ULB = [[4,6],[1,6],[5,8]]
DFR = [[0,8],[2,2],[3,0]]
DLF = [[0,6],[1,2],[2,0]]
DRB = [[0,2],[3,2],[5,0]]
DBL = [[0,0],[5,2],[1,0]]
UF = [[4,1],[2,7]]
UB = [[4,7],[5,7]]
UR = [[4,5],[3,7]]
UL = [[4,3],[1,7]]
FR = [[2,5],[3,3]]
FL = [[2,3],[1,5]]
BR = [[5,3],[3,5]]
BL = [[5,5],[1,3]]
DF = [[0,7],[2,1]]
DB = [[0,1],[5,1]]
DR = [[0,5],[3,1]]
DL = [[0,3],[1,1]]
keyarr = [URF, UFL, UBR, ULB, DFR, DLF, DRB, DBL, UF, UB, UR, UL, FR, FL, BR, BL, DF, DB, DR, DL]
# Initialise cubie colours; read clockwise for corners, and starting with sticker of ref for orientation (orientation like ZZ edges; corners point U,D)
# U R F
URF = ["gold", "g", "crimson"]
UFL = ["gold", "crimson", "b"]
UBR = ["gold", "orangered", "g"]
ULB = ["gold", "b", "orangered"]
DFR = ["w", "crimson", "g"]
DLF = ["w", "b", "crimson"]
DRB = ["w", "g", "orangered"]
DBL = ["w", "orangered", "b"]
UF = ["gold", "crimson"]
UB = ["gold", "orangered"]
UR = ["gold", "g"]
UL = ["gold", "b"]
FR = ["crimson", "g"]
FL = ["crimson", "b"]
BR = ["orangered", "g"]
BL = ["orangered", "b"]
DF = ["w", "crimson"]
DB = ["w", "orangered"]
DR = ["w", "g"]
DL = ["w", "b"]
solvedcube = [URF, UFL, UBR, ULB, DFR, DLF, DRB, DBL, UF, UB, UR, UL, FR, FL, BR, BL, DF, DB, DR, DL]
# Set up blank colour array, with centre stickers filled in (black stickers showing means an error)
totcol = []
totcol.append(["k", "k", "k", "k", "w", "k", "k", "k", "k"])
totcol.append(["k", "k", "k", "k", "b", "k", "k", "k", "k"])
totcol.append(["k", "k", "k", "k", "crimson", "k", "k", "k", "k"])
totcol.append(["k", "k", "k", "k", "g", "k", "k", "k", "k"])
totcol.append(["k", "k", "k", "k", "gold", "k", "k", "k", "k"])
totcol.append(["k", "k", "k", "k", "orangered", "k", "k", "k", "k"])
# Calculate sticker colours
# Loop through each corner
for i in range(8):
# Determine cubie state
if cubestate[0][i] == 0: # Gray cubies show cube states to sort through
cubie = ["darkgray", "darkgray", "darkgray"]
else: # Fixed cubies are ignored
index = cubestate[0][i] - 1 # Permutation
orient = cubestate[1][i] # Orientation
cubie = solvedcube[index]
if orient == 1: # if orient == 1 then shift one way (clockwise), if 2 then the other (anti-clockwise), if 0 do nothing
tmpsticker = cubie.pop()
cubie.insert(0, tmpsticker)
elif orient == 2:
tmpsticker = cubie.pop(0)
cubie.insert(3, tmpsticker)
key = keyarr[i] # Extract key for this particular cubie
for j in range(3): # Loop through each sticker on cubie
fcoord = key[j][0] # Set face coord
scoord = key[j][1] # Set sticker coord
totcol[fcoord][scoord] = cubie[j] # Insert correct sticker colour into total colour array
# Loop through each edge
for i in range(8, 20):
if cubestate[0][i] == 0:
cubie = ["darkgray", "darkgray"]
else:
index = cubestate[0][i] - 1 # Permutation
orient = cubestate[1][i] # Orientation
cubie = solvedcube[index]
if orient == 1: # if orient == 1 then swap colours, otherwise do nothing
tmpsticker = cubie.pop()
cubie.insert(0, tmpsticker)
key = keyarr[i]
for j in range(2):
fcoord = key[j][0]
scoord = key[j][1]
totcol[fcoord][scoord] = cubie[j]
# Set Polygons; first initialise figure
fig = plt.figure(1, figsize=(13,10), dpi=90)
ax = fig.add_subplot(111)
# sticker coords to define 4 corners
h1 = 0.1
h2 = 0.9
h3 = 0.9
h4 = 0.1
v1 = 0.1
v2 = 0.1
v3 = 0.9
v4 = 0.9
# Loop through each face
for i in range(6):
# multipliers
xhm = mult[i][0]
xvm = mult[i][1]
yhm = mult[i][2]
yvm = mult[i][3]
# initial coords
x0 = init_coords[i][0]
y0 = init_coords[i][1]
# Loop through each sticker
for n in range(9):
h = n%3 # stciker x coord
v = n//3 # sticker y coord
xb = x0 + h*xhm + v*xvm # base x coord
yb = y0 + h*yhm + v*yvm # base y coord
x = [xb + h1*xhm + v1*xvm, xb + h2*xhm + v2*xvm, xb + h3*xhm + v3*xvm, xb + h4*xhm + v4*xvm] # x coordinates of face stickers
y = [yb + h1*yhm + v1*yvm, yb + h2*yhm + v2*yvm, yb + h3*yhm + v3*yvm, yb + h4*yhm + v4*yvm] # y coordinates of face stickers
# draw filled polygon
ax.fill(x, y, totcol[i][n])
# Settings:
ax.set_title('Cube State ' + str(outno))
xrange = [0,13]
yrange = [0,10]
ax.set_xlim(*xrange)
ax.set_ylim(*yrange)
ax.set_xticklabels([]) # Turn off axes values
ax.set_yticklabels([])
ax.set_aspect(1)
ax.set_facecolor('lightgray') # Set background colour
# Show Plot
if outno != 0:
# Draw to file; do not show; name cube state after number in outno
#file_name = ''
#for i in range(19):
# file_name += str(cubestate[0][i]) + '-' + str(cubestate[1][i]) + '__'
#file_name += str(cubestate[0][19]) + '-' + str(cubestate[1][19]) + '.png'
file_name = "Cube_State_" + str(outno) + ".png"
plt.savefig(file_name)
plt.close(fig)
else:
# Show immediately; not saved to file
plt.show()
|
def square(x):
return x * x
print square(2) # 4
print type(square) # <type 'function'>
squareLambda = lambda x: x * x
print squareLambda(2) # 4
print type(squareLambda) # <type 'function'>
list = range(5)
print list # [0, 1, 2, 3, 4]
print map(squareLambda, list) # [0, 1, 4, 9, 16]
|
file = open("test.txt", "r")
lines = file.readlines()
for line in lines:
str = line
arr1 = (str.split("//"))
if len(arr1)==2:
print ( arr1[1], "- is a comment")
if len(arr1)==1:
str.split()
arr2 = arr1[0].split("/*")
arr3 = arr1[0].split("*/")
if arr2[0]=='':
print ("Comment starts at line-", arr2[1])
print ("(If comment does not end then no comment)")
if len(arr3)!=1:
if arr3[1]=="\n":
print ("Comment ends at line-", arr3[0])
print ("(If comment does not start then no comment)")
file.close()
|
fruit1=input("whats your favorite fruit?\n")
veg1=input("whats your favorite vegetable?\n")
sweet1=input("whats your favorite sweet?\n")
print(f"\n\r{fruit1}\n{veg1}\n{sweet1}\nare your favorites?") |
print('\tHello World\n') #\t creates
#an indent, \n makes a new line, and
#using \ before a character will
#treat it differently, for example:
print("This is a double quote \", yet still in a double \nquoted print because of the backslash.")
print("""There once was a movie star icon
who preferred to sleep with the light on.
They learned how to code
a device that sure glowed
and lit up the night using Python!\n""")
firstName = input("What is your first name?\n")
firstName = firstName.upper()
lastName = input("What is your last name?\n")
lastName = lastName.upper()
print("Hello, " + firstName + " " + lastName +"!")
country = input("What country do you live in?\n")
country = country.upper()
print("Hello, " + firstName + " " + lastName + ", from " + country + ".\n")
#find counts the number of values before<<< the string entered, including spaces, and starts from 0, and the number given
#is where the first value of the given string is found. So, for example, print(testingNewFunction.find("peoples")) returns
#, because it starts at 0 from the "H", and ends at the "p" of peoples
testingNewFunction = "Heello, peoples of this country!"
print("This is going to be a function test.")
print(testingNewFunction)
print("The following number will be the amount of spaces from 'H', starting with 0,\n to the place 'p' occupies.")
print(testingNewFunction.find("peoples"))
#Python can figure out the value of a variable on the fly when doing something like postalCode = input("Please tell
#us your postal code: "), it'll know it's value based on what the user inputs, however, some languages will need for the below.
postalCode = " "
postalCode = input("Please tell us your postal code: ")
print(postalCode.upper() + " is your postal code.")
#If you're using a function, it always<<< requires parenthesis.
length = 3
height = 5
area = length*height
message = "The answer is:"
print(message)
print(area)
print("\n")
age = "42"
#^ 42 is a string
#child_age = age/2 <<< this code produces an error, as 42 is a string and can't be used in calculations.
age = "42"
child_Age = int(age)/2
print(age + " is the age of the parent, " + str(child_Age) + " is the age of the child, making the parent\n "\
+ str(child_Age) + " when the child was birthed.")
#Shows proper usage of int making something a str and str making something an int
print("5+5= " + str(5+5))
print("15-5= " + str(15-5))
print("5*3= " + str(15*3))
print("15/3= " + str(15/3))
print("3**2= " + str(3**2))
print("43%5= " + str(43%5))
#PEMDAS applies<<< order of operations
#THE + CONNECTS TWO STRINGS<<<
#Another way to show is to have a placeholder. Don't know entire differences between float/decimal (%f & %d),
#float seems to be attachable to dec, dec seems to be attachable to whole. Float has decimals and decimal is wholes.
area = 6
print("The area of the square is %f" % area)
print("The area of the square is %.0f" % area)
print("The area of the square is %.02f" % area)
print("The area of the square is %03d" % area)
print("The area of the square is %3d" % area)
#break
print("My favorite number is %d!" % 42)
#Putting %10d will make the number placed after 10 spaces, useful for money formatting and such.
print("The cost of a wheelbarrow is %10d" % 45)
print("This is a longer string length than the \nprevious, and the value is %12d" % 65)
#Another way of using "placeholders", more common and useful method.
print("My favorite number is {0:.0f}".format(72))
print("Here are three numbers, {0:d}, {1:d}, {2:d}.".format(5,10,97))
area=100
print("The area of the square is {0:f}.".format(area))
print("The area of the square is {0:.0f}.\n".format(area))
#loan calc challenge
P = input("Input Principal/Loan: ")
P = int(P)
J = input("Input your annual interest rate in decimal form: ")
J = float(J)/12
N = input("Total number of payments: ")
N = int(N)*-1
M = P * (J/(1-(1+J)**N))
print("Your monthly payment is " + str(M))
#end challenge
import datetime
print(datetime.date.today())
#can store dates in variables
currentDate = datetime.date.today()
print(currentDate)
print("Year: " + str(currentDate.year))
print("Month: " + str(currentDate.month))
print("Day: " + str(currentDate.day))
#formatting dates
# %a=weekday abrv. %A=weekday full %d= zero-padded day number %b=month abrv. %B= month full
# %m=zero-padded month number
print(currentDate.strftime("%d %b, %Y"))
print(currentDate.strftime("%d %B, %y"))
#Using dates in a sentence
testDate = datetime.datetime.strptime("Sep 14, 2015", "%b %d, %Y").date()
print(testDate)
#advanced
eventDate = datetime.datetime.strptime("2 September, Sunday", "%d %B, %A").date() #.date() specifies date in particular, where time would also be shown
print(eventDate.strftime("Please attend our event on the %dnd of %B, on %A."))
# LOOK ON PHONE PICTURES, TAKEN AT 5:35, LETS GET BACK TO CALCULATING DAYS UNTIL YOUR BIRTHDAY, MAKING
#STRINGS INTO DATES.
#
#
#
#
#
#
#
#
#
#
# working with time
currentTime = datetime.datetime.now()
print(currentTime.time()) #.time() specifies time in particular, where date would also be shown
print(currentTime.hour)
print(currentTime.minute)
print(currentTime.second)
print(datetime.datetime.strftime(currentTime, "%I:%M:%S"))
testTime = datetime.datetime.strptime("9:35:0", "%I:%M:%S").time() #.time() specifies time in particular
print(testTime)
|
import turtle
import random
#set up screen for drawing
my_screen = turtle.Screen()
my_turtle = turtle.Turtle()
my_screen.colormode(255)
screenwidth, screenheight = my_screen.screensize()
# this function draws mountains
def mountains (radius):
my_turtle.pu ()
my_turtle.color ("green", "green")
my_turtle.setpos(screenwidth, 0)
my_turtle.width(radius/20)
my_turtle.pd()
while my_turtle.xcor () > -screenwidth:
my_turtle.seth(90)
my_turtle.circle(radius, 180)
#this function draws the sun
def sun(radius):
my_turtle.pu()
turtle.textinput("hey", "It's a beautiful day!")
my_turtle.setpos(screenwidth-radius, screenheight-radius)
my_turtle.pd()
#draw ridges
for i in range (19):
my_turtle.color ("yellow", "")
my_turtle.width(radius/20)
my_turtle.begin_fill()
my_turtle.circle(radius/10, 180)
my_turtle.rt(200)
my_turtle.end_fill()
my_turtle.pu()
def head (radius):
#draw head of stick figure
my_turtle.width(1)
my_turtle.color ("black", "white")
my_turtle.begin_fill()
my_turtle.setpos(0,0)
my_turtle.seth(0)
my_turtle.pd()
my_turtle.circle (radius)
my_turtle.lt(90)
my_turtle.end_fill()
my_turtle.penup()
#draw hairline of stick figure
def hairline (radius):
my_turtle.fd(radius*1.5)
my_turtle.pendown()
my_turtle.lt(90)
my_turtle.fd((radius**2-(radius/3)**2)**.5)
my_turtle.bk((radius**2-(radius/3)**2)**.5)
my_turtle.lt(180)
my_turtle.fd((radius**2-(radius/3)**2)**.5)
my_turtle.bk((radius**2-(radius/3)**2)**.5)
# draw eyes of stick figure
def eyes (radius):
my_turtle.rt(90)
my_turtle.penup()
my_turtle.fd(radius/3)
my_turtle.rt(90)
my_turtle.fd(radius/2)
my_turtle.pendown()
my_turtle.dot(radius/5)
my_turtle.penup()
##draw nose of stick figure
def nose (radius):
my_turtle.lt(180)
my_turtle.fd(radius)
my_turtle.pendown()
my_turtle.dot(radius/5)
my_turtle.penup()
my_turtle.rt(180)
my_turtle.fd(radius/2)
my_turtle.lt(90)
my_turtle.fd(radius/3)
my_turtle.pendown()
my_turtle.width (radius/20)
my_turtle.fd(radius/5)
my_turtle.lt(90)
my_turtle.fd(radius/5)
my_turtle.bk(radius/5)
my_turtle.rt (90)
my_turtle.penup()
my_turtle.fd(radius/4)
my_turtle.rt(90)
#drawmouth of stick figure
def mouth (radius):
my_turtle.pendown()
my_turtle.color("black", "red")
my_turtle.begin_fill()
my_turtle.fd (radius/4)
my_turtle.bk (2*radius/4)
my_turtle.lt(90)
my_turtle.circle(-radius/4, 180)
my_turtle.end_fill()
my_turtle.pu()
my_turtle.setpos(0,0)
my_turtle.rt(90)
##draw ears of stick figure
def ears (radius):
my_turtle.circle(radius,90)
my_turtle.lt(90)
my_turtle.fd(radius/5)
my_turtle.circle (radius/5, 220)
my_turtle.pd()
my_turtle.rt(45)
my_turtle.width (1)
my_turtle.circle(radius/6,180)
my_turtle.pu()
my_turtle.setpos(0,0)
my_turtle.seth(0)
my_turtle.circle(radius, 270)
ears = turtle.pos()
my_turtle.rt(90)
my_turtle.pd()
my_turtle.circle(radius/6, 180)
my_turtle.pu()
#draw neck,hands stomack and legs (using sticks) of stick figure
def neck(radius):
my_turtle.setposition(0,0)
my_turtle.seth(270)
my_turtle.pd()
my_turtle.fd (radius)
def left_hand (radius):
my_turtle.left(45)
my_turtle.bk(radius*3/2)
my_turtle.fd(radius*3/2)
def right_hand (radius):
my_turtle.rt(90)
my_turtle.bk(radius*3/2)
my_turtle.fd(radius*3/2)
def stomach (radius):
my_turtle.lt(45)
my_turtle.fd(radius)
def right_leg (radius):
my_turtle.lt(45)
my_turtle.fd(radius*3/2)
my_turtle.bk(radius*3/2)
def left_leg (radius):
my_turtle.rt(90) #(dif angles for dif positions)
my_turtle.fd(radius*3/2)
#thought bubble above stick figure's head
def thought_bubble (radius):
my_turtle.pu()
my_turtle.setpos(0,0)
my_turtle.seth(0)
my_turtle.circle(radius, 120)
my_turtle.pd()
my_turtle.lt(90)
my_turtle.bk(radius/5)
for i in range (20):
my_turtle.circle(radius/10, 180)
my_turtle.lt(200)
my_turtle.pu()
#draw hi
def say_hi (radius):
my_turtle.seth(270)
my_turtle.bk(radius*2/3)
my_turtle.pd()
my_turtle.fd(radius/2)
my_turtle.bk(radius/4)
my_turtle.seth(0)
my_turtle.fd(radius/4)
my_turtle.seth(270)
my_turtle.fd(radius/4)
my_turtle.bk(radius/2)
my_turtle.seth(0)
my_turtle.pu()
my_turtle.fd(radius/6)
my_turtle.pd()
my_turtle.dot(radius/15)
my_turtle.pu()
my_turtle.seth(270)
my_turtle.fd(radius/8)
my_turtle.pd()
my_turtle.fd(radius*3/8)
#draw stick figure (using functions of the body parts)
def draw_stick_figure (radius):
head (radius)
hairline (radius)
eyes (radius)
nose (radius)
mouth (radius)
ears (radius)
neck (radius)
left_hand (radius)
right_hand (radius)
stomach (radius)
right_leg (radius)
left_leg (radius)
def main (num):
# user input will determine the scale of the image, draw all the parts! Only draw if between 50 and 150 inclusive
while num<50 or num>150:
num = int(turtle.textinput("Welcome!", "Enter a random number between 50 and 150."))
mountains (num)
sun (num)
draw_stick_figure(num)
thought_bubble (num)
say_hi(num)
#set num to 0 and call main
num = 0
main (num)
|
from cs50 import get_float
while True:
change_float = get_float("Change owed: ")
if change_float > 0:
break
change = change_float * 100
total_coins = 0
# quarters = 0
# dimes = 0
# nickels = 0
# pennies = 0
while change >= 25:
change -= 25
# quarters += 1
total_coins += 1
while change >= 10:
change -= 10
# dimes += 1
total_coins += 1
while change >= 5:
change -= 5
# nickels += 1
total_coins += 1
while change >= 1:
change -= 1
# pennies += 1
total_coins += 1
print(f"{total_coins}")
# print(f"Quarters: {quarters}")
# print(f"Dimes: {dimes}")
# print(f"Nickels: {nickels}")
# print(f"Pennies: {pennies}") |
KG=input('請輸入你的體重,單位是公斤')
M=input('請輸入你的身高,單位視公尺')
BMI=float(KG)/(float(M)*float(M))
if float(BMI)<18.5:
print('體重不足')
elif float(BMI)<24:
print('正常')
elif float(BMI)<27:
print('過重')
elif float(BMI)<30:
print('輕度肥胖')
elif float(BMI)<35:
print('中度肥胖')
else:
print('重度肥胖')
|
#Accept an integer n and compute n+nn+nnn
a=int(input("Enter the integer : "))
n1=int("%s" %a)
n2=int("%s%s" %(a,a))
n3=int("%s%s%s" %(a,a,a))
print("value of n+nn+nnn is : ",n1+n2+n3)
|
#Count the occurence of each word in a line of text.
def wordoccur(n,p):
x=n.split(" ")
c=0
for i in range(0,len(x)):
if(p==x[i]):
c=c+1
return c
print("Enter the string:")
n=str(input())
print("Enter the word to count the occurence:")
p=str(input())
print("The occurence of the",p,"is",wordoccur(n,p))
|
#program to display fibonacci series
t=int(input("Enter the number of terms:"))
n1=0
n2=1
count=0
if t<=0:
print("please enter a positive integer")
elif t==1:
print("fibonacci sequence upto",t)
print(n1)
else:
print("Fibonacci sequence:")
while count < t:
print(n1)
n=n1+n2
n1=n2
n2=n
count+=1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.