blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
029a5d5df2dba07d003c0c2179de276d3f63658d | priyankaonly1/PythonDSA | /List/larElement.py | 242 | 3.578125 | 4 | def getMax(l):
if not l:
return None
else:
res = l[0]
for i in range(1,len(l)):
if l[i] > res:
res = l[i]
return res
l = [int(x) for x in input().split()]
print(getMax(l)) |
874c2930d3f4e55b6ab4547e4720663a19fc5404 | Aasthaengg/IBMdataset | /Python_codes/p03545/s103931584.py | 1,003 | 3.546875 | 4 | def operator(x):
if x < 0:
return '-'
else:
return '+'
def main():
abcd = str(input())
a = int(abcd[0])
b = int(abcd[1])
c = int(abcd[2])
d = int(abcd[3])
lst = []
for op_1 in range(2):
for op_2 in range(2):
for op_3 in range(2):
b1 = b
c1 = c
d1 = d
if op_1 == 1:
b1 = -b
if op_2 == 1:
c1 = -c
if op_3 == 1:
d1 = -d
if b1 + c1 + d1 == 7 - a:
lst.append(b1)
lst.append(c1)
lst.append(d1)
break
op1 = operator(lst[0])
op2 = operator(lst[1])
op3 = operator(lst[2])
answer = str(a) + op1 + str(b) + op2 + str(c) + op3 + str(d) + '=' + '7'
print(answer)
if __name__ == '__main__':
main() |
83deae323957c85e9ea0bd589a5ae4e606eacf9e | dhanudhanusha99/Python-Programming | /zerodivision.py | 258 | 3.671875 | 4 | try:
a=int(input("Enter the numerator : "))
b=int(input("Enter the denominator : "))
print("Result after division : "%(a/b))
except(ZeroDivisionError,ValueError) as er:
print(er)
else:
print("Successfully Executed ")
finally:
print("Executed") |
4743dc11174ff5ad4d91ff50ac18b2e04a75655f | Marat200/python_task | /задание 2 к уроку 7.py | 806 | 3.9375 | 4 | from random import randint
MAX_SIZE = 50
def merge_sort(array):
if len(array) < 2:
return array
mid = len(array) // 2
left_part = array[:mid]
right_part = array[mid:]
left_part = merge_sort(left_part)
right_part = merge_sort(right_part)
return merge_list(left_part, right_part)
def merge_list(list_1, list_2):
result = []
i = 0
j = 0
while i < len(list_1) and j < len(list_2):
if list_1[i] <= list_2[j]:
result.append(list_1[i])
i += 1
else:
result.append(list_2[j])
j += 1
result += list_1[i:]
result += list_2[j:]
return result
numbers = [randint(0, 50) for _ in range(MAX_SIZE)]
print(numbers)
print(merge_sort(numbers))
|
8eebb7a2842e0d2aae9ea3f014b600acbc762a4e | codingspecialist/RaspberryPi4-Book-Example | /ch03/for01.py | 183 | 3.78125 | 4 | for i in range(0, 5, 1):
print(i)
print("----------")
for j in[1,3,5,7,9]:
print(j)
print("----------")
for k in range(0, 3, 1):
print("꿈은 이루어 진다.")
|
6da1527d1ec8329eb07b481ca2f78f4e73734e0b | tchinyamakobvu/Assignments | /pythondata/readwrite.py | 211 | 3.984375 | 4 | #Reads name.txt
with open('name.txt') as f:
my_name = f.read()
greeting = 'Hello my name is ' + my_name + '.'
print(greeting)
#write that to a file
with open('Hello.txt',"w") as g:
g.write(greeting) |
be8f5c80e2f07bf03598e7acc7babe8eb1399594 | DragonfireX/python-_exercises_and-notes | /python_query_processes.py | 443 | 3.796875 | 4 | tags = ['python', 'development', 'tutorials', 'code'] # database query here
#big difference between index and length---index starts with 0 ---length starts with 1
number_of_tags = len(tags)
last_item = tags[-1] #value of the last item using negative index
index_of_last_item = tags.index(last_item) #once you have value you can pass to the index function and return of value
print(number_of_tags)
print(last_item)
print(index_of_last_item)
|
7ab79d760d20ca352468ee79aaec48225f095db1 | AleksaArsic/ProjektovanjeAlgoritama | /vezba07/hashTable/hashFunctions.py | 2,101 | 3.796875 | 4 | import math
# hashSize should be defined by the user
def divisionMethod(keyVal, hashSize):
return keyVal % hashSize
def multiplyMethod(keyVal, hashSize):
A = (math.sqrt(5) - 1 ) / (2)
return int((hashSize * (keyVal * A % 1)))
def doubleHashing(keyVal, hashSize):
return ((divisionMethod(keyVal, hashSize) + multiplyMethod(keyVal, hashSize)) % hashSize)
def chainedHashInsert(list, data, hashSize):
# insert data at the head of list T[h(data.key)]
# check if there is a list entry at the returned index
index = doubleHashing(data.key, hashSize)
if list[index] == None:
list[index] = data
else:
tempData = list[index]
while tempData.next != None:
tempData = tempData.next
tempData.next = data
def chainedHashDelete(list, data, hashSize):
index = doubleHashing(data.key, hashSize)
if list[index] == None:
print("No element found with the given key")
else:
tempData = list[index]
temp = None
if tempData.value == data.value:
temp = tempData.next
list[index] = temp
else:
while tempData.next.value != data.value:
temp = tempData
tempData = tempData.next
temp = tempData
temp.next = tempData.next.next
def chainedHashSearch(list, key, hashSize):
index = doubleHashing(key, hashSize)
if list[index] == None:
print("No elements found with the given key.")
else:
printChain(list[index])
def printChain(data):
tempData = data
print("Chain data:")
print(tempData.value)
while tempData.next != None:
print(tempData.next.value)
tempData = tempData.next
def printChainedHash(list, hashSize):
for i in range(0, hashSize):
if list[i] != None:
print("index: ", i, "data: ", list[i].value)
tempData = list[i]
while tempData.next != None:
print("linked data [", i, "]:", tempData.next.value)
tempData = tempData.next
|
06679787cb3396ff2b42e6c5a34e2e3d69dc47da | hut/dotfiles | /pythonlib/formats.py | 510 | 3.609375 | 4 | def opencsv(filename):
import csv
fstream = open(filename, "r")
reader = csv.reader(fstream)
data = []
for entry in reader:
data.append(entry)
fstream.close()
return data
def columns(data, *columns):
newdata = []
for entry in data:
newdata.append([entry[i] for i in columns])
return newdata
def writecsv(filename, data):
import csv
fstream = open(filename, "w")
writer = csv.writer(fstream)
writer.writerows(data)
fstream.close()
|
13f771cda5b5698d0a782e81dfe2c8cd6725db97 | GreyLove/DataStructureAndAlgorithm | /18-1.py | 902 | 3.765625 | 4 | # // 面试题18(一):在O(1)时间删除链表结点
# // 题目:给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该
# // 结点。
class node(object):
def __init__(self,val):
self.val = val
self.next = None
def deleteNode(root,node):
if not root or not node:
return
if root == node and node.next == None:
return
elif node.next == None:
cur = root
while cur.next != node:
cur = cur.next
cur.next = None
else:
cur = node.next
node.val = cur.val
node.next = cur.next
cur.next = None
return root
cur = node(0)
root = cur
tmp = cur
for i in range(1,3):
cur.next = node(i)
cur = cur.next
if i == 1:
tmp = cur
root = deleteNode(root,tmp)
print(root)
# root = deleteNode(root,tmp)
# print(root)
|
fcf5b0528070e2bf461afc3f97f4ba7545dc2213 | VladAdmin0/Trainer | /getsum.py | 1,752 | 4.09375 | 4 | # Given two integers, which can be positive and negative, find the sum of all the numbers between including them
# too and return it. If both numbers are equal return a or b.
a = int(input('enter a:'))
b = int(input('enter b:'))
def get_sum(a,b):
if a == b:
# return a
print(a)
elif a < 0 and b > 0:
counta = a
countb = a + b
c = 0
d = 0
while counta <= 0:
c = a + c
a += 1
counta += 1
while countb >= 0:
d = b + d
b -= 1
countb -= 1
print(c+d)
elif b < 0 and a > 0:
countb = b
counta = b + a
c = 0
d = 0
while countb <= 0:
c = b + c
b += 1
countb += 1
while counta >= 0:
d = a + d
a -= 1
counta -= 1
print(c+d)
elif b < 0 and a < 0:
if a < b:
c = 0
count = a - b
while count <= 0:
c = b + c
count += 1
b -= 1
print(c)
elif b < a:
count = b - a
c = 0
while count <= 0:
c = a + c
count += 1
a -= 1
print(c)
elif b > 0 and a > 0:
if a < b:
count = b-a
c = 0
while count >= 0:
c = a + c
count -= 1
a += 1
print(c)
elif b < a:
count = a - b
c = 0
while count >= 0:
c = b + c
b += 1
count -= 1
print(c)
else:
print(a+b)
get_sum(a,b)
|
82899902560dfe0c6e998219da43747ae9d27a47 | pragatirahul123/list | /Column_Row.py | 275 | 4.03125 | 4 | row=int(input("enter a row ="))
column=int(input("enter a column="))
index=1
a=1
empty=[]
while index<=column:
empty1=[]
b=a
j=1
while j<=row:
empty1.append(b)
j+=1
b+=1
empty.append(empty1)
index+=1
a+=column
print(empty)
|
c48488acf1b5ed2d9241d25de853cb6dd908d9b3 | novayo/LeetCode | /For Irene/Hash/0036_Valid_Sudoku.py | 862 | 3.75 | 4 | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
length = len(board)
rows = [set() for i in range(length)] # x
cols = [set() for i in range(length)] # y
blocks = [set() for i in range(length)] # x // 3 * 3 + y // 3 => block index
# O(m*n)
for x in range(length):
for y in range(length):
if board[x][y] == '.':
continue
index_blocks = x // 3 * 3 + y // 3
if board[x][y] in rows[x] or board[x][y] in cols[y] or board[x][y] in blocks[index_blocks]:
return False
rows[x].add(board[x][y])
cols[y].add(board[x][y])
blocks[index_blocks].add(board[x][y])
return True |
9243413b092ab761be6044db031aedd31bc44bed | sudheerachary/Kaggle | /digit_recognizer/script.py | 18,192 | 3.53125 | 4 |
# coding: utf-8
# # MNIST using CNN Keras - Acc 0.996 (TOP 4%)
# ### **Sudheer Achary**
#
# * **1. Introduction**
# * **2. Data preparation**
# * 2.1 Load data
# * 2.2 Check for null and missing values
# * 2.3 Normalization
# * 2.4 Reshape
# * 2.5 Label encoding
# * 2.6 Split training and valdiation set
# * **3. CNN**
# * 3.1 Define the model
# * 3.2 Set the optimizer and annealer
# * 3.3 Data augmentation
# * **4. Evaluate the model**
# * 4.1 Training and validation curves
# * 4.2 Confusion matrix
# * **5. Prediction and submition**
# * 5.1 Predict and Submit results
# # 1. Introduction
#
# This is a 11 layers Sequential Convolutional Neural Network for digits recognition trained on MNIST dataset. I choosed to build it with keras API (Tensorflow backend) which is very intuitive. Firstly, I will prepare the data (handwritten digits images) then i will focus on the CNN modeling and evaluation.
#
# I achieved 99.685% of accuracy with this CNN trained on GTX 1080Ti for 50 epochs with batch size of 64 using tensorflow-gpu with keras.
#
# This Notebook follows three main parts:
#
# * The data preparation
# * The CNN modeling and evaluation
# * The results prediction and submission
#
# <img src="http://img1.imagilive.com/0717/mnist-sample.png" ></img>
# In[ ]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
get_ipython().magic(u'matplotlib inline')
np.random.seed(2)
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import itertools
from keras.utils.np_utils import to_categorical # convert to one-hot-encoding
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization
from keras.optimizers import Adagrad
from keras.regularizers import l2
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
sns.set(style='white', context='notebook', palette='deep')
# # 2. Data preparation
# ## 2.1 Load data
# In[ ]:
# Load the data
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
# In[ ]:
Y_train = train["label"]
# Drop 'label' column
X_train = train.drop(labels = ["label"],axis = 1)
# free some space
del train
g = sns.countplot(Y_train)
Y_train.value_counts()
# We have similar counts for the 10 digits.
# ## 2.2 Check for null and missing values
# In[ ]:
# Check the data
X_train.isnull().any().describe()
# In[ ]:
test.isnull().any().describe()
# I check for corrupted images (missing values inside).
#
# There is no missing values in the train and test dataset. So we can safely go ahead.
# ## 2.3 Normalization
# We perform a grayscale normalization to reduce the effect of illumination's differences.
#
# Moreover the CNN converg faster on [0..1] data than on [0..255].
# In[ ]:
# Normalize the data
X_train = X_train / 255.0
test = test / 255.0
# ## 2.3 Reshape
# In[ ]:
# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)
X = X_train.values.reshape(-1,28,28,1)
test = test.values.reshape(-1,28,28,1)
# Train and test images (28px x 28px) has been stock into pandas.Dataframe as 1D vectors of 784 values. We reshape all data to 28x28x1 3D matrices.
#
# Keras requires an extra dimension in the end which correspond to channels. MNIST images are gray scaled so it use only one channel. For RGB images, there is 3 channels, we would have reshaped 784px vectors to 28x28x3 3D matrices.
# ## 2.5 Label encoding
# In[ ]:
# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])
Y = to_categorical(Y_train, num_classes = 10)
# Labels are 10 digits numbers from 0 to 9. We need to encode these lables to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0]).
# ## 2.6 Split training and valdiation set
# In[ ]:
# Set the random seed
random_seed = 894
# In[ ]:
# Split the train and the validation set for the fitting
X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size = 0.001, random_state=random_seed)
# I choosed to split the train set in two parts : a small fraction (0.01%) became the validation set which the model is evaluated and the rest (99.99%) is used to train the model.
#
# Since we have 42 000 training images of balanced labels (see 2.1 Load data), a random split of the train set doesn't cause some labels to be over represented in the validation set.
# We can get a better sense for one of these examples by visualising the image and looking at the label.
# In[ ]:
# Some examples
g = plt.imshow(X_train[0][:,:,0])
# # 3. CNN
# ## 3.1 Define the model
# I used the Keras Sequential API, where you have just to add one layer at a time, starting from the input.
#
# The first is the convolutional (Conv2D) layer. It is like a set of learnable filters. I choosed to set 64 filters for the first conv2D layer with kernel of size 5x5 and 128 filters for the next two conv2D layers with 3x3 kernels respectively. Each filter transforms a part of the image (defined by the kernel size) using the kernel filter. The kernel filter matrix is applied on the whole image. Filters can be seen as a transformation of the image.
#
# The CNN can isolate features that are useful everywhere from these transformed images (feature maps).
#
# The second important layer in CNN is the pooling (MaxPool2D) layer. This layer simply acts as a downsampling filter. It looks at the 2 neighboring pixels and picks the maximal value. These are used to reduce computational cost, and to some extent also reduce overfitting. We have to choose the pooling size (i.e the area size pooled each time) more the pooling dimension is high, more the downsampling is important.
#
# Combining convolutional and pooling layers, CNN are able to combine local features and learn more global features of the image.
#
# 'elu' is the exponential linear unit (activation function. The **elu** activation function is used to add non linearity to the network.
#
# The Flatten layer is use to convert the final feature maps into a one single 1D vector. This flattening step is needed so that you can make use of fully connected Dense layers after some convolutional/maxpool layers. It combines all the found local features of the previous convolutional layers.
#
# In the end i used the features in two fully-connected (Dense) layers which is just artificial an neural networks (ANN) classifier. In the last layer (Dense(10, activation="softmax")) the net outputs distribution of probability of each class.
# In[ ]:
model = Sequential()
model.add(Conv2D(filters = 64, kernel_size = (5,5), padding = 'Same', activation ='elu', input_shape = (28,28,1)))
model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation ='elu',))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(BatchNormalization())
model.add(Conv2D(filters = 128, kernel_size = (3,3), padding = 'Same', activation ='elu'))
model.add(Conv2D(filters = 128, kernel_size = (3,3), padding = 'Same', activation ='elu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(BatchNormalization())
model.add(Conv2D(filters = 256, kernel_size = (3,3), padding = 'Same', activation ='elu'))
model.add(Conv2D(filters = 256, kernel_size = (3,3), padding = 'Same', activation ='elu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(BatchNormalization())
model.add(Flatten())
model.add(Dense(256, activation = "elu"))
model.add(Dense(10, activation = "softmax"))
model.summary()
# ## 3.2 Set the optimizer and annealer
#
# Once our layers are added to the model, we need to set up a score function, a loss function and an optimisation algorithm.
#
# We define the loss function to measure how poorly our model performs on images with known labels. It is the error rate between the oberved labels and the predicted ones. We use a specific form for categorical classifications (>2 classes) called the "categorical_crossentropy".
#
# The most important function is the optimizer. This function will iteratively improve parameters (filters kernel values, weights and bias of neurons ...) in order to minimise the loss.
#
# I choosed Adam (with default values), it is a very effective optimizer. The Adam update adjusts the Adagrad method in a very simple way in an attempt to reduce its aggressive, monotonically decreasing learning rate.
# We could also have used Stochastic Gradient Descent ('sgd') optimizer, but it is slower than Adam.
#
# The metric function "accuracy" is used is to evaluate the performance our model.
# This metric function is similar to the loss function, except that the results from the metric evaluation are not used when training the model (only for evaluation).
# In[ ]:
# Define the optimizer
optimizer = Adagrad(lr=0.01, epsilon=1e-4, decay=0.0)
# In[ ]:
# Compile the model
model.compile(optimizer = 'Adam' , loss = "categorical_crossentropy", metrics=["accuracy"])
# <img src="http://img1.imagilive.com/0717/learningrates.jpg"> </img>
# In order to make the optimizer converge faster and closest to the global minimum of the loss function, i used an annealing method of the learning rate (LR).
#
# The LR is the step by which the optimizer walks through the 'loss landscape'. The higher LR, the bigger are the steps and the quicker is the convergence. However the sampling is very poor with an high LR and the optimizer could probably fall into a local minima.
#
# Its better to have a decreasing learning rate during the training to reach efficiently the global minimum of the loss function.
#
# To keep the advantage of the fast computation time with a high LR, i decreased the LR dynamically every X steps (epochs) depending if it is necessary (when accuracy is not improved).
#
# With the ReduceLROnPlateau function from Keras.callbacks, i choose to reduce the LR by half if the accuracy is not improved after 3 epochs.
# In[ ]:
# Set a learning rate annealer
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.00001)
# In[ ]:
epochs = 50
batch_size = 64
# ## 3.3 Data augmentation
# In order to avoid overfitting problem, we need to expand artificially our handwritten digit dataset. We can make your existing dataset even larger. The idea is to alter the training data with small transformations to reproduce the variations occuring when someone is writing a digit.
#
# For example, the number is not centered
# The scale is not the same (some who write with big/small numbers)
# The image is rotated...
#
# Approaches that alter the training data in ways that change the array representation while keeping the label the same are known as data augmentation techniques. Some popular augmentations people use are grayscales, horizontal flips, vertical flips, random crops, color jitters, translations, rotations, and much more.
#
# By applying just a couple of these transformations to our training data, we can easily double or triple the number of training examples and create a very robust model.
#
# The improvement is important :
# - Without data augmentation i obtained an accuracy of 98.114%
# - With data augmentation i achieved 99.7% of accuracy
# In[ ]:
# With data augmentation to prevent overfitting (accuracy 0.99286)
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range = 0.1, # Randomly zoom image
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=False, # randomly flip images
vertical_flip=False) # randomly flip images
datagen.fit(X_train)
# For the data augmentation, i choosed to :
# - Randomly rotate some training images by 10 degrees
# - Randomly Zoom by 10% some training images
# - Randomly shift images horizontally by 10% of the width
# - Randomly shift images vertically by 10% of the height
#
# I did not apply a vertical_flip nor horizontal_flip since it could have lead to misclassify symetrical numbers such as 6 and 9.
#
# Once our model is ready, we fit the training dataset .
# In[ ]:
# Fit the model
history = model.fit_generator(datagen.flow(X_train, Y_train, batch_size=batch_size),
epochs = epochs, validation_data = (X_val,Y_val),
verbose = 1, steps_per_epoch=X_train.shape[0] // batch_size
, callbacks=[learning_rate_reduction])
# In[ ]:
# Set a learning rate annealer
learning_rate_reduction = ReduceLROnPlateau(monitor='acc',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.00001)
# In[ ]:
history = model.fit_generator(datagen.flow(X, Y, batch_size=batch_size),
epochs = 10, verbose = 1, steps_per_epoch=X.shape[0] // batch_size
, callbacks=[learning_rate_reduction])
# # 4. Evaluate the model
# ## 4.1 Confusion matrix
# Confusion matrix can be very helpfull to see your model drawbacks.
#
# I plot the confusion matrix of the validation results.
# In[ ]:
# Look at confusion matrix
X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.3, random_state=random_seed)
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# Predict the values from the validation dataset
Y_pred = model.predict(X_val)
# Convert predictions classes to one hot vectors
Y_pred_classes = np.argmax(Y_pred,axis = 1)
# Convert validation observations to one hot vectors
Y_true = np.argmax(Y_val,axis = 1)
# compute the confusion matrix
confusion_mtx = confusion_matrix(Y_true, Y_pred_classes)
# plot the confusion matrix
plot_confusion_matrix(confusion_mtx, classes = range(10))
# Here we can see that our CNN performs very well on all digits with few errors considering the size of the validation set (4 images).
#
# However, it seems that our CNN has some little troubles with the 4 digit, they are misclassified as 9. Sometime it is very difficult to catch the difference between 4 and 9 when curves are smooth.
# Let's investigate for errors.
#
# I want to see the most important errors . For that purpose i need to get the difference between the probabilities of real value and the predicted ones in the results.
# In[ ]:
# Display some error results
# Errors are difference between predicted labels and true labels
errors = (Y_pred_classes - Y_true != 0)
Y_pred_classes_errors = Y_pred_classes[errors]
Y_pred_errors = Y_pred[errors]
Y_true_errors = Y_true[errors]
X_val_errors = X_val[errors]
def display_errors(errors_index,img_errors,pred_errors, obs_errors):
""" This function shows 6 images with their predicted and real labels"""
n = 0
nrows = 1
ncols = 3
fig, ax = plt.subplots(nrows,ncols,sharex=True,sharey=True)
for row in range(nrows):
for col in range(ncols):
error = errors_index[n]
ax[col].imshow((img_errors[error]).reshape((28,28)))
ax[col].set_title("Predicted label :{}\nTrue label :{}".format(pred_errors[error],obs_errors[error]))
n += 1
# Probabilities of the wrong predicted numbers
Y_pred_errors_prob = np.max(Y_pred_errors,axis = 1)
# Predicted probabilities of the true values in the error set
true_prob_errors = np.diagonal(np.take(Y_pred_errors, Y_true_errors, axis=1))
# Difference between the probability of the predicted label and the true label
delta_pred_true_errors = Y_pred_errors_prob - true_prob_errors
# Sorted list of the delta prob errors
sorted_dela_errors = np.argsort(delta_pred_true_errors)
# Top 6 errors
most_important_errors = sorted_dela_errors[-6:]
# Show the top 6 errors
display_errors(most_important_errors, X_val_errors, Y_pred_classes_errors, Y_true_errors)
# The most important errors are also the most intrigous.
#
# For those six case, the model is not ridiculous. Some of these errors can also be made by humans, especially for one the 9 that is very close to a 4. The last 9 is also very misleading, it seems for me that is a 0.
# In[ ]:
# predict results
results = model.predict(test)
# select the indix with the maximum probability
results = np.argmax(results,axis = 1)
results = pd.Series(results,name="Label")
# In[ ]:
submission = pd.concat([pd.Series(range(1,28001),name = "ImageId"),results],axis = 1)
submission.to_csv("cnn_mnist_datagen.csv",index=False)
|
a0f42f9387b1d3c70924a956d602d5a45801b574 | shubhamkumar27/Leetcode_solutions | /50. Pow(x, n).py | 1,043 | 3.71875 | 4 | '''
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−231, 231 − 1]
'''
class Solution:
def myPow(self, x, n):
########## ITERATIVE ###########
if n==0:
return 1
if x==1:
return 1
if n<0:
x = 1/x
n = -n
p = 1
while(n>0):
if n%2:
p *= x
x *= x
n = n//2
return p
########## RECURSIVE ###########
if n==0:
return 1
if x==1:
return 1
if n<0:
return 1/self.myPow(x,-n)
if n%2:
return x*self.myPow(x, n-1)
else:
return self.myPow(x*x,n//2)
######### DIRECT ##############
return x**n
|
b5f1e09f3beba9cc72f301708ef5af4a36456648 | lovehhf/LeetCode | /473. 火柴拼正方形.py | 2,703 | 3.84375 | 4 | # -*- coding:utf-8 -*-
"""
还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一个正方形的方法。不能折断火柴,可以把火柴连接起来,并且每根火柴都要用到。
输入为小女孩拥有火柴的数目,每根火柴用其长度表示。输出即为是否能用所有的火柴拼成正方形。
示例 1:
输入: [1,1,2,2,2]
输出: true
解释: 能拼成一个边长为2的正方形,每边两根火柴。
示例 2:
输入: [3,3,3,3,4]
输出: false
解释: 不能用所有火柴拼成一个正方形。
注意:
给定的火柴长度和在 0 到 10^9之间。
火柴数组的长度不超过15。
"""
from typing import List
class Solution:
def dfs(self, nums, arr, i, r) -> bool:
"""
回溯
:param nums: 火柴数组
:param arr: 表明当前状态下每条边长的长度
:param i: 当前搜索到的下标
:param r: 正方形边长
:return:
"""
if all(x == r for x in arr):
return True
for j in range(4):
if nums[i] + arr[j] > r:
continue
arr[j] += nums[i]
if self.dfs(nums, arr, i + 1, r):
return True
arr[j] -= nums[i] # 恢复现场
return False
def makesquare(self, nums: List[int]) -> bool:
if len(nums) < 4 or sum(nums) & 3:
return False
r = sum(nums) >> 2
print(r)
arr = [0] * 4
nums.sort(reverse=True) # 逆序排序, 尽可能降低dfs深度
return self.dfs(nums, arr, 0, r)
# 超时, 待优化
# class Solution:
#
# def dfs(self, nums, i, u, k):
# """
# :param i: 当前搜索到的数
# :param u: 已经搜索到的火柴
# :return:
# """
# if u > self.r:
# return False
#
# if u == self.r:
# # if k == 3:
# # return True
# if k == 2:
# return True if sum(nums) & 3 else False
# u = 0
# k += 1
#
# for j in range(len(nums)):
# if self.dfs(nums[:i] + nums[i + 1:], j, u + nums[j], k):
# return True
# return False
#
# def makesquare(self, nums: List[int]) -> bool:
# if len(nums) < 4:
# return False
#
# nums.sort(reverse=True)
# s = sum(nums)
# self.r = s // 4
# if (s & 3 or any([x > self.r for x in nums])):
# return False
# return self.dfs(nums, 0, 0, 0)
nums = [5,5,5,5,4,4,4,4,3,3,3,3]
s = Solution()
print(s.makesquare(nums))
|
e30f37d0c9b24ec8403f066958d3440518bc0655 | a2606844292/vs-code | /test2/高阶内置函数/Lambda表达式介绍/lambda.py | 213 | 4.03125 | 4 | # def add(num1,num2):
# result=num1+num2
# return result
# print(add(1,2))
#相加
super_add=lambda num1,num2:num1+num2
#相乘
multiply=lambda a,b:a*b
print(super_add(1,2))
print(multiply(1,2)) |
772a20c6a9bfb34237023103516daf5b8c8f6190 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2252/60616/246505.py | 776 | 3.765625 | 4 | def equal(str1,str2):
list1=list(str1)
list2=list(str2)
bo1=True
bo2=True
for item1 in list1:
if(item1 not in list2):
bo1=False
break
else:
if(list1.count(item1)!=list2.count(item1)):
bo1=False
break
for item2 in list2:
if(item2 not in list1):
bo2=False
break
else:
if(list1.count(item2)!=list2.count(item2)):
break
return bo1 and bo2
testNum=int(input())
for i in range(testNum):
text = input()
string=input()
size1=len(text)
size2=len(string)
ans=[]
for j in range(size1-size2+1):
if(equal(text[j:j+size2],string)):
ans.append(j)
print(len(ans)) |
1eab756b91109eedde9759649f097190749013d1 | torvigoes/Exercicios-Python3 | /Mundo 1/ex017.py | 323 | 3.671875 | 4 | from time import sleep
from math import hypot
print('=' * 30)
print(' ')
b = float(input('Digite o comprimento do cateto oposto: '))
c = float(input('Agora, do cateto adjacente: '))
print(' ')
print('Calculando...')
sleep(0.5)
print(f'O comprimento da hipotenusa é de: {hypot(b, c):.2f}')
print(' ')
print('=' * 30)
|
49798b437f753831ecd6813f46fade067d01f4b7 | ryuldashev/student_project | /init.py | 4,488 | 3.9375 | 4 | def init():
print("\n----------")
print("\nDeveloper: Malik Khodjaev / Разработчик: Малик Ходжаев")
print("\n----------")
print("\nHello. To choose English just type: eng")
print("\nIf you want to exit just type: exit")
print("\nПривет. Чтобы выбрать русский язык введи: рус")
print("\nЧтобы выйти из программы введи: выйти")
print("\n----------")
lang = input()
if lang == "eng" or lang == "рус":
choose_lang(lang)
elif lang == "exit" or lang == "выйти":
"\nBye! Пока!"
exit()
else:
print("\nJust enter eng to use English. Otherwise the program will be closed.")
print("\nПросто введите рус, чтобы использовать русский язык. Иначе программа будет закрыта.")
def eng_language():
import engFunc
print("\nOK. You have chosen English.")
print("Now you can enter any word in English and we will make a phonetic analysis of it.")
word = input()
# Отправляем слово на проверку
word_result = engFunc.get_english_word(word)
# Выводим результаты фонетического анализа слова
print("\nThe result of phonetic analysis of the word «", word, "»")
# Вывод количества букв в вводимом слове
print("\nTotal letters in the «", word, "»:", word_result[0])
# Вывод количества гласных и их количества
print("\nTotal consonants in the word «", word, "»:", len(word_result[1]))
print("The list of consonants of the word: «", word, "»:", word_result[1])
# Вывод количества согласных и их количества
print("\nTotal vowels in the word «", word, "»:", len(word_result[2]))
print("The list of vowels of the word: «", word, "»:", word_result[2])
print("\n Do you want to enter another word? (yes/no)?")
if input() == "yes":
eng_language()
elif input() == "no":
print("See you soon! Увидемся!")
exit()
else:
print("Just enter yes or no, nothing more. Otherwise the program will be closed.")
input()
def ru_language():
import ruFunc
print("\nХорошо. Вы выбрали русский язык.")
print("Теперь вы можете ввести любое слово по-русски и мы сделаем их фонетический анализ.")
word = input()
# Отправляем слово на проверку
word_result = ruFunc.get_russian_word(word)
# Выводим результаты фонетического анализа слова
print("\nРезультат фонетического анализа слова «", word, "»")
# Вывод количества букв в вводимом слове
print("\nВсего букв в слове «", word, "»:", word_result[0])
# Вывод количества гласных и их количества
print("\nВсего гласных в слове «", word, "»:", len(word_result[1]))
print("Список гласных в слове: «", word, "»:", word_result[1])
# Вывод количества согласных и их количества
print("\nВсего согласных в слове «", word, "»:", len(word_result[2]))
print("Список согласных в слове: «", word, "»:", word_result[2])
print("\n Вы хотите ввести другое слово? (да/нет)?")
if input() == "да":
ru_language()
elif input() == "нет":
print("See you soon! Увидемся!")
exit()
else:
print("Просто введите да или нет, ничего более. Иначе программа будет закрыта.")
input()
def choose_lang(lang):
if lang == "eng":
eng_language()
elif lang == "рус":
ru_language()
elif lang == "exit" or lang == "выйти":
print("See you soon! Увидемся!")
exit()
# [/] Запуск системы
init()
# Запуск системы [/]
|
24d0a41c6f9fb8b47dd90e027dbf63ec6f3be40a | Jamp-H/Neural-Network | /neural_network.py | 6,742 | 3.65625 | 4 | ###############################################################################
#
# AUTHOR(S): Joshua Holguin
# DESCRIPTION: program that will inplement stochastic gradient descent algorithm
# for a one layer neural network
# VERSION: 0.0.1v
#
###############################################################################
import numpy as np
from sklearn.preprocessing import scale
from scipy.stats import norm
from random import randint
# Function: n_net_one_split
# INPUT ARGS:
# X_mat : train inputs/feature matrix, n_observations x n_features
# y_vec : train outputs/label vector, n_observations x 1
# max_epochs : int scalar > 1
# step_size : double scalar > 0
# n_hidden_units : int scalar>1, number of hidden units
# is_subtrain : logical vector, size n_observations
# Return: loss_values, V_mat, w_vec
def n_net_one_split(X_mat, y_vec, max_epochs, step_size, n_hidden_units, is_subtrain):
# initialize design of layered neural network
design = (X_mat.shape[1], n_hidden_units, 1)
# divide X_mat and y_vec into train, validation (60% 40% respectively)
train = (is_subtrain == 1)
validation = (is_subtrain == 0)
# get subtrain_X and subtrain_y of of training data and is_subtrain
subtrain_X = X_mat[train, :]
y_train = y_vec[train]
print(subtrain_X.shape)
val_X = X_mat[validation, :]
y_val = y_vec[validation]
y_tild__train_vector = np.where(y_train==0, -1, y_train)
y_tild__val_vector = np.where(y_val==0, -1, y_val)
# initilize V_mat list (weight matrix n_features x n_hidden_units)
# used to predict hidden units given input
V_mat = []
w_vec = np.random.randn(X_mat.shape[1])
w_vec /= 10
# loop though design of layers
# initilize each matrix; add to V_mat
for i in range(0,len(design) - 1):
# calculate dimensions and num of entries of new matrix
new_mat_row = design[i + 1]
new_mat_col = design[i]
num_of_entries = new_mat_row * new_mat_col
# create matrix
new_mat = np.random.randn(new_mat_row, new_mat_col)
new_mat /= 10
# append matrix to list of matricies (V_mat)
V_mat.append(new_mat)
# loop over epochs (k=1 to max_epochs)
# update the parameters using the gradients with respect to each
# subtrain observation
for epoch in range(0,max_epochs):
grad_matrix_list = []
# loop over data points in subtrain data set
index = 0
for point in subtrain_X:
# compute the gradients of V_mat/w_vec with respect to a
# single observation in the subtrain set
y_tild = y_tild__train_vector[index]
h_list = forward_prop(point, V_mat)
grad_matrix_list.append(h_list[0])
hidden_layer = np.matmul(h_list[1], (1-h_list[1]))
with_weight = V_mat[1] * hidden_layer
grad = with_weight * point.reshape(57,1)
grad_matrix_list.append(grad)
# update V.mat/w.vec by taking a step (scaled by step.size)
# in the negative gradient direction
for layer in range(0, len(grad_matrix_list)):
grad_matrix_list[layer] -= step_size * grad_matrix_list[layer]
index += 1
# compute the logistic loss on the subtrain/validation sets
# store value in loss_values (log loss
# formula log[1+exp(-y_tild * real_pred)])
prediction_h_units_sub = forward_prop(subtrain_X.transpose(), grad_matrix_list)
prediction_h_units_val = forward_prop(X_val.transpose(), grad_matrix_list)
train_loss = np.log(1+np.exp(-y_tild__train_vector*prediction_h_units_sub))
val_loss = np.log(1+np.exp(-y_tild__val_vector*prediction_h_units_val))
loss_values = [train_loss, val_loss]
return (loss_values, V_mat, w_vec)
# return outputs (loss_values, V_mat, w_vec)
# Function: convert_data_to_matrix
# INPUT ARGS:
# file_name : the csv file that we will be pulling our matrix data from
# Return: data_matrix_full
def convert_data_to_matrix(file_name):
data_matrix_full = np.genfromtxt( file_name, delimiter = " " )
return data_matrix_full
# Function: split matrix
# INPUT ARGS:
# X : matrix to be split
# Return: train, validation matriceis
def split_train_val(X):
train, validation = np.split( X, [int(.6 * len(X))])
return (train, validation)
# Function: log_loss_csv
# INPUT ARGS:
# log_loss_data : tuple containing log loss data for the NN
# Return: none, creates csv files
def log_loss_csv(log_loss_data):
with open("Neural_Net_Log_Loss_Train.csv", mode = 'w') as file:
fieldnames = ['epochs', 'train error']
writer = csv.DictWriter(file, fieldnames = fieldnames)
writer.writeheader()
epoch = 0
for error in log_loss_data[0][0].items():
writer.writerow({'epoch': epoch,
'train error': error})
epoch +=1
with open("Neural_Net_Log_Loss_Val.csv", mode = 'w') as file:
fieldnames = ['epochs', 'train error']
writer = csv.DictWriter(file, fieldnames = fieldnames)
writer.writeheader()
epoch = 0
for error in log_loss_data[0][1].items():
writer.writerow({'epoch': epoch,
'val error': error})
epoch +=1
# Function: forward_prop
# INPUT ARGS:
# in_mat : input row from matrix (1 x features)
# list_of_weights : List of maricies containing weights
# Return: hidden layer vector
def forward_prop(in_row, list_of_weights):
h_list = []
h_list.append(in_row)
for layer in range(0, len(list_of_weights) - 1):
weight = list_of_weights[layer]
hidden_layer = h_list[layer]
a_vec = np.matmul(weight, hidden_layer)
if layer == len(list_of_weights) - 1:
h_list.append(a_vec)
else:
a_vec = 1/(1 + np.exp(-a_vec))
h_list.append(a_vec)
return h_list
# Function: main
# INPUT ARGS:
# none
# Return: none
def main():
np.random.seed(1)
file_name = "spam.data"
# Get data into matrix form
X_mat_full = convert_data_to_matrix(file_name)
X_mat_full_col_len = X_mat_full.shape[1]
# split data into a matrix and vector of pred values
X_mat = X_mat_full[:,:-1]
y_vec = X_mat_full[:,X_mat_full_col_len-1]
# Scale matrix for use
X_sc = scale(X_mat)
is_subtrain = np.zeros(X_mat.shape[0])
for i in range(0,X_mat.shape[0]):
if i < X_mat.shape[0] * .6:
is_subtrain[i] = 1
else:
is_subtrain[i] = 0
# dummy data so not use to actually test
loss_data = n_net_one_split(X_sc, y_vec, 2, .05, 3, is_subtrain)
main()
|
1a9db869ce4c8253505b40d88a912a7d3ad804c1 | jickyi521/LeetCode | /LeetCode/python/maxdepth_0908.py | 735 | 3.625 | 4 |
class TreeNode(object):
def __init__(self, x):
set.val = x
self.left = None
self.right = None
def maxDepth(self, root):
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
def maxDepth2(self, root):
stack = []
if root is not None:
stack.append((1, root))
depth = 0
while stack != []:
current_depth, node = stack.pop()
if node is not None:
depth = max(depth, current_depth)
stack.append((current_depth + 1, node.left))
stack.append((current_depth + 1, node.right))
return depth
|
68d7fbffaf21bb55bc4f87b06accb70e3a2f90a9 | jroca72/eltao | /python/mysql/inicio.py | 392 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def letra_nif(dni):
mi_lista=["T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E","O"]
valor = dni / 23
valor = valor * 23
valor = dni - valor
return mi_lista[valor]
dninumero = input("dame el número de dni : ")
letra = letra_nif(dninumero)
print "la letra del DNI es : " + letra
|
5f76d936bc8c8ff3702a0b15e787e5e3f994947b | gilmp/python-development | /python-strings/string_negative.py | 223 | 4.03125 | 4 | #!/usr/bin/env python
################################
# THIS IS ABOUT STRING METHODS #
################################
astring = "Hello world!"
print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))
|
a7d2559a4329b505dac935b533c571dbe5f8d8bc | EdnaMota/python3_estudos | /desafio011.py | 249 | 3.75 | 4 | l = float(input('Largura da parede: '))
a = float(input('Altura da parede: '))
print(f'Sua parede tem a dimensão de {l:.1f} x {a:.1f} e sua área é de {l * a:.1f}m².\nPara pintar essa parede, você precisará de {(l * a) / 2} litros de tinta.') |
5b09821907d3f8bebd48c2c371520833a6a3226e | nerozenJL/My-LeetCode-solutions | /53-maximum subarray.py | 1,188 | 3.640625 | 4 | class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max=0
sum=0
if nums:
max=nums[0]
for num in nums:
"""
ÿһλԪأֻ뵽ԭеУԭУ
ʱҪԭУлĿܣܼˣֻ
ʱԭеûбҪˣԭкΪ
ķӸλʼߴһλʼ
ʣµ⣺δȫ
"""
if sum <= 0:
if num > 0:
sum = num
if sum>=max:
max=sum
else:
if max<0 and num>max:
max = num
else:
sum+=num
if num>0 and sum>max:
max=sum
return max |
cf8ac4aac0049005be39feaf6c0ccbb316b8b384 | nobinson20/codingChallenges | /NotInInteger.py | 378 | 3.65625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(nums):
# write your code in Python 3.6
nums = list(set(nums))
nums.sort()
cnt = 1
for e in nums:
if e < 0:
continue
if e != cnt:
return cnt
if e > 0:
cnt += 1
return cnt |
640d458328b630c6ebb3e302b006949f9b3dd3d9 | prodigiousnishu/Advance_Python_Batch3 | /Puthon Basics List_Organising day-7.py | 1,249 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
a = ['dog','cat','fish','duck']
# In[2]:
#pop -- its a function which is used to delete a element from the last of a list
a.pop()
# In[3]:
a
# In[4]:
a.pop(0)
# In[5]:
a
# In[6]:
motorcycles = ['honda','yamaha','suzuki','ducati']
motorcycles
# In[7]:
motorcycles.remove('ducati')
print(motorcycles)
# In[10]:
cars = ['bmw','audi','toyota','benz']
# In[11]:
cars.sort()
print(cars)
# by using sort the lit will be sorted permanently and can not be rechanged
# In[12]:
cars
# In[13]:
cars_1 = ['maruti','tata','landrover','jaguar']
print('here is the original list:')
print(car_1)
# In[17]:
cars_y = ['maruti','tata','landrover','jaguar']
print('here is the original list:')
print(cars_y)
print('here is the sorted list:')
cars_y.sorted()
print(cars_y)
# In[ ]:
#IQ: what is the difference between sorted and sort
#sort will change the position of element permanently
#sort will change the position of element temporarily
# In[18]:
#IQ: how to reverse elemt in list
cars_1 = ['maruti','tata','landrover','jaguar']
cars_1.reverse()
print(cars_1)
# In[ ]:
cars_1 = ['maruti','tata','landrover','jaguar']
cars_1.count()
print(cars_1)
|
3c84571cdff8c4789dce826efdf901eb241a9974 | Hank02/capstone | /previous_versions/test.py | 698 | 3.515625 | 4 | import sys
def func1():
commands = len(sys.argv)
if commands == 2:
name = sys.argv[1]
elif commands == 3:
name = sys.argv[2]
print("hello {}".format(name))
def func2():
print("Yep!")
print("That did it!")
def func3():
print("Oh my...")
print("It seems you git this down!")
print("Congrats!")
if __name__ == '__main__':
if sys.argv[1] == "func1":
func1()
if sys.argv[1] == "func2":
func2()
if sys.argv[1] == "func3":
func3()
# import datetime
# import calendar
# today = str(datetime.date.today())
# today = today.split("-")
# print(today[1])
# month = calendar.month_abbr[int(today[1])]
# print(month) |
31ec1d061c747bf311c5ba022522cc579018be29 | eezhal92/flask-sqlalchemy | /book_lib/application/service/borrowing.py | 680 | 3.765625 | 4 | """."""
class Borrowing:
"""."""
def __init__(self, book_repo):
"""."""
self.book_repo = book_repo
def borrow(self, book_title):
"""."""
available_copies = self._find_available_copies(book_title)
if (len(available_copies) == 0):
raise Exception(
"No copies of title `{}` are available".format(book_title)
)
to_be_borrowed_book = available_copies[0]
self.book_repo.mark_borrowed(to_be_borrowed_book)
return to_be_borrowed_book
def _find_available_copies(self, book_title):
"""."""
return self.book_repo.find_available_copies(book_title)
|
9667ccf5af99d1a0a267ef0af658ac7c50316b66 | mak705/Python_interview | /python_prgrams/testpython/if2.py | 124 | 3.96875 | 4 | #num=("enter the one digit number")
num = 7
if num > 3:
print("3")
if num >= 5:
print("5")
if num == 7:
print("7")
|
ec886cfe93e365b85a34a2f6a82fde99183cb280 | TMJUSTNOW/Algorithm-Implementations | /4. Linear-Time Selection/dSelect.py | 9,452 | 4.03125 | 4 | # Michael D. Salerno
def dSelect(A, k):
'''
My implementation of an O(n) deterministic selection algorithm.
Input: A list of comparable elements, A, and the order of the element to
be selected, k.
Output: The kth order statistic (the kth smallest element in A).
The deterministic selection algorithm is very similar to the randomized
selection algorithm (see my documentation for rSelect.py). The key
differences are the manner in which the pivot is chosen (using the median of
medians method) and the fact that the algorithm is no longer performed
in-place, since it requires creating copies of portions of the input array.
For the sake of demonstration, the parameters to the recursion in this
implementation do not make use of pointers to the boundaries of the portion
of the array being recursively searched; instead, the parameters consist of
an array, its size, and the order of the element being searched for.
Procedure Overview:
0. If the length of the array is 1, return its element
1. Logically break A into n/5 groups of size 5 each (plus remainders)
2. Sort each group (e.g., using Merge Sort)
3. Copy n/5 medians (i.e., middle element of each sorted group) into
new array C
4. Recursively compute the median of C and return this as the pivot
5. Partition A around the pivot. (Let i = final index of the pivot)
6. If i > k, return a recursion on the left side of the array
7. If i < k, return a recursion on the right side of the array
Another key difference between rSelect and dSelect is that the dSelect
algorithm uses 2 recursive calls instead of 1.
dSelect Theorem:
For every input array of length n, dSelect runs in O(n) time.
Warning:
Although dSelect deterministically guarantees an O(n) running time, it is
not as good as rSelect in practice. This is because it has larger hidden
constants and it does not perform the selection in place.
Analysis:
Breakdown of the running times of each step of the algorithm as enumerated
in the Procedure Overview above:
0. O(1)
1. O(n)
2. O(n) - Sorting an array with 5 elements has an O(1) time complexity.
This step sorts approximately n/5 such arrays.
3. O(n)
4. T(n/5)
5. O(n)
6./7. T(7n/10) - See proof of following lemma
Key Lemma: The second recursive call (in step 6 or 7) is guaranteed to be
on an array of rough size <= 7*n/10
Rough Proof:
- Let k = n/5 = # of groups
- Let xi = ith smallest of the k "middle elements" (so pivot = xi,
where i = k/2)
Because x(k/2) is the median of medians, it is larger than about 50%
of the other middle elements. Transitively, the subgroups that these
lesser middle elements belong to also contain 2 additional elements that
are guaranteed to be less than x(k/2). So x(k/2) is greater than 3 out
of 5 (60%) of the elements in roughly 50% of the subgroups; thus, x(k/2)
is guaranteed to be greater than at least 30% of all of the elements
across the subgroups.
Similarly, x(k/2) is smaller than about 50% of the other middle
elements and a symmetric argument shows that x(k/2) is guaranteed to be
less than at least 30% of the elements across all of the subgrous.
Therefore, the upper bound on the size of the array being passed to the
second recursive call is 7/10ths of the original array size, or 7*n/10.
So, T(1) = 1 and
T(n) <= c*n + T(n/5) + T(7*n/10), where c is a constant >= 1
Strategy: Guess and check
Guess: There is some constant a (independent of n) such that T(n) <= a*n
for all n >= 1. (If this is true, the T(n) = O(n) and the algorithm is
linear-time.)
Claim: Let a = 10*c, then T(n) <= a*n for all n >= 1
(the 10 would normally be reverse-engineered from induction)
Proof (by induction on n):
Base case: T(1) = 1 <= a*1 (since a >= 1)
Inductive step: (n > 1) Inductive Hypothesis: T(k) <= a*k for all k < n
We have T(n) <= c*n + T(n/5) + T(7*n/10) (given)
<= c*n + a*(n/5) + a*(7*n/10) (inductive hypothesis)
= n*(c + 9*a/10) = a*n = O(n) (choice of a)
QED!
'''
assert 1 <= k <= len(A) #Ensure that k makes sense for an array of length len(A)
def deterministicSelection(A, n, k):
if n == 1:
return A[0]
groups = groupsOfFive(A) #break A into groups of 5
for i in range(len(groups)):
groups[i] = mergeSort(groups[i]) #sort each of the groups (O(n))
C = medians(groups) #find the medians of each group
pivot = deterministicSelection(C, len(C), n/10) #select the median of medians as the pivot; len(C) is either n/5 or n/5 + 1
p = A.index(pivot) #save the pivot's index
A[0], A[p] = A[p], A[0] #swap the pivot into the first position
switchFlag = False ##flag to be used to handle duplicate pivot values
i = 0 #initialize pointer to shadow the division between the <p and >p partitions
for j in range(1, len(A)): #j is a pointer to the next unexamined element; it separates the <p and >p partitions from the unexamined partition
if A[j] == A[0]: ##check if the next unexamined value is equal to the pivot; of this happens more than once, there are some number of duplicate pivot values
if not switchFlag:
switchFlag = True ##alternating switchFlag ensures that duplicate pivot values are split evenly
else:
i += 1
if i != j:
A[i], A[j] = A[j], A[i]
switchFlag = False
elif A[j] < A[0]:
i += 1 #increment i so that it points at the left-most element of the >p partition
if i != j: #this check avoids redundant swaps which would occur if an element greater than the pivot hasn't been found yet
A[i], A[j] = A[j], A[i] #after this swap, i points at the right-most element of the <p partition that was just swapped in
A[0], A[i] = A[i], A[0] #swap the pivot with the right-most element of the <p partition; this will also be its correct position in the final sorted list
if i == k: #check if the pivot is the kth order statistic
return A[i]
elif i > k: #if the pivot is greater than the kth order element, recurse on a copy of the left side of the array and adjust the size parameter
return deterministicSelection(A[:i], i, k)
else: #if the pivot is smaller than the kth order element, recurse on a copy the right side of the array and adjust the size and order parameters
return deterministicSelection(A[i+1:], n-(i+1), k-(i+1))
return deterministicSelection(A[:], len(A), k-1) #k-1 is passed here in order to offset to 1-based indexing from Python's native 0-based indexing
#a copy of A is passed in order to prevent the original list from being modified
def groupsOfFive(A):
'''
Breaks a list of length n into into groups of 5 elements (n/5 subgroups) and
returns them in a list of lists. The origninal elements are copied into
their respective subgroups.
Input: A list, A.
Output: A list of lists containing the n/5 subgroups
'''
groups = []
x = []
for e in A:
x.append(e)
if len(x) == 5:
groups.append(x)
x = []
if len(x) != 0:
groups.append(x)
return groups
def mergeSort(arr):
'''
My implementation of Merge Sort. For analysis see my documentation of
mergeSort.py.
'''
if len(arr) <= 1:
return arr
lhs = mergeSort(arr[:len(arr)/2])
rhs = mergeSort(arr[len(arr)/2:])
result = []
while len(lhs) != 0 and len(rhs) != 0:
if lhs[0] <= rhs[0]:
result.append(lhs.pop(0))
else:
result.append(rhs.pop(0))
if len(lhs) == 0:
result += rhs
else:
result += lhs
return result
def medians(groups):
'''
Computes the medians of the given subgroups and returns them in a list.
Input: A list of lists containing subgroups
Output: A list of the subgroups' medians
'''
result = []
for g in groups:
if len(g) %2 == 0:
result.append(g[len(g)/2 - 1]) #if the given array is even in length, identify the first of the two middle indices as the middle index
else:
result.append(g[len(g)/2])
return result |
7a3a1eb145660ce5689c40a910789ee6963da092 | Vinod096/learn-python | /lesson_02/personal/chapter_5/21_RPS_game.py | 2,245 | 4.65625 | 5 | #Write a program that lets the user play the game of Rock, Paper, Scissors against the computer.
#The program should work as follows:
#1. When the program begins, a random number in the range of 1 through 3 is generated.
#If the number is 1, then the computer has chosen rock. If the number is 2, then the computer
#has chosen paper. If the number is 3, then the computer has chosen scissors.
# (Don’t display the computer’s choice yet.)
#2. The user enters his or her choice of “rock, ” “paper, ” or “scissors” at the keyboard.
#3. The computer’s choice is displayed.
#4. A winner is selected according to the following rules:
#• If one player chooses rock and the other player chooses scissors, then rock wins.
#(The rock smashes the scissors.)
#• If one player chooses scissors and the other player chooses paper, then scissors wins.
#(Scissors cuts paper.)
#• If one player chooses paper and the other player chooses rock, then paper wins.
# (Paper wraps rock.)
#• If both players make the same choice, the game must be played again to determine
#the winner.
from random import randint
def computers_choice(number):
if number == 1:
return ("rock")
elif number == 2:
return ("paper")
else:
return ("scissors")
def players_choice(computer_choice):
print("Choose rock or paper or scissors : ")
computer = computer_choice(randint(1, 3))
print("computer choice :",computer)
while (computer):
player_choice = input("player_choice : ").lower()
if computer == "rock" and player_choice == "scissors":
print("rock wins")
print("The rock smashes the scissors.")
break
elif computer == "scissors" and player_choice == "paper":
print("scissors wins.")
print("Scissors cuts paper.")
break
elif computer == "paper" and player_choice == "rock":
print("paper wins")
print("Paper wraps rock.")
break
elif computer == player_choice:
print("play again")
break
else:
print("wrong input")
print(f"Computer: {computer}, Player Choice: {player_choice}")
players_choice(computers_choice) |
c09b845b6b1afa1787f144840caa0b2185691e55 | kayedavi/fpinpython | /src/chapter01/cafe.py | 1,259 | 3.515625 | 4 | from __future__ import annotations
from dataclasses import dataclass
from functools import reduce
from itertools import groupby
@dataclass(frozen=True)
class CreditCard:
def charge(self, price: float) -> None:
pass
@dataclass(frozen=True)
class Coffee:
price: float = 5.0
@dataclass(frozen=True)
class Payments:
def charge(self, cc: CreditCard, price: float) -> None:
pass
@dataclass(frozen=True)
class Charge:
cc: CreditCard
amount: float
def combine(self, other: Charge) -> Charge:
if self.cc == other.cc:
return Charge(self.cc, self.amount + other.amount)
else:
raise Exception("Can't combine charges to different cards")
def buy_coffee(cc: CreditCard) -> (Coffee, Charge):
cup = Coffee()
return cup, Charge(cc, cup.price)
def buy_coffees(cc: CreditCard, n: int) -> (list[Coffee], Charge):
purchases = [buy_coffee(cc)] * n
coffees, charges = zip(*purchases)
return list(coffees), reduce((lambda c1, c2: c1.combine(c2)), charges)
def coalesce(charges: list[Charge]) -> list[Charge]:
return [reduce((lambda c1, c2: c1.combine(c2)), x) for x in
[list(chgs) for credit_card, chgs in groupby(charges, lambda charge: charge.cc)]]
|
55c785aacb9d3805041f34050775d9dddf1f64cd | sergio-lira/data_structures_algorithms | /project_2/submission/problem_2.py | 1,952 | 4.53125 | 5 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
result_set = list()
recursive_search(suffix, path, result_set)
return result_set
def recursive_search(suffix, path, results):
if os.path.isfile(path):
if path.endswith(suffix):
results.append(path)
else:
return
elif os.path.isdir(path):
items = os.listdir(path)
for item in items:
recursive_search(suffix, os.path.join(path, item), results)
else:
print("Error: this path does not exist!")
return
print('\n<<< Test Case 1 >>>\nSearching for .h')
print(find_files(".h", "."))
"""Expected result:
['.\\testdir\\subdir1\\a.h',
'.\\testdir\\subdir3\\subsubdir1\\b.h',
'.\\testdir\\subdir5\\a.h',
'.\\testdir\\t1.h']"""
print('\n<<< Test Case 2 >>>\nSearching for .c')
print(find_files(".c", "."))
"""['.\\testdir\\subdir1\\a.c',
'.\\testdir\\subdir3\\subsubdir1\\b.c',
'.\\testdir\\subdir5\\a.c',
'.\\testdir\\t1.c']"""
print('\n<<< Test Case 3 >>>\nSearching for .f')
print(find_files(".f", "."))
#Expected empty set as result
print('\n<<< Test Case 4 >>>\nSearching for t1.c')
print(find_files('t1.c', "."))
#Expected a single match
print('\n<<< Test Case 5 >>>\nSearching for *.*')
print(find_files("*.*", "."))
#Expected empty set, I was trying to mess around with the .endswith function
print('\n<<< Test Case 6 >>>\nSearching for path that does not exist')
print(find_files("*.*", "not_a_path/"))
#Expected empty set, I was trying to mess around with the .endswith function
|
8d33594f74c58174b463aba1f3b365e4ef01fd5e | micgainey/Towers-of-Hanoi | /towers_of_hanoi_count.py | 1,979 | 4.15625 | 4 | """
Towers of Hanoi rules
1. You can't place a larger disk onto a smaller disk.
2. Only 1 disk can be moved at a time.
Towers of Hanoi moves is:
2^n - 1
OR
2 * previous + 1
example with 3 disks
3 towers: A. B. C.
Starting point:
1
2
3
A B C
Move1
2
3 1
A B C
Move2
3 2 1
A B C
Move3
1
3 2
A B C
Move4
1
2 3
A B C
Move5
1 2 3
A B C
Move6
2
1 3
A B C
Move7
1
2
3
A B C
"""
"""
Iterative approach:
for one disk it will take 1 move
for two disks minimum number of moves is 3
...
n - 1 disks = p
2p + 1 = minimum number of moves for n disks
number of disks minimum number of moves
1 1
2 3
3 (2 * 3) + 1 = 7
4 (2 * 7) + 1 = 15
5 (2 * 15) + 1 = 31
6 (2 * 31) + 1 = 63
7 (2 * 63) + 1 = 127
8 (2 * 127) + 1 = 255
9 (2 * 255) + 1 = 511
n - 1 p
n 2p + 1
"""
# This function will return the minimum number of moves it will take to solve TOH with n disks
def towers_of_hanoi_moves(disks):
if disks <= 0:
print('Number of disks must be greater than 0')
return
num_of_moves = 0
for i in range(0, disks):
num_of_moves = (2 * num_of_moves) + 1
# Uncomment below to see the number of moves for each disk
# print(num_of_moves)
return num_of_moves
# print(towers_of_hanoi_moves(9))
num_of_moves = int(input("Enter the number of disks: "))
print(towers_of_hanoi_moves(num_of_moves))
|
d2fbf30db61168c9609f200197e857a92a8fe29b | Chetanrajput161194/AWS-Devops | /Multiply.py | 152 | 4.15625 | 4 | def multiply(a,b):
return a*b
num1=int(input("ENter the First number :"))
num2=int(input("ENter the second number :"))
print(multiply(num1,num2))
|
396539d6f9fc1de95b699a08c65b6ed21be1dc02 | Addlaw/Python-Cert | /gas_prices.py | 1,062 | 3.640625 | 4 | ################################################################################
# Author: Addison Lawrence
# Date: 4/19/2020
# Reads file of gas prices over 52 weeks and plots them
################################################################################
import matplotlib.pyplot as plt#import matplotlib
gasprice=[]#intialize gasprice
weeks=list(range(1,53))#create list of week numbers
with open('2008_Weekly_Gas_Averages.txt') as fo:#open price file
for line in fo:
gasprice.append(float(line.rstrip()))#add each price to a list
fig, prices=plt.subplots()#begin plot figure
prices.plot(weeks,gasprice)#plot week and gasprice
prices.set_title('2008 Weekly Gas Prices')#plot title
prices.set_ylabel('Average Price (dollars/gallon)')#y label
prices.set_xlabel('Weeks (by number)')#x label
prices.set_xticks([10,20,30,40,50])#set x tick marks
prices.set_yticks([1.5,2.0,2.5,3.0,3.5,4.0])#set y tick marks
prices.set_xlim(1,52)#set y limit
prices.set_ylim(1.5,4.25)#set x limit
plt.grid()#turn on grid
plt.show()#show plot
|
f0c7059d76c15bc6b0d2abce0fd222aab9455efe | shuxu94/submarine | /src/main/submarine/navigation.py | 837 | 3.6875 | 4 | class Course(object):
def __init__(self, desx, desy):
self.desx = desx
self.desy = desy
def setStart(self, startx, starty):
self.startx = startx
self.starty = starty
def distanceOffCourse(self, currentx, currenty): # using the projection forumla to find the distance
# away from the intended course
self.desx = desx - self.startx
self.desy = desy - self.startx
self.currentx = currentx - self.startx
self.currenty = currenty - self.starty
adotb = (self.desx*self.currentx) + (self.desxy*self.currenty)
magb = math.sqrt((self.desx*self.desx) + (self.desy*self.desy))
magbsqr = magb*magb
projectx = (adotb/magbsqr) * self.desx
projecty = (adotb/magbsqr) * self.desy
disx = self.currentx - projectx
disy = self.currenty - projecty
distance = math.sqrt((disx*disx) + (disy*disy))
return distance |
45ed44673a3c46e0e5065af64a568f4c2e45a794 | aslamsikder/Complete-Python-by-Aslam-Sikder | /Aslam_07_conditinal_logic.py | 351 | 4.21875 | 4 | # If Else statement
print("Enter your marks: ")
number = int(input())
if (number>=1 and number<=100):
if (number<=100 and number>=80):
grade = 'A+'
elif (number<=80 or number>=70):
grade = 'A'
else:
grade = 'less than 70% marks!'
print("You got", grade)
else:
print("You have entered an invalid marks!") |
a7c3e3ee1788aea459a14118c8a5ab9e7d545487 | Nevermind7/codeeval | /easy/lettercase_percentage_ratio.py | 452 | 3.75 | 4 | import sys
from string import ascii_uppercase as upper, ascii_lowercase as lower
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
chars = [x for x in test.strip()]
small = [x for x in chars if x in lower]
big = [x for x in chars if x in upper]
print('lowercase: {:.2f} uppercase: {:.2f}'.format(100*len(small)/len(chars),
100*len(big)/len(chars)))
test_cases.close()
|
0a1160cdb0c9d2d944693b098eaba9043d794ed0 | friedman97/uchi | /diversity.py | 10,433 | 3.515625 | 4 | #CS121: PA 7 - Diversity Treemap
#
# Code for reading Silicon Valley diversity data, summarizing
# it, and building a tree from it.
#
# YOUR NAME: _______
import argparse
import csv
import json
import pandas as pd
import sys
import numpy as np
import treenode
import treemap
import textwrap
class TreeNode(object):
def __init__(self, label, count=None, children=None):
'''
construct a Tree node
Inputs:
label: (string) a label that identifies the node
count: (float) an application specific weight
children: (list of TreeNodes) child nodes, or None if no children
'''
self._label = label
self._count = count
self._children = children
self._verbose_label = None
def get_children_as_dict(self):
return self._children
def get_children_as_list(self):
return [self._children[x] for x in sorted(self._children)]
@property
def label(self):
return self._label
@property
def count(self):
return self._count
@property
def children(self):
return self._children
@property
def verbose_label(self):
return self._verbose_label
@label.setter
def label(self, label):
self._label = label
@count.setter
def count(self, count):
self._count = count
@children.setter
def children(self, children):
self._children = children
@verbose_label.setter
def verbose_label(self, verbose_label):
self._verbose_label = verbose_label
def num_children(self):
if self._children is None:
return 0
else:
return len(self._children)
def tree_print_r(self, prefix, last, kformat, vformat, maxdepth):
if maxdepth is not None:
if maxdepth == 0:
return
else:
maxdepth -= 1
if len(prefix) > 0:
if last:
lprefix1 = prefix[:-3] + u" └──"
else:
lprefix1 = prefix[:-3] + u" ├──"
else:
lprefix1 = u""
if len(prefix) > 0:
lprefix2 = prefix[:-3] + u" │"
else:
lprefix2 = u""
if last:
lprefix3 = lprefix2[:-1] + " "
else:
lprefix3 = lprefix2 + " "
if self.count is None:
ltext = (kformat).format(self.label)
else:
ltext = (kformat + ": " + vformat).format(self.label, self.count)
ltextlines = textwrap.wrap(ltext, 80, initial_indent=lprefix1,
subsequent_indent=lprefix3)
print(lprefix2)
print(u"\n".join(ltextlines))
if self.children is None:
return
else:
for i, st in enumerate(self.children):
if i == len(self.children) - 1:
newprefix = prefix + u" "
newlast = True
else:
newprefix = prefix + u" │"
newlast = False
st.tree_print_r(newprefix, newlast, kformat, vformat, maxdepth)
def tree_print(self, kformat="{}", vformat="{}", maxdepth=None):
'''
Inputs: self: (the tree object)
kformat: (format string) specifying format for label
vformat: (format string) specifying format for label and count
maxdepth: (integer) indicating number of levels to print.
None sets no limit
Returns: no return value, but a tree is printed to screen
'''
self.tree_print_r(u"", False, kformat, vformat, maxdepth)
###############
# #
# Your code #
# #
###############
def load_diversity_data(filename):
'''
Load Silicon Valley diversity data and print summary
Inputs:
filename: (string) the name pf the file with the data
Returns: a pandas dataframe
'''
data = pd.read_csv(filename)
comp = np.unique(data["company"])
num_comp = len(comp)
print("Diversity data comes from the following", num_comp, "companies:")
for c in comp:
print(c)
print()
employees = sum(data["count"])
print("The data includes", employees, "employees")
print()
print("##########" + "\n" + "gender" + "\n" + "###########" + '\n' + '')
mf = set(data["gender"])
for g in mf:
gender = data.loc[data["gender"] == g]
gennum = sum(gender['count'])
print(g, ":", gennum)
print()
print("##########" + "\n" + "race" + "\n" + "###########" + '\n' + '')
pple = set(data["race"])
for p in pple:
race = data.loc[data["race"] == p]
racenum = sum(race['count'])
print(p, ":", racenum)
print()
print("##########" + "\n" + "job_category" + "\n" + "###########" + '\n' + '')
professions = set(data["job_category"])
for j in professions:
job = data.loc[data["job_category"] == j]
jobnum = sum(job['count'])
print(j, ":", jobnum)
print()
return data
def prune_tree(original_sub_tree, values_to_discard):
'''
Returns a tree with any node whose label is in the list values_to_discard
(and thus all of its children) pruned. This function should return a copy
of the original tree and should not destructively modify the original tree.
The pruning step must be recursive.
Inputs:
original_sub_tree: (TreeNode) a tree of type TreeNode whose internal
counts have been computed. That is, compute_internal_counts()
must have been run on this tree.
values_to_discard: (list of strings) A list of strings specifying the
labels of nodes to discard
Returns: a new TreeNode representing the pruned tree
'''
evaltree = TreeNode(original_sub_tree.label, original_sub_tree.count)
final_tree = evaltree.children= []
if original_sub_tree.num_children() > 0:
for child in original_sub_tree.children:
if child.label not in values_to_discard:
prunedtree = prune_tree(child, values_to_discard)
if prunedtree:
final_tree.append(prunedtree)
return evaltree
else:
if original_sub_tree.label in values_to_discard:
return None
else:
return TreeNode(original_sub_tree.label, original_sub_tree.count)
#############################
# #
# Our code: DO NOT MODIFY #
# #
#############################
def data_to_tree(data, hierarchy):
'''
Converts a pandas DataFrame to a tree (using TreeNode) following a
specified hierarchy
Inputs:
data: (pandas.DataFrame) the data to be represented as a tree
hierarchy: (list of strings) a list of column names to be used as
the levels of the tree in the order given. Note that all
strings in the hierarchy must correspond to column names
in data
Returns: a tree (using the TreeNode class) representation of data
'''
if hierarchy is None or len(hierarchy) == 0:
raise ValueError("Hierarchy must be a non-empty list of column names")
# create dictionary of possible values for each level of the hierarchy
hierarchy_labels = {}
for level in hierarchy:
if level not in data.columns:
raise ValueError("Column " + str(level) + " included in the \
hierarchy, but does not exist in data", data.columns)
else:
hierarchy_labels[level] = data[level].unique()
return create_st(data, hierarchy, hierarchy_labels, "")
def create_st(relevant_rows, hierarchy, hierarchy_labels, level_label):
'''
Recursively creates subtrees
'''
if len(hierarchy) == 0:
# Return leaf node with count of relevant rows
return treenode.TreeNode(level_label,
count=relevant_rows["count"].sum())
else:
curr_children = []
curr_level = hierarchy[0]
hierarchy = list(hierarchy[1:])
for level_value in hierarchy_labels[curr_level]:
curr_rows = relevant_rows[relevant_rows[curr_level] == level_value]
curr_children.append(create_st(curr_rows, hierarchy,
hierarchy_labels, level_value))
return treenode.TreeNode(level_label, children=curr_children)
def parse_args(args):
parser = argparse.ArgumentParser(description='Drawing treemaps.')
parser.add_argument('-i', '--input_filename', nargs=1,
help="input filename", type=str,
default=["data/Reveal_EEO1_for_2016.csv"])
parser.add_argument('-o', '--output_filename', nargs=1,
help="output filename", type=str, default=[None])
parser.add_argument('-w', '--width', nargs=1,
help="initial bounding rectangle width", type=float,
default=[1.0])
try:
return parser.parse_args(args[1:])
except Exception as e:
print(e)
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) > 1:
args = parse_args(sys.argv)
data = load_diversity_data(args.input_filename[0])
# Subdivide by job category and then gender
example_tree = data_to_tree(data, ["job_category", "gender"])
treemap.compute_internal_counts(example_tree)
treemap.compute_verbose_labels(example_tree)
treemap.draw_treemap(example_tree,
bounding_rec_height=1.0,
bounding_rec_width=args.width[0],
output_filename=args.output_filename[0])
# Subdivide by job category, gender, and race
example_tree = data_to_tree(data, ["job_category", "gender", "race"])
treemap.compute_internal_counts(example_tree)
treemap.compute_verbose_labels(example_tree)
treemap.draw_treemap(example_tree,
bounding_rec_height=1.0,
bounding_rec_width=args.width[0],
output_filename=args.output_filename[0])
# Subdivide by company, gender, and race
example_tree = data_to_tree(data, ["company", "gender", "race"])
treemap.compute_internal_counts(example_tree)
treemap.compute_verbose_labels(example_tree)
treemap.draw_treemap(example_tree,
bounding_rec_height=1.0,
bounding_rec_width=args.width[0],
output_filename=args.output_filename[0])
# Show gender and race filtering for only small companies
original_tree = data_to_tree(data, ["company", "gender", "race"])
treemap.compute_internal_counts(original_tree)
example_tree = prune_tree(original_tree,
["Adobe", "Airbnb", "Apple", "Cisco", "eBay",
"Facebook", "Google", "HP Inc.", "HPE",
"Intel", "Intuit", "LinkedIn", "Lyft",
"Nvidia", "Salesforce", "Square", "Twitter",
"Uber"])
treemap.compute_internal_counts(example_tree)
treemap.compute_verbose_labels(example_tree)
treemap.draw_treemap(example_tree,
bounding_rec_height=1.0,
bounding_rec_width=args.width[0],
output_filename=args.output_filename[0])
# Show non-white and non-asian Silicon Valley workforce
original_tree = data_to_tree(data, ["company", "race", "gender"])
treemap.compute_internal_counts(original_tree)
example_tree = prune_tree(original_tree, ["Asian", "White"])
treemap.compute_internal_counts(example_tree)
treemap.compute_verbose_labels(example_tree)
treemap.draw_treemap(example_tree,
bounding_rec_height=1.0,
bounding_rec_width=args.width[0],
output_filename=args.output_filename[0])
else:
print("doing nothing besides loading the code...")
|
f10a866f8ee17c9ff122446bff7dc223d55cad24 | dev-dougie/curso_em_video-python | /Módulo 1/EX_050.py | 194 | 3.78125 | 4 | a1 = int(input('Digite o primeiro termo: '))
r = int(input('Digite a razão da PA: '))
an = a1 + (10 - 1) * r
for c in range(a1, an + r, r):
print('{}'.format(c), end=' -> ')
print('FINISH') |
2b562aef25095c472298fbb920a5288e941ec9d8 | XingXing2019/LeetCode | /LinkedList/LeetCode 2 - AddTwoNumbers/AddTwoNumbers_Python/main.py | 765 | 3.734375 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
res = ListNode()
point = res
cur, car = 0, 0
while l1 is not None and l2 is not None:
cur = (l1.val + l2.val + car) % 10
car = (l1.val + l2.val + car) // 10
point.next = ListNode(cur)
point = point.next
l1 = l1.next
l2 = l2.next
if l1 is None and l2 is not None:
l1 = ListNode()
if l1 is not None and l2 is None:
l2 = ListNode()
if car != 0:
point.next = ListNode(car)
return res.next
|
5feb4c0555fa708a02118ec71b0b7adb5ccb2c78 | Atheelah/FileHandling_Counting-Lines | /main.py | 195 | 3.625 | 4 | f = open("zen_text.txt")
Count = 0
Content = f.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Count += 1
print("This is the number of lines in the file :")
print(Count)
|
e3eb1cc0bfdfaa689ed91bf1333963aa5f59120d | MaximilianSchnatterer/Assignements | /Assignments1/exercise3.py | 200 | 4.0625 | 4 | list = [1,2,3]
list.append(4)
print(list)
list.clear()
print(list)
list = [1,2,3]
list.pop(0)
print(list)
list = [1,2,3]
list.reverse()
print(list)
list = [3,1,2]
list.sort(reverse=1)
print(list) |
272c8db43a7b42239726f75f70523a735b646bd1 | sujanchory/Online-Py | /Extra_Candies.py | 188 | 3.609375 | 4 | candies=list(map(int,input().split()))
ec=int(input())
l=list()
for i in candies:
if i+ec>=max(candies):
l.append('true')
else:
l.append('false')
print(l)
|
72df413026cf7cf863065994956932ca41c6e304 | JohanRivera/Python | /bases.py | 6,701 | 4.09375 | 4 | a = "hola"
b = 5
c = 3.3
d = True
print (type(a), type(b), type(c), type(d))
c = True
print('\n', type(c))
b = "mundo"
saludo = a + b
print(saludo)
#OPERADORES
b = 5
c = 3.3
print(b+c)
print(b-c)
print(b*c)
print(b/c)
print(b//c) # aproximación para darun entero
print(b**c) # potencia
print(b%c) # modulo
print(b and c)
print(b or c)
#Secuencia de datos. Vectores
#Estructuras de datos
#1. Listas
#Las listas como son objetos pueden almacenar cualquier variable.
#Las listas se pueden recorrer de manera positvia y negativa, por ejemplo, tenemos una
#lista n=['hola', 'nooo','bb'], y llamamos a n[-1] estamos llamando al ultimo valor de la lista que es 'bb',
# y así sucesivamente.
#Para eliminar un elemento de una lista, sigamos con la lista n del comentario anterior, y escribimos
# del n[1]; en ese momento estamos eliminando la segunda posicion de la lista que es 'nooo'. Adicionalmente,
# también se puede eliminar un elemento de una lista utilizando la función remove la cual se utiliza
# escribiendo literalmente el cual elemento se desea borrar, utilizando la misma lista n sería:
# n.remove('hola'), y eliminaría justo el elemento que se esta escribiendo.
lista = [] #Primera forma de declarar una lista
lista2 = list() #Segunda forma de decalrar una lista
#Ejemplo
#Otra forma para añadir elementos a una lista, es especificando en cual posición deseo que el
# nuevo elemento se añada mediante la función insert, siguiendo con la lista n del ejemplo, quedaría:
# n.insert(0, 'adios'), en este ejemplo la lista quedaría así: n = ['adios', 'hola', 'nooo', 'bb']
lista.append(1)
lista.append(2)
lista.append(3)
lista.append(4)
lista.append(5)
lista.append('Hola')
lista.append(7)
for i in lista: #El i es realmente un apuntador en un arreglo dinamico.
print(i)
#Rangos
for j in range(10): #Cuando se utiliza rango, funciona para arrojarme la posición de un vector
print(j)
#Tuplas
#Es un vector estatico, al declararla se vuelve inmutable.
Tupla = ('Hola', 1, 2, 6.7) #Forma de declararlo
print(Tupla) #Al imprimir una tupla se observa en parentesis
print(lista) # Y al imprimir una lista se observa entre corchetes cuadrados
print(type(lista), type(Tupla))
#Diccionario
#Un diccionario es un vector que se almacena por parejas, en donde le primer valor esla lave "key" y el segundo valor
#es el contenido o el valor. NOTA: LA LLAVE NO SE PUEDEN REPETIR.
#Para agregar nuevos elementos al diccionario seria, diccionario['amarillo'] = 'yellow'
#Para eliminar es mediante el uso de del la cual sería, del(diccionario['amarillo'])
#Adicionalmente, puedo dentro de un diccionario utilizar otro diccionario o lista ejemplo:
# diccionario = {'Johan':{'edad' : 22, 'estatura' : 170 cm}, 'Pedro':[23, 170 cm]}
#Una forma para llamar un diccionario y que no salga error si no encuentra la llave se utiliza el metodo get
# el cual se usa así: print(diccionario.get{'Johan', 'No existe esta clave en el diccionario'}),
# entonces dado el caso que no exista esa clave va a salir el msj que se dejo predeterminado de lo contrario
# saldra el valor que tendra esa clave
#Una forma para saber si una clave existe dentro de un diccionario es utilizando: 'Johan' in diccionario
# esa instrucción nos arrojara un valor booleano, True si existe y False si no existe.
#Además, para mostrar unicamente las claves del diccionario se utiliza el metodo keys que sería:
# print(diccionario.keys()). Y si en caso contrario solo quieres saber los valores se utiliza el metodo values
# que sería: print(diccionario.values()), y si se quiere saber ambas cosas se puede utilizar el metodo items o
# sencillamante llamar al diccionario, que sería: print(diccionario.items()) o print(diccionario)
#Por otro lado, si se desea ver cuantos elementos tiene mi diccionario se utiliza el metodo len
# que sería: len(equipo), esto nos indica numericamente cuantos elementos tiene mi diccionario
#Por último, si se desea eliminar todo el diccionario se ejecutaría el metodo clear:
# diccionario.clear()
diccionario = dict() #Forma de declarar un diccionario 1
diccionario2 = {} #Forma de declarar un diccionario 2
diccionario = {
'johan' : 22,
'felipe' : 23,
'saludo' : "hola",
}
for key in diccionario:
print("llave: ", key, " contenido: ", diccionario[key])
#Conjuntos
#set, es un set al igual que en los diccionarios las variables no se pueden repetir.
listaprueba = [1,1,2,2,3,3,4,4]
print(listaprueba)
listaprueba = set(listaprueba) #El set lo utilizamos en algun vector para eliminar variables repetidas.
print(listaprueba)
dset = {1,2,3,4,5,'hola',1}
print(dset)
#Sentencias
#Condicionales
var1 = 1
var2 = 10
#Condicionales anidados
if var1 == var2:
print('Es igual')
elif var1 > var2:
print('Es mayor var1')
else:
print('No sirve')
#ciclos
for x in 'hola':#Recorre la palabra, letra por letra
print(x)
else: #Funciona para cuando acabe el ciclo hacer una acción inmediata
print('hola')
j=0
while j < 10:
j+=1
print(j)
else: #Funciona para cuando acabe el ciclo hacer una acción inmediata
print("Se salio prro")
#Funciones regulares, se pueden llamar a si mismas dentro de la función.
def holaMundo():
print("Hola mundo")
def suma(x=0,y=0): #Le puedo dar valores por defecto a cualquier variable que no seciba un valor.
return x+y
def ParOImpar(x):
return (x%2 == 0)
#A continuación se puede ver como se hace el manejo de errores en las funciones para que el programa
# no se salga porque encuentra un error, sino que siga ejecutando si no es grave
import random
def genNumAleatorio(min,max): #Función que genera un numero aleatorio entre un rango
try:
if min > max:
return random.randint(max,min)
return random.randint(min,max)
except TypeError:
print("Debes escribir numeros")
return -1
def factorial(num):
try:
resultado = num
for i in range(num-1,1,-1):
resultado *= i
return resultado
except TypeError:
print("Debes escribir un numero")
return -1
def numerosEntre(a,b):
try:
if a>b:
cambio = a
a = b
b = cambio
for i in range(a+1,b):
print(i)
except TypeError:
print("Debes escribir un numero")
return -1
#Funciones Lambdas, estas funciones lambdas son funciones de una linea de codigo las cuales pueden recibir
#la cantidad de parametros que se desee desde 0 hasta infinito.
flambda = lambda a, b, c, d: a*b/c+d-10
print(flambda(10,20,50,100))
#Estructurar el codigo mediante una función principal
if __name__ == '__main__':
holaMundo()
suma(10,10)
ParOImpar(11)
|
d56618884e7a38473c7324d0fde345bf93c31f15 | prasoonjain123/DSA | /Sorting Algo/SelectionSort.py | 369 | 4.0625 | 4 | # By setting the min of array at start
def selectionSort(arr):
for i in range(len(arr)-1):
for j in range(i+1,len(arr)):
if arr[j]<arr[i]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print(arr)
selectionSort([5,6,2,9,7,3])
selectionSort(['idhf','wiuf','aedho','prasoon','prashant','pradeep']) |
4d8bb7d38f8cf702fd9e99996c31cd6836d948f9 | shobhit20091995/MLDL-iNeuron | /Assignmnet_python/assignment 2.py | 450 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 02:56:46 2021
@author: shobhit kumar
"""
# star pattern code -- part 1
for i in range(5):
for j in range(i+1):
print("* ",end="")
print("\n")
for i in reversed(range(5)):
for j in range(i-1):
print("* ",end="")
print("\n")
# part 2
print("reversing the input word --\nineuron ")
a='ineuron'
for i in reversed(a):
print(i,end='')
|
987f59d573f52a399f03b633592e858284474665 | cforee/juxt | /juxt.py | 962 | 3.84375 | 4 | #!/usr/bin/python
import sys, random
# "juxtaposer" - Christopher S. Foree
# Takes a series of arguments specifying syntactic categories of English speech
# and generates a random juxtaposition of words resembling a sentence (of sorts)
word_set = []
allowed_syntactic_categories = ['adj','adv','art','nou','pre','pro','ver']
args = sys.argv[1:]
# show help if no command line arguments were provided
if len(args) < 1:
print 'USAGE: "python juxt.py ' + ' '.join(allowed_syntactic_categories) + '"'
# iterate through each command line argument, select a word at random from
# each specified syntactic category, then append it to our word set ("sentence")
for arg in args:
short_arg = arg[0:3]
word_file = './syntactic_categories/' + short_arg + '.txt'
if short_arg not in allowed_syntactic_categories: continue
with open (word_file, "r") as word_list: word_set.append(random.choice(word_list.read().splitlines()))
# output the word set
print ' '.join(word_set)
|
5f20ef7638ef6f27b41cf30f70c28fbf3fb387f9 | jasolovioff/combat_sys_magic | /Creature.py | 1,154 | 3.5625 | 4 | from Card import Card
'''
Creatures
Creatures fight for you: they can attack during the combat phase of your turn and block during the combat phase of an
opponent’s turn. You can cast a creature as a spell during your main phase, and it remains on the battlefield as a
permanent. Creatures enter the battlefield with "summoning sickness," which means that a creature you control can’t
attack (or use an ability that has in its cost) until it starts your turn under your control. You can block with a
creature no matter how long it’s been on the battlefield.
'''
class Creature(Card):
toughness = 0
power = 0
# uncolored, white, black, blue, red, green
summon_costs = {"uncolored": 0, "white": 0, "black": 0, "blue": 0, "red": 0, "green": 0}
name = ""
def __init__(self, name, toughness, power, summon_costs):
self.toughness = toughness
self.power = power
self.summon_costs = summon_costs
self.name = name
def get_toughness(self):
return self.toughness
def get_power(self):
return self.power
def get_summon_costs(self):
return self.summon_costs
|
bcc153ca42653a3aeacdc99bd30239ec9403fbc7 | srinanpravij/DevPython | /multiIFGrading.py | 310 | 3.875 | 4 | # @Author : Vijayalakshmi K @Time : 12/5/2020 8:16 PM
num = int(input("Enter the number:"))
#print(type(num))
if num >= 90:
print("Grade A")
elif num >= 80:
print("Grade B")
elif num >= 70:
print("Grade C")
elif num >= 60:
print("Grade D")
else:
print("score not enough to grade")
exit(0)
|
f552b8937c2c4f2bbe83da63c2a6398d2379f2bb | starrcaft/InformationProtection | /assignment/[IS00]_03_201603867_조성환/bruteforce/프로그램/bruteforce.py | 1,159 | 3.8125 | 4 | MAX_KEY_SIZE = 26
def getMode():
while True:
print('Enter either "encrypt" or "e" or "decrypt" or "d". ')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('The value you entered its invalid')
def getFileName():
print('Enter your file name:')
return input()
def getKey():
key = 0
inputKey = open('key.txt', 'rb').read().decode()
return inputKey.split(',')
def encrypt(mode, fileName, key):
outputFileName = 'encrypt.txt'
if mode[0]== 'd':
outputFileName = 'decrypt.txt'
translated = ''
outputFile = open(outputFileName, 'wb')
inputFile = open(fileName, 'rb')
message = inputFile.read().decode()
count=0
for keyInput in key :
for symbol in message:
translated += shift(symbol, keyInput[count])
count=(count+1)%len(keyInput)
outputFile.write((translated+'\n').encode())
translated=""
outputFile.close()
inputFile.close()
print('En(De)cryption complete')
def shift(symbol, key):
return chr(ord(symbol)^ord(key))
encrypt(getMode(),getFileName(), getKey()) |
5d36998f5fcfaf962aa6a01b87229e814cd97059 | hunterkorgel/Advent-of-Code-2019 | /day1.py | 853 | 3.90625 | 4 | ### Advent of Code
### Day 1
fuel_total = 0
additional_fuel = 0
filename = 'day1input.txt'
def fuelcalc(number):
answer = ((number / 3)//1) - 2
return answer
def fuelsum(number):
total = 0
number = int(number)
while fuelcalc(number) > 0:
total += fuelcalc(number)
number = fuelcalc(number)
return total
with open(filename) as file_object:
for line in file_object:
mass = int(line)
fuel = fuelsum(mass)
fuel_total += fuel
print(fuel_total)
#print("Total fuel = " + str(fuel_total) + ".")
additional_fuel = ((fuel_total / 3)//1) - 2
while additional_fuel > 0:
# print("Adding " + str(additional_fuel) + " fuel.")
fuel_total += additional_fuel
additional_fuel = ((additional_fuel / 3)//1) - 2
print(fuel_total)
|
8b83e0a5e44f6de326dc1e673cb3e258142fd2c1 | soultalker/workon | /TuLingXueYuan/爱因斯坦阶梯问题.py | 835 | 3.75 | 4 | #爱因斯坦阶梯问题:有一个长阶梯,若每次上2阶,最后剩1阶;若每次上3阶,最后剩2阶;若每次上5阶,最后剩4阶;若每次上
#6阶,最后剩5阶;若每次上7阶,最后正好不剩。阶梯至少多少阶
#1、自编
i = 1
while i:
if i % 2 != 1:
i += 1
continue
elif i % 3 != 2:
i += 1
continue
elif i % 5 != 4:
i += 1
continue
elif i % 6 != 5:
i += 1
continue
elif i % 7 != 0:
i += 1
continue
else:
print(i)
break
#2、答案
x = 1
while x :
if (x % 2 == 1) \
and (x % 3 == 2) \
and (x % 5 == 4) \
and (x % 6 == 5) \
and (x % 7 == 0):
print(x)
break
else:
x += 1
print('循环结束') |
ede74bf15d9dcabb138aa839caafe63140299d2e | frinellkd/ListsSlicing | /test.py | 151 | 3.703125 | 4 | new_list = [1,2,3,4,5,6,7,8]
value = 3
def cust_inst(new_list):
new_list[:] = new_list[::-1]
print new_list
cust_inst(new_list)
print new_list |
b46e85ec17c3af76c7133cd8e54425effea0b01b | IsauraRs/PythonInter | /Basico/Jueves/ProgFuncional/Decoradores2.py | 573 | 3.78125 | 4 | #3
# decorador que agrega un mensaje con el nombre de la funcion
def nombre(funcion):
def decorada(*parms): # * se usa para indicar que la funcion puede tener 0 o mas parametros
# acciones nuevas de la funcion
print("Se ha iniciado la funcion %s"%(funcion.__name__))
return funcion(*parms) #funcion original
return decorada
def cubo(n):
print (n**3)
@nombre # se puede indicar el decorador usando @ para que se llame solo
def suma(a,b):
print (a+b)
F=nombre(cubo) # sin usar @
F(2)
suma(3,7) # usando @
|
443f43d8573c1f93becc0c91150fcc81f5a82634 | fly8764/LeetCode | /sort/insert_sort.py | 9,983 | 3.5625 | 4 | class Solution1:
def __init__(self):
self.size = 0
def insetSort(self,nums):
#T(n) = n**2
#从前往后遍历
size = len(nums)
if size < 2:
return nums
for i in range(1,size):
j = i-1
temp = nums[i]
#扫描,从后往前扫描
while j > -1 and nums[j] > temp:
nums[j+1] = nums[j] #较大值往后挪
j -= 1
nums[j+1] = temp
return nums
def shellSort(self,nums):
#T(n) = n*logn
# 实际遍历时,不是 在一定间隔下,把一个子序列简单插入排序后,再对下一个子序列排序
# 而是 把所有的从前(nums[d])到后逐元素的进行,排序时找到前面间隔d的元素比较
# 一种子序列拍完了
size = len(nums)
if size < 2:
return nums
d = size//2
while d > 0:
for i in range(d,size):
temp = nums[i]
j = i - d
while j > -1 and nums[j] > temp:
#这里注意 nums[j] > temp而不是 nums[j]> nums[j+d](下面第一行会更行nums[j+d])
nums[j+d] = nums[j]
j -= d
nums[j+d] = temp
d //= 2
return nums
def bubbleSort(self,nums):
#T(n) = n**2
size = len(nums)
if size < 2:return nums
for i in range(1,size):
for j in range(i-1,-1,-1):
if nums[j] > nums[j+1]:
temp = nums[j+1]
nums[j+1] = nums[j]
nums[j] = temp
return nums
# def quickSort(self,nums):
#递归
#方法一:开辟新的数组
# size = len(nums)
# if size < 2:return nums
# temp = nums[0]
# left_sub = []
# right_sub = []
#
# for i in range(1,size):
# if nums[i] < temp:
# left_sub.append(nums[i])
# else:
# right_sub.append(nums[i])
# left = self.quickSort(left_sub)
# right = self.quickSort(right_sub)
# return left+[temp] + right
# def quickSort(self,nums,s,t):
#这里理解错了,
#实际上,每次swap 都是在调整 pivot的位置,当左右指针相等时,pivot的位置也调整好了,
#不用在最后再次调整 开头与i的位置元素,即 nums[left] = temp
# left = s
# right = t
# if s < t:
# temp = nums[s]
# while left < right: #从两边往中间扫描,直到left == right
# while right > left and nums[right] > temp:
# right -= 1
# if left < right: #看是上面哪个条件跳出来的
# 先不管 nums[left]的大小如何,先交换到右边的nums[right]再说,到那边再比较
# tmp = nums[left]
# nums[left] = nums[right]
# nums[right] = tmp
# left += 1
# while left < right and nums[left] < temp:
# left += 1
# if left < right:#先不管 nums[right]的大小如何,先交换到左边的nums[left]再说,到那边再比较
# tmp = nums[right]
# nums[right] = nums[left]
# nums[left] = tmp
# right -= 1
# nums[left] = temp #这一步不需要
# self.quickSort(nums,s,left-1)
# self.quickSort(nums,left+1,t)
def swap(self,nums,i,j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
def partition(self,nums,s,t):
#从左往右逐个扫描,而不是像上面那个解法,左右两边同时向中间扫描,直到相等
#这种方法 每次需要调整位置时,都要交换一次位置,操作数比较多
pivot = s
index = pivot + 1
temp = nums[pivot]
for i in range(pivot+1,t+1):
if nums[i] < temp:
self.swap(nums,i,index)
index += 1
self.swap(nums,pivot,index-1)
return index - 1
def quickSort(self,nums,s,t):
if s == t:return nums
elif s < t:
# 不要把partition写在里面,不然变量的作用范围容易受到影响;
# 最好写在外面
pivot = self.partition(nums, s, t)
self.quickSort(nums, s, pivot - 1)
self.quickSort(nums, pivot + 1, t)
def selectSort(self,nums):
#类似于冒泡排序,只不过,是在找到未排列 列表中的最小元素与 表头元素交换
size = len(nums)
def mergeSort(self,nums):
#递归,从上到下 递归,从下到上返回;
#递归题目:先假设 递归函数存在,拿过来直接用;然后,考虑如何处理边界情况
size = len(nums)
if size < 2:return nums
mid = size//2
left = nums[:mid]
right = nums[mid:]
return self.merge(self.mergeSort(left),self.mergeSort(right))
def merge(self,left,right):
res = []
while left and right:
if left[0] < right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
while left:
res.append(left.pop(0))
while right:
res.append(right.pop(0))
return res
def buildMaxheap(self,nums):
#这里从size//2开始往前遍历有两个好处
#1.类似于从完全二叉树的倒数第二层开始调整堆,2*i+1 2*i+2分别对应 节点i的左右子节点
#2.从后往前,从下往上,一层一层地“筛选”,保证最大的元素在堆顶。类似于冒泡
self.size = len(nums)
for i in range(self.size//2,-1,-1):
self.heapify(nums,i)
def heapify(self,nums,i):
left = 2*i + 1
right = 2*i + 2
largest = i
if left < self.size and nums[left] > nums[largest]: largest = left
if right < self.size and nums[right] > nums[largest]: largest = right
if largest != i:
#继续递归,使得上面调整后,下面的堆 仍然符合最大/小 堆的要求
self.swap(nums, i, largest)
self.heapify(nums, largest)
def heapSort(self,nums):
#最大堆排序
self.bubbleSort(nums)
for i in range(self.size-1,0,-1):
#把堆顶元素放到后面,最小元素放在堆顶,后面再重新调整堆;同时为处理的列表长度减1
self.swap(nums,0,i)
self.size -= 1
#从堆顶开始重新调整堆,原先的堆整体往上升了一层
self.heapify(nums,0)
return nums
def buildMinheap(self,nums):
self.size = len(nums)
for i in range(self.size//2,-1,-1):
self.heapifyMin(nums,i)
def heapifyMin(self,nums,i):
left = 2*i + 1
right = 2*i + 2
least = i
if left < self.size and nums[left] < nums[least]: least = left
if right < self.size and nums[right] < nums[least]:least = right
if least != i:
self.swap(nums,i,least)
self.heapifyMin(nums,least)
def heapSortMin(self,nums):
#T(n) = (n/2)logn + nlogn
#要保证 不改变 完全二叉树的 结构,因为在调整堆时,有 left = 2*i + 1 等的存在,要用到堆的结构
#因此,最小堆排序只能 额外申请一个数组,每次保存 堆顶的最小值,
#之后把右小角的值 交换到 堆顶,删除末尾元素,修改堆的长度,再次调整堆
res = []
self.buildMinheap(nums)
for i in range(self.size):
res.append(nums[0])
#把最大元素放到堆顶,之后删掉最后一个元素,修改堆的长度
self.swap(nums,0,self.size-1)
nums.pop()
self.size -= 1
self.heapifyMin(nums,0)
return res
def radixSort(self,nums):
maxx = max(nums)
bit = 0
while maxx:
bit += 1
maxx //= 10
mod = 10
dev = 1
for i in range(bit):
temp = {}
for j in range(len(nums)):
bucket = nums[j]%mod//dev
if bucket not in temp:
temp[bucket] = []
temp[bucket].append(nums[j])
cur = []
for idx in range(10):
if idx in temp:
cur.extend(temp[idx])
nums = cur[:]
mod *= 10
dev *= 10
return nums
class Solution:
def quickSort(self,nums,s,t):
if s >=t:
return
# 这里需要额外的变量保存边界索引,
l,r = s,t
temp = nums[l]
while l < r:
while r > l and nums[r] > temp:
r -= 1
if r > l:
nums[l] = nums[r]
l += 1
while l < r and nums[l] < temp:
l += 1
if l < r:
nums[r] = nums[l]
r -= 1
nums[l] = temp
self.quickSort(nums,s,l-1)
self.quickSort(nums,l+1,t)
def heapSort(self,nums):
pass
if __name__ == '__main__':
so = Solution()
nums = [4,1,5,3,8,10,28,2]
print(nums,'raw')
print(sorted(nums),'gt')
# res = so.insetSort(nums[:])
# print(res)
# res2 = so.shellSort(nums[:])
# print(res2)
# res3 = so.bubbleSort(nums[:])
# print(res3,'bubbleSort')
so.quickSort(nums,0,len(nums)-1)
print(nums)
# res = so.mergeSort(nums)
# print(res)
res = so.heapSort(nums[:])
print(res)
# res = so.heapSortMin(nums[:])
# print(res)
# res = so.radixSort(nums[:])
# print(res) |
cea032ce90b96197d9792740dc5a8953df65c8a5 | hanas001/Stepik | /3.2_7_v01.py | 393 | 3.890625 | 4 | x = [5, 5, 12, 9, 20, 12, 3, 5, 12]
def f(x):
'''
Function makes square root from the given number
:param x: is number
:return: square root from the number
'''
return (x**2)
dictionary = {}
result = ()
for i in x:
if result not in dictionary:
result = f ( i )
print (dictionary.setdefault ( i , result ))
else:
print ( dictionary[i])
|
e74abbba141a9de6c5b0755f83c7d0aac722a8d7 | abhay-jagtap/Learning-Python | /csv_Read.py | 252 | 3.5625 | 4 | import csv, os
if os.path.isfile('emp.csv'):
f = open('emp.csv','r')
r = csv.reader(f)
data = list(r)
for line in data:
for word in line:
print(word,'\t',end='')
print('')
else:
print('File is missing')
|
b5c755fefa7a26e80f0a3a39f7e2489e4035f611 | soojeong-DA/pre-education | /quiz/pre_python_03.py | 1,085 | 4 | 4 | """3.Enter key를 눌러 주사위를 던지게 한 후, 주사위의 눈이 높은 사람이 승리하는
간단한 주사위 게임을 만드세요
예시
<입력>
첫번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : 1~6 랜덤숫자 출력
두번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : 1~6 랜덤숫자 출력
<출력>
첫 번째(두 번째) 참가자의 승리입니다. or 비겼습니다.
"""
import random
dice = [1,2,3,4,5,6]
input1 = input('첫번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : ')
if input1 == '':
person1 = random.choice(dice)
else:
print('엔터키를 눌러주세요')
input2 = input('두번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : ')
if input2 == '':
person2 = random.choice(dice)
else:
print('엔터키를 눌러주세요')
if person1 == person2:
print('비겼습니다.')
elif person1 > person2:
print('첫번째 참가자의 승리입니다.')
else:
print('두번째 참가자의 승리입니다.') |
4e7633005dbb3ff2d8c35785220c13a875386757 | jameshilliard/PythonCode | /PythonCourseliaoxuefeng/函数式编程/ 装饰器/decorator_log.py | 890 | 3.71875 | 4 | #!/usr/bin/env python
#coding=utf-8
import functools
"""
请编写一个decorator,能在函数调用的前后打印出'begin call'和'end call'的日志。
再思考一下能否写出一个@log的decorator,使它既支持:
@log
def f():
pass
又支持:
@log('execute')
def f():
pass
"""
def log(text):
if isinstance(text, str):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s():' % (text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
else:
def wrapper():
print "Start Call"
text()
print "End Call"
return wrapper
@log
def call():
print "I am calling !!!"
call()
@log('test')
def test():
print "I am testing !!!"
test()
|
741160dd0bc2246f47281deb54e99d9ac88cb142 | samuel-santos3112/Exercicios-Python | /CalculoSalario.py | 175 | 3.9375 | 4 | valorHora = input("Informe valor hora : ")
hora = input("Informe quantidade de horas trabalhadas: ")
salario = float (valorHora) * int (hora)
print ("Salário :",salario)
|
fb7ce1e1a6e471c022dfabfe4fc853f513cb5f0b | bssrdf/pyleet | /C/ConstructTargetArrayWithMultipleSums.py | 2,088 | 3.6875 | 4 | '''
-Medium-
*Priority Queue*
*Greedy*
Given an array of integers target. From a starting array, A consisting of all 1's,
you may perform the following procedure :
let x be the sum of all elements currently in your array.
choose index i, such that 0 <= i < target.size and set the value of A at index i to x.
You may repeat this procedure as many times as needed.
Return True if it is possible to construct the target array from A otherwise
return False.
Example 1:
Input: target = [9,3,5]
Output: true
Explanation: Start with [1, 1, 1]
[1, 1, 1], sum = 3 choose index 1
[1, 3, 1], sum = 5 choose index 2
[1, 3, 5], sum = 9 choose index 0
[9, 3, 5] Done
Example 2:
Input: target = [1,1,1,2]
Output: false
Explanation: Impossible to create target array from [1,1,1,1].
Example 3:
Input: target = [8,5]
Output: true
Constraints:
N == target.length
1 <= target.length <= 5 * 10^4
1 <= target[i] <= 10^9
'''
import heapq
class Solution(object):
def isPossible(self, target):
"""
:type target: List[int]
:rtype: bool
"""
A = target
total = sum(A)
A = [-a for a in A]
heapq.heapify(A)
while True:
a = -heapq.heappop(A)
total -= a
if a == 1 or total == 1: return True
if a < total or total == 0 or a % total == 0:
return False
a %= total
total += a
heapq.heappush(A, -a)
def isPossible2(self, target):
"""
:type target: List[int]
:rtype: bool
"""
# 100%
A = target
total = sum(A)
A = [-a for a in A]
heapq.heapify(A)
while total > 1 and -A[0] > total//2:
a = -heapq.heappop(A)
total -= a
if total <= 1:
return True if total == 1 else False
a %= total
total += a
heapq.heappush(A, -a)
return total == len(A)
if __name__ == "__main__":
print(Solution().isPossible([9,3,5]))
print(Solution().isPossible2([9,3,5])) |
b2fd900500a01b4ce27a70080fd2be408e76de83 | kulterryan/Py | /HCF2NUMBER/main.py | 384 | 3.953125 | 4 | # Source: CodeWithHarry via Youtube
# URL: https://www.youtube.com/watch?v=DePWIOK1STg
# HCF/GDP using Python
num1 = int(input("Enter first number\n"))
num2 = int(input("Enter second number\n"))
if num1 > num2:
mn = num1 #mn=minimum number
else:
mn = num2
for i in range(1, mn+1):
if num1%i==0 and num2%i==0:
hcf = i
print("The HCF of two numbers is:", hcf) |
95ab2b9b9adf4422c5c68a53218b718fb8a38f4c | Mariasnezh/mariasnezh | /front_x.py | 663 | 4.1875 | 4 | list1 = []
list2 = []
emp = ""
while True:
line = input()
if line.strip() == emp:
break
a = line.startswith('x')
if a:
list1.append(line)
list1.sort()
else:
list2.append(line)
list2.sort()
list3 = list1 + list2
#print(list1)
#print(list2)
print(list3)
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
|
db75d5a3c8800a72849afe1cf4084d7e7d40333d | ybear90/coding_dojang_solution-practice- | /Lv1/DecimalNumSum.py | 436 | 3.71875 | 4 | """
각 자릿수의 합을 구할 수 있나요?
초보자 프로그래머 홍길동은 사용자가 입력한 양의정수(범위는 int)각 자리수를 더해 출력하는 프로그램을 만들고 싶어한다.
ex) 5923의 결과는 5+9+2+3인 19이다 ex) 200의 결과는 2+0+0인 2이다 ex) 6719283의 결과는 6+7+1+9+2+8+3인 36이다.
"""
iNum = input()
summ = list()
for i in iNum:
summ.append(int(i))
print(sum(summ))
|
b364ed1a4c4cac63030c3020dbf24a015469a400 | sallamander/ktorch | /examples/addition_rnn.py | 8,298 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""Sequence to sequence learning for performing addition
Reference Implementation:
https://github.com/keras-team/keras/blob/master/examples/addition_rnn.py
Input: "535+61"
Output: "596"
Padding is handled by using a repeated sentinel character (space)
Input may optionally be reversed, shown to increase performance in many tasks.
References:
- "Learning to Execute": http://arxiv.org/abs/1410.4615
- "Sequence to Sequence Learning with Neural Networks":
http://papers.nips.cc/paper/
5346-sequence-to-sequence-learning-with-neural-networks.pdf
Theoretically it introduces shorter term dependencies between source and target
Two digits reversed:
- One layer LSTM (128 hidden units), 5k training examples = ~98% train/test
accuracy in ~127 epochs
Three digits reversed:
- One layer LSTM (128 hidden units), 50k training examples = ~99% train/test
accuracy in ~34 epochs
Four digits reversed:
- One layer LSTM (128 hidden units), 400k training examples = ~99% train/test
accuracy in ~6 epochs
Five digits reversed:
- One layer LSTM (128 hidden units), 550k training examples = ~99% train/test
accuracy in ~6 epochs
"""
import numpy as np
import torch
from torch.nn import Linear, Module, ModuleList
from ktorch.metrics import categorical_accuracy
from ktorch.model import Model
# === Parameters for the model === #
DEVICE = None # change to None for CPU, 'cuda:1' for GPU 1, etc.
N_EPOCHS = 127
# Try replacing LSTM with GRU or RNN
RNN = torch.nn.LSTM
HIDDEN_SIZE = 128
BATCH_SIZE = 128
LAYERS = 1
# === Parameters for the dataset === #
DIGITS = 2
REVERSE = True
TRAINING_SIZE = 5000
# Maximum length of input is 'int + int' (e.g., '345+678'), where the maximum
# length of int is DIGITS.
MAXLEN = DIGITS + 1 + DIGITS
# All the numbers, plus sign and space for padding.
CHARS = '0123456789+ '
def generate_random_number():
"""Generate a random number for an addition problem
:return: random number with number of digits <= DIGITS
:rtype: int
"""
return int(''.join(np.random.choice(list('0123456789'))
for i in range(np.random.randint(1, DIGITS + 1))))
class CharacterTable(object):
"""Encodes and decodes true or predicted character sets"""
def __init__(self, chars):
"""Init
:param chars: characters that can appear in the input.
:type chars: str
"""
self.chars = sorted(set(chars))
self.char_indices = dict(
(char, index) for index, char in enumerate(self.chars)
)
self.indices_char = dict(
(index, char) for index, char in enumerate(self.chars)
)
def encode(self, decoded_str, num_rows):
"""One-hot encode the provided string
:param decoded_str: string to be encoded
:type decoded_str: str
:param num_rows: number of rows in the returned one-hot encoding; this
is used to keep the number of rows for each data the same
:type num_rows: int
:return: array holding a one-hot encoding of the provided string
:rtype: numpy.ndarray
"""
encoded_array = np.zeros((num_rows, len(self.chars)))
for idx_char, char in enumerate(decoded_str):
encoded_array[idx_char, self.char_indices[char]] = 1
return encoded_array
def decode(self, encoded_array, calc_argmax=True):
"""Decode the given vector or 2D array to their character output
:param encoded_array: a tensor of probabilities or one-hot
representations; or a vector of character indices (used with
`calc_argmax=False`)
:type encoded_array: numpy.ndarray
:param calc_argmax: if True, find the character index with maximum
probability, defaults to `True`.
:type calc_argmax: bool
"""
if calc_argmax:
encoded_array = encoded_array.argmax(dim=-1)
decoded_array = ''.join(
self.indices_char[val.tolist()] for val in encoded_array
)
return decoded_array
class Colors:
ok = '\033[92m'
fail = '\033[91m'
close = '\033[0m'
class SimpleRNN(Module):
def __init__(self):
"""Init"""
super().__init__()
self.encoder = RNN(len(CHARS), HIDDEN_SIZE, batch_first=True)
self.decoder_layers = ModuleList([
RNN(HIDDEN_SIZE, HIDDEN_SIZE, batch_first=True)
for _ in range(LAYERS)
])
self.linear = Linear(in_features=HIDDEN_SIZE, out_features=len(CHARS))
def forward(self, inputs):
"""Return the outputs from a forward pass of the network
:param inputs: batch of input addition problems, of shape
(BATCH_SIZE, MAXLEN, len(CHARS))
:type inputs: torch.Tensor
:return: outputs of SimpleRNN, of shape (BATCH_SIZE, DIGITS + 1)
:rtype: torch.Tensor
"""
layer, _ = self.encoder(inputs)
layer = layer[:, -1:, :].repeat(1, DIGITS + 1, 1)
for decoder_layer in self.decoder_layers:
layer, _ = decoder_layer(layer)
outputs = self.linear(layer)
outputs = torch.transpose(outputs, 1, 2)
return outputs
ctable = CharacterTable(CHARS)
questions = []
expected = []
seen = set()
print('Generating data...')
while len(questions) < TRAINING_SIZE:
a, b = generate_random_number(), generate_random_number()
# Skip any addition questions we've already seen, as well as
# any such that x+Y == Y+x (hence the sorting).
key = tuple(sorted((a, b)))
if key in seen:
continue
seen.add(key)
q = '{}+{}'.format(a, b)
# Pad the data with spaces such that it is always MAXLEN
query = q + ' ' * (MAXLEN - len(q))
ans = str(a + b)
# Answers can be of maximum size DIGITS + 1.
ans += ' ' * (DIGITS + 1 - len(ans))
if REVERSE:
# Reverse the query, e.g. '12+345 ' becomes ' 543+21'
query = query[::-1]
questions.append(query)
expected.append(ans)
print('Total addition questions:', len(questions))
print('Vectorizing questions and answers...')
x = np.zeros((len(questions), MAXLEN, len(CHARS)), dtype=np.bool)
y = np.zeros((len(questions), DIGITS + 1, len(CHARS)), dtype=np.bool)
for i, sentence in enumerate(questions):
x[i] = ctable.encode(sentence, MAXLEN)
for i, sentence in enumerate(expected):
y[i] = ctable.encode(sentence, DIGITS + 1)
x = torch.from_numpy(x).float()
y = torch.from_numpy(y).float()
y = torch.argmax(y, dim=2)
# Shuffle (x, y) in unison as the later parts of x will almost all be larger
# digits
indices = np.arange(len(y))
np.random.shuffle(indices)
x = x[indices]
y = y[indices]
# Explicitly set apart 10% for validation data that we never train over
split_at = len(x) - len(x) // 10
(x_train, x_val) = x[:split_at], x[split_at:]
(y_train, y_val) = y[:split_at], y[split_at:]
print('Training Data:')
print(x_train.shape)
print(y_train.shape)
print('Validation Data:')
print(x_val.shape)
print(y_val.shape)
network = SimpleRNN()
model = Model(network, device=DEVICE)
model.compile(
loss='CrossEntropyLoss',
optimizer='Adam',
metrics=[categorical_accuracy]
)
# Train the model each generation and show predictions against the validation
# dataset
for iteration in range(0, N_EPOCHS):
print()
print('-' * 50)
print('Iteration', iteration)
model.fit(x_train, y_train,
batch_size=BATCH_SIZE,
n_epochs=1,
validation_data=(x_val, y_val))
# Select 10 samples from the validation set at random so we can visualize
# errors
for i in range(10):
ind = np.random.randint(0, len(x_val))
rowx, rowy = x_val[np.array([ind])], y_val[np.array([ind])]
rowx = rowx.to(DEVICE)
preds = model.predict(rowx, batch_size=1)
_, preds = torch.max(preds, 1)
q = ctable.decode(rowx[0])
correct = ctable.decode(rowy[0], calc_argmax=False)
guess = ctable.decode(preds[0], calc_argmax=False)
print('Q', q[::-1] if REVERSE else q, end=' ')
print('T', correct, end=' ')
if correct == guess:
print(Colors.ok + '☑' + Colors.close, end=' ')
else:
print(Colors.fail + '☒' + Colors.close, end=' ')
print(guess)
|
6a9074729bb71a7376275f6f369d6eccd85965e2 | luarbo/HackerRank | /Day 13: Abstract Classes.py | 329 | 3.625 | 4 | #Write MyBook class
class MyBook(Book):
def __init__(self, title, author, price):
self.title=title
self.author=author
self.price=str(price)
def display(self):
print ("Title: " + self.title)
print ("Author: " + self.author)
print ("Price: " + self.price)
|
f60f4bb620cb53363e4284312655033e0be05ea4 | uqchenxi/Traffic-Flow-Prediction-Flask-App | /project/outcome_visualization.py | 4,003 | 3.671875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
NUMLIST = [str(i) for i in range(10)] # the number str from 1 to 9
"""
Construct a function to extract passenger flow and corresponding date from a stop
Parameters:
dataframe: The traffic dataframe to be extract
stop_id: The stop to be analyzed
Return:
stop: the customized data only contains time interval and passengers
"""
def create_stop_data(stop_id, dataframe):
stop = dataframe[dataframe['stop_id'] == stop_id]
stop = stop[['Time Interval', 'Passengers']]
stop['Time Interval'] = stop['Time Interval'].apply(lambda x: get_time_period(x))
stop = stop.astype('float32')
return stop
"""
Construct a function to extract passenger flow and corresponding date from a stop
Parameters:
dataframe: The traffic dataframe to be extract
route_id: The route to be analyzed
Return:
stop: the customized data only contains time interval and passengers
"""
def create_route_data(route_id, dataframe):
route = dataframe[dataframe['Route'] == route_id]
route = route[['Time Interval', 'Passengers']]
route['Time Interval'] = route['Time Interval'].apply(lambda x: get_time_period(x))
route = route.astype('float32')
return route
"""
Construct a function to extract hours and minutes from Time Interval str
Parameters:
time_str: the time string to be extract:
Returns:
s_num: the expected number of string
"""
def get_time_period(time_str):
status = False
s_num = ''
for i, num in enumerate(time_str):
if num == ' ':
status = True
if status == True:
if num in NUMLIST:
s_num += num
if len(s_num) == 4:
status = False
return s_num
# # read the processed data from passenger flow file and destination file
# dataframe = pd.read_csv('./Aggregate_Passenger_Flow_April_route.csv')
# dataframe = dataframe.dropna()
# destination = pd.read_csv('./Destination.csv')
# # dataframe['stop_id'] = dataframe['stop_id'].astype(str)
# #
# # # combine the passenger flow file and destination file
# # combined_data = pd.merge(destination, dataframe, on = 'stop_id')
# #
# # # extract the dataset of UQ lake on April 1st, 2019
# # stop_UQ = create_stop_data('1882', dataframe)
# #route_412 = create_route_data('412', dataframe)
# route_411 = create_route_data('412', dataframe)
#
# # plot of the stop passenger from April 2019
# #plt.figure('Passenger Flow for UQ Lake Station [1882] during April 2019')
# plt.figure('Passenger Flow for Route [412] during April 1st 2019')
# # x_list = stop_UQ.index
# # y_list = stop_UQ['Passengers']
# x_list = route_411.index
# y_list = route_411['Passengers']
# # plt.scatter(x_list, y_list)
# ax = plt.gca()
# ax.plot(x_list, y_list, color='b', linewidth=1, alpha=0.6)
#
# ax.set_ylabel('Passenger Number')
# ax.set_xlabel('Time Interval : 15 minutes / Duration: April 1st to April 30th')
# #ax.set_xlabel('Time Interval : 15 minutes / Duration: April 1st 06:00am to 23:59pm')
# #ax.set_xlabel('Time Interval : 15 minutes / Duration: April 1st to April 7th')
# #ax.set_title('Passenger Flow for UQ Lake Station [1882] during April, 2019')
# #ax.set_title('Passenger Flow for UQ Lake Station [1882] during April, 2019')
# #ax.set_title('Passenger Flow for Boggo Road station [10795] during April 1st, 2019')
# #ax.set_title('Passenger Flow for Boggo Road station [10795] during April 1st to April 7th, 2019')
# #ax.set_title('Passenger Flow for Boggo Road station [10795] during April 1st to April 30th, 2019')
# #ax.set_title('Passenger Flow for Route [412] during April 1st to 7th, 2019')
# #ax.set_title('Passenger Flow for Route [412] during April 1st, 2019')
# ax.set_title('Passenger Flow for Route [412] during April, 2019')
#ax.set_title('Passenger Flow for Route [411] during April 1st to 7th, 2019')
#ax.set_title('Passenger Flow for Route [411] during April 1st, 2019')
#ax.set_title('Passenger Flow for Route [411] during April, 2019') |
94b7163ac01ac841b075d6aab9096c09cf776286 | ColtW27/Command_line_book_search | /get_book_data.py | 1,972 | 4 | 4 | def list_authors_in_string(authors): # adds "and" and makes the output a string
authors = " and ".join(authors)
return authors
def get_authors(volume): # returns the list of authors for the volume
if "authors" in volume["volumeInfo"]:
authors = list_authors_in_string(volume["volumeInfo"]["authors"])
return authors
else:
return "Unavailable"
def get_title(volume): # returns the title for the volume
if "title" in volume["volumeInfo"]:
return volume["volumeInfo"]["title"]
else:
return "Unavailable"
def get_publisher(volume): # returns the publisher for the volume
if "publisher" in volume["volumeInfo"]:
return volume["volumeInfo"]["publisher"]
else:
return "Unavailable"
# note for future optimazation, dry up code by combining these two functions, as they are all but identical except for the "- 1"
def get_list_number_for_book_replacement():
book_to_replace = ""
while book_to_replace not in range(1, 6):
try:
book_to_replace = int(input("""Which book would you like \
to replace? Please select a list number. \n"""))
except ValueError: # handles non number inputs
book_to_replace = ""
if book_to_replace not in range(1, 6): # specifies if the input is out of the list range
print("That response is not a number between 1 and 5. Please try again.")
return int(book_to_replace) - 1
def get_book_to_add_search_list_number():
book_to_add = ""
while book_to_add not in range(1, 6):
try:
book_to_add = int(input("""Which book would you like \
to add? Please select a list number. \n"""))
except ValueError:
book_to_add = ""
# specifies if the input is out of the list range
if book_to_add not in range(1, 6):
print("That response is not a number between 1 and 5. Please try again.")
return int(book_to_add)
|
f683209bf47adfb3b32690f64301d1fabfeaf07f | Zhoodarbeshim/CH2TASK17 | /task17.py | 1,332 | 3.78125 | 4 | greet = input()
google_office = [
'1 google_kazakstan'
'2 google_paris'
'3 google_uar'
'4 google_kyrgystan'
'5 google_san_francisco'
'6 google_germany'
'7 google_moscow'
'8 google_sweden'
]
if greet == 'Hello':
for x in google_office:
print(x)
choice_of_office = int(input('Enter a number: '))
complain = input('Write your complain: ')
if choice_of_office == 1:
with open ('google_kazakstan.txt', 'w') as f:
f.write(complain)
if choice_of_office == 2:
with open('google_paris.txt', 'w',) as f:
f.write(complain)
if choice_of_office == 3:
with open('google_uar.txt', 'w',) as f:
f.write(complain)
if choice_of_office == 4:
with open('google_kyrgyzstan.txt', 'w',) as f:
f.write(complain)
if choice_of_office == 5:
with open('google_san_francisco.txt', 'w',) as f:
f.write(complain)
if choice_of_office == 6:
with open('google_germany.txt', 'w',) as f:
f.write(complain)
if choice_of_office == 7:
with open('google_moscow.txt', 'w',) as f:
f.write(complain)
if choice_of_office == 8:
with open('google_sweden.txt', 'w',) as f:
f.write(complain)
else:
print('wrong') |
49e0d904854b85d800633292f0477680f98c571a | ARUNDHATHI1234/Python | /co1/program14.py | 120 | 3.984375 | 4 | n=int(input("enter a number:"))
s=str(n)
nn=s+s
nnn=s+s+s
temp=n+int(nn)+int(nnn)
print("the valueof n+nn+nnn is:",temp) |
37ec81bb8e7aee380a2c8a71b3cf7c597d952178 | AkashSDas/Mini-Projects | /sudoku.py | 3,329 | 3.5625 | 4 | import random
board = [
[0, 0, 0, 2, 6, 0, 7, 0, 1],
[6, 8, 0, 0, 7, 0, 0, 9, 0],
[1, 9, 0, 0, 0, 4, 5, 0, 0],
[8, 2, 0, 1, 0, 0, 0, 4, 0],
[0, 0, 4, 6, 0, 2, 9, 0, 0],
[0, 5, 0, 0, 0, 3, 0, 2, 8],
[0, 0, 9, 3, 0, 0, 0, 7, 4],
[0, 4, 0, 0, 5, 0, 0, 3, 6],
[7, 0, 3, 0, 1, 8, 0, 0, 0]
]
def solve(board):
find = find_empty(board)
if not find:
return True
else:
row, column = find
for i in range(1, 10):
if valid(board, i, (row, column)):
board[row][column] = i
if solve(board):
return True
# If our solution is incorrect then we reset the value back to 0
board[row][column] = 0
return False
def valid(board, entry, position):
row, column = position
# Check row
for i in range(len(board[0])):
if board[row][i] == entry and column != i:
return False
# Check column
for i in range(len(board)):
if board[i][column] == entry and row != i:
return False
# Check 3x3 box
box_x = column // 3
box_y = row // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x*3, box_x*3 + 3):
if board[i][j] == entry and (i, j) != (row, column):
return False
return True
def display_board(board):
for i in range(len(board)):
for j in range(0, len(board[i]), 3):
print(f"{board[i][j]} {board[i][j+1]} {board[i][j+2]}", end="")
if (j+3) % 3 == 0 and (j+3) != 9:
print(" | ", end="")
print(end="\n")
if (i+1) % 3 == 0 and i != 0 and (i+1) != 9:
print("- - - - - - - - - - -")
def find_empty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
display_board(board)
solve(board)
print()
display_board(board)
def generate_random_sudoku_board():
board = [[0 for _ in range(9)] for _ in range(9)]
solve(board)
random.shuffle(board)
return board
board = generate_random_sudoku_board()
print()
display_board(board)
def make_random_decision(difficulty_level):
if difficulty_level == 'Easy':
if random.random() <= 0.6:
return False
else:
return True
if difficulty_level == 'Medium':
if random.random() <= 0.4:
return False
else:
return True
if difficulty_level == 'Hard':
if random.random() <= 0.2:
return False
else:
return True
def set_value_to_0(board, difficulty_level):
for i in range(len(board)):
for j in range(len(board[0])):
if make_random_decision(difficulty_level):
board[i][j] = 0
return board
def generate_random_sudoku_board_to_play(difficulty_level):
board = generate_random_sudoku_board()
if difficulty_level == 'Easy':
board = set_value_to_0(board, difficulty_level)
if difficulty_level == 'Medium':
board = set_value_to_0(board, difficulty_level)
if difficulty_level == 'Hard':
board = set_value_to_0(board, difficulty_level)
return board
board = generate_random_sudoku_board_to_play('Medium')
print()
display_board(board)
|
7108b758f2544184a102ebc52caab00334bc57c7 | rahulwadhwa238/LoadTruckSelection | /LoadDeliverySelection.py | 2,081 | 3.796875 | 4 | import datetime
class LoadTruck:
TruckList = []
def __init__(self,num, r, s, e, l):
self.number = num
self.rate = r
self.start = s
self.end = e
self.left = l
self.status = True
LoadTruck.TruckList.append(self)
def set_days_left(self,days_left):
self.days_left = days_left
def cycle_left(LoadTruck):
for Truck in LoadTruck.TruckList:
if (Truck.start > current_date):
days_left = Truck.end-current_date
else:
days_left = 30 - (current_date - Truck.start)
Truck.set_days_left(days_left)
#print (Truck.number, ":", Truck.days_left)
def truck_selection(LoadTruck):
cycle_left(LoadTruck)
truck_selection = []
for Truck in LoadTruck.TruckList:
if (Truck.left >= current_task):
task_cost = Truck.rate*current_task
cost_breakdown = "\t{} INR/Km\t{} Km\t\t\t{} INR/Km\t{} Km".format(Truck.rate, Truck.left, 0, 0)
left = Truck.left - current_task
else:
task_cost = Truck.rate*Truck.left + ((Truck.rate*12)/10)*(current_task-Truck.left)
cost_breakdown = "\t{} INR/Km\t{} Km\t\t\t{} INR/Km\t{} Km".format(Truck.rate, Truck.left, ((Truck.rate*12)/10), (current_task-Truck.left))
left = 0
truck_selection.append(["Truck No.: ", Truck.number, "\n\nCost BreakDown:\n\tMinimum Rate\tMinimum Distance Left\tAfter Rate\tAfter Distance\n", cost_breakdown, "\nTotal Cost: ", task_cost, " INR\n\nDistance Left After Task: ", left, "\nCycle Day(s) Left: ", Truck.days_left])
truck_selection.sort(key = lambda x: (x[9], x[5], x[7]))
for selected_truck_details in truck_selection[0] :
print (selected_truck_details, end = "")
############### Object Defined #########################
l1 = LoadTruck(1,30,7,6,500)
l2 = LoadTruck(2,60,1,30,700)
current_date = datetime.datetime.now().day #CurrentDate
current_task = 800 #CurrentTask
################### Main Thread ###########################
print("Task Distance: ", current_task, "km")
print("Current Date:", datetime.datetime.now().date(), "\n")
truck_selection(LoadTruck)
print("\n") |
12bc8a9321d919ad44d6921105b77b1523d2bad8 | Sarastro72/Advent-of-Code | /2019/10/puzzle2.py | 1,476 | 3.828125 | 4 | #!/usr/local/bin/python
import math
filepath = 'input'
# Best position from puzzle 1
ox = 23
oy = 19
def getAngle(dx, dy):
a = math.atan2(dx, dy)
if (a < 0):
a = a + (2*math.pi)
return a * 360 / (2 * math.pi)
class Asteroid:
def __init__(self, x, y):
self.x = x
self.y = y
self.rx = x - ox
self.ry = oy - y
self.angle = int(getAngle(self.rx, self.ry) * 1000)
def __str__(self):
return f"Asteroid @({self.x},{self.y}) {self.sortable()}"
def sortable(self):
sdist = math.fabs(self.rx) + math.fabs(self.ry)
return "%06d:%03d" % (self.angle, sdist)
asteroids = []
with open(filepath) as fp:
line = fp.readline().strip()
y = 0
while line:
for x in range(len(line)):
if line[x] == "#":
a = Asteroid(x, y)
asteroids.append(a)
line = fp.readline().strip()
y += 1
asteroids.sort(key=lambda a: a.sortable())
asteroids.pop(0) # Remove center
lastAngle = -1
i = 0
destroyed = 0
while True:
target = asteroids[i]
if (target.angle != lastAngle):
destroyed += 1
print(f"#{destroyed} Boom, {target} is destroyed!")
asteroids.pop(i)
lastAngle = target.angle
else:
i += 1
if (i >= len(asteroids)):
print("Full revolution. Starting new lap:")
i = 0
lastAngle = -1
if (destroyed == 200 or len(asteroids) == 0):
break
|
7b32237309feacc9dcf0a584835927b3c6cac30f | thinkphp/seeds.py | /reverse2.py | 514 | 4 | 4 | '''
Reverse number
@thinkphp
MIT Style License
'''
import sys
#iterative version
def reverse(n):
s = 0
x = n
while x:
s = s*10 + x%10
x = int(x/10)
return s
#recursive solution
def reverse_rec(s,n):
if n == 0:
return s
else:
return reverse_rec(s*10+n%10,int(n/10))
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Usage: python reverse2.py 12345678"
sys.exit()
n = int(sys.argv[1])
print reverse_rec(0,n)
|
76d53da1184e990fca80449193c0f5e73b89c690 | kiranani/playground | /Python3/0617_Merge_2_BTs.py | 700 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
def recurse(r1, r2):
if r1 is not None and r2 is not None:
r1.val += r2.val
r1.left = recurse(r1.left, r2.left)
r1.right = recurse(r1.right, r2.right)
return r1
elif r1 is None:
return r2
else:
return r1
return recurse(t1, t2)
|
e0404972a67ea770543455110994fdcbbd8da62c | mtharanya/python-programming- | /minimum.py | 401 | 3.90625 | 4 | while True:
inp = raw_input('Enter a number: ')
if inp == 'done' :
break
try:
num = float(inp)
except:
print 'Invalid input'
continue
numbers = list(num)
minimum = None
for num in numbers :
if minimum == None or num < minimum :
minimum = num
print 'Minimum:', minimum
|
1da03c2af2ca069a957c6537d737cd8d02d5e504 | SensehacK/playgrounds | /python/PF/Extra/Assignment45.py | 563 | 3.703125 | 4 | #PF-Tryout
def find_armstrong(number):
original_number = number # save original number here
temp=0
while(number!=0):
remainder=number%10
number=number//10 # perform integer division
temp+=(remainder*remainder*remainder)
if(original_number==temp): # compare with the original number
return True # because num has been modified
return False
number=371
if(find_armstrong(number)):
print(number,"is an Armstrong number")
else:
print(number,"is not an Armstrong number") |
24fdd6a818c04cdfe0628caca1209d7bf5fda017 | hasnain-khan1/downloader_video | /create_video_list.py | 5,363 | 3.5 | 4 | import tkinter as tk
import tkinter.scrolledtext as tkst
import video_library as lib
import font_manager as fonts
def set_text(text_area, content):
text_area.delete("1.0", tk.END)
text_area.insert(1.0, content)
def set_playlist_text(text_area, content):
text_area.delete("1.0", tk.END)
for x in content:
text_area.insert(tk.END, x + '\n')
"""
This function reset the both input video and play text boxes
"""
def reset_playlist(text_area):
text_area.delete("1.0", tk.END)
video_playlist.clear()
play_count.clear()
"""
This function shows the total play counts of videos added to input video text
"""
def play_playlist(text_area,content):
text_area.delete("1.0", tk.END)
for x in content:
text_area.insert(tk.END, str(x) + '\n')
class CreateVideoList():
def __init__(self, root):
if root == None:
window = tk.Tk()
fonts.configure()
else:
window = tk.Toplevel(root)
window.geometry("750x600")
window.title("Create Video List")
#list_videos_btn = tk.Button(window, text="List All Videos", command=self.list_videos_clicked)
#list_videos_btn.grid(row=0, column=0, padx=10, pady=10)
"""
enter_lbl = tk.Label(window, text="Enter Video Number")
enter_lbl.grid(row=0, column=1, padx=10, pady=10)
self.input_txt = tk.Entry(window, width=3)
self.input_txt.grid(row=0, column=2, padx=10, pady=10)
check_video_btn = tk.Button(window, text="Check Video", command=self.check_video_clicked)
check_video_btn.grid(row=0, column=3, padx=10, pady=10)
"""
enter_video_lbl = tk.Label(window, text="Enter Video Number to add in playlist")
enter_video_lbl.grid(row=1, column=1, padx=10, pady=10)
self.input_video_txt = tk.Entry(window, width=3)
self.input_video_txt.grid(row=1, column=2, padx=10, pady=10)
check_video_btn = tk.Button(window, text="Add Video", command=self.enter_video_clicked)
check_video_btn.grid(row=1, column=3, padx=10, pady=10)
self.list_txt = tkst.ScrolledText(window, width=48, height=12, wrap="none")
self.list_txt.grid(row=3, column=0, columnspan=3, sticky="W", padx=10, pady=10)
self.video_txt = tk.Text(window, width=24, height=8, wrap="none")
self.video_txt.grid(row=3, column=3, sticky="NW", padx=10, pady=10)
reset_btn = tk.Button(window, text="Reset", command=self.reset_button_clicked)
reset_btn.place(x=550,y=230)
self.play_count_txt = tk.Text(window, width=24, height=8, wrap="none")
self.play_count_txt.grid(row=4, column=3, sticky="NW", padx=10, pady=10)
play_btn = tk.Button(window, text="Play", command=self.play_button_clicked)
play_btn.place(x=550,y=470)
self.status_lbl = tk.Label(window, text="", font=("Helvetica", 10))
self.status_lbl.grid(row=4, column=0, columnspan=4, sticky="W", padx=10, pady=10)
self.list_videos_clicked()
if root == None:
window.mainloop()
def check_video_clicked(self):
key = self.input_txt.get()
name = lib.get_name(key)
if name is not None:
director = lib.get_director(key)
rating = lib.get_rating(key)
play_count = lib.get_play_count(key)
video_details = f"{name}\n{director}\nrating: {rating}\nplays: {play_count}"
set_text(self.video_txt, video_details)
else:
set_text(self.video_txt, f"Video {key} not found")
self.status_lbl.configure(text="Check Video button was clicked!")
def list_videos_clicked(self):
video_list = lib.list_all()
set_text(self.list_txt, video_list)
self.status_lbl.configure(text="List Videos button was clicked!")
def enter_video_clicked(self):
try:
key = (self.input_video_txt.get())
name = lib.get_name(key)
if key=="" or name is None:
self.list_videos_clicked()
set_text(self.video_txt, f"Video {key} not found")
else:
playlist=lib.get_name(key)
video_playlist.append(playlist)
play_count.append(key)
set_playlist_text(self.video_txt,video_playlist)
except ValueError:
pass
self.status_lbl.configure(text="Add Video button was clicked!")
"""
These functions call the above reset_playlist and play_playlist functions on button click
"""
def reset_button_clicked(self):
reset_playlist(self.video_txt)
reset_playlist(self.play_count_txt)
self.status_lbl.configure(text="Reset button was clicked!")
def play_button_clicked(self):
l=[]
for i in play_count:
a=lib.increment_play_count(i)
b=lib.get_play_count(i)
name = lib.get_name(i)
video_details = f"{name}\nPlays: {b}"
l.append(video_details)
play_playlist(self.play_count_txt,l)
print(l)
self.status_lbl.configure(text="Play button was clicked!")
play_count=[]
video_playlist=[]
if __name__ == "__main__":
CreateVideoList(None)
|
ebdfa1b6cac1619088ba779f2bd5907d0a3d78fd | Sahithipalla/pythonscripts | /csvfile.py | 718 | 3.53125 | 4 | pwd
import csv
data=open("test.csv")
data
csv_data=csv.reader(data)
csv_data
data_lines=list(csv_data)
data_lines
#create or overwrite a csv.file
file_output=open("new_file.csv","w",newline="")
csv_writer=csv.writer(file_output,delimiter=",")
csv_writer.writerow(["col1","col2","col3"])
csv_writer.writerows([[1,2,3],[4,5,6],[7,8,9]])
file_out.close()
data=open("new_file.csv")
data
csv_data=csv.reader(data)
data_lines=list(csv_data)
data_lines
#edit the file
f=open("new_file.csv","a",newline="")
csv_writer=csv.writer(f)
csv_writer.writerow([12,34,56])
csv_writer.writerows([[10,20,30],[40,50,60],[70,80,90]])
f.close()
data=open("new_file.csv")
data
csv_data=csv.reader(data)
data_lines=list(csv_data)
data_lines
|
f1068ab1a5ca9d430adfac63347025244b504264 | yamauchih/shitohichi-tools | /graphfetcher/vectorextractor/test_call_argument.py | 737 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2013 Yamauchi, Hitoshi
# For Rebecca from Hitoshi the fool
#
# function argument behavior test.
#
def func(alist):
listlen = len(alist)
if (listlen < 3):
raise StandardError('list length is too short.')
# alist is passed by a kind of reference
# The ocntents can be changed.
alist[0] = 8
# this makes alist copy (alist[:] is total copy)
alist = alist[2:listlen-1]
print 'in func 1: ', str(alist)
# copied object is changed, but this change can not be seen from the main.
alist[0] = 100
print 'in func 2: ', str(alist)
if __name__=="__main__":
alist = [1,2,3,4,5,6]
func(alist)
print 'in main: ', str(alist)
|
974ae7a08eb01f22492c35d527043d3ebcccf851 | sevenhe716/LeetCode | /Mock/m4131_microsoft.py | 2,269 | 3.78125 | 4 | # Time: O(n)
# Space: O(1)
# Ideas:
# mark
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from common import TreeNode
class Solution:
def trimBST(self, root: 'TreeNode', L: int, R: int) -> 'TreeNode':
if not root:
return
if root.val < L:
return self.trimBST(root.right, L, R)
elif root.val > R:
return self.trimBST(root.left, L, R)
else:
root.left = self.trimBST(root.left, L, R)
root.right = self.trimBST(root.right, L, R)
return root
def trimBST1(self, root: 'TreeNode', L: int, R: int) -> 'TreeNode':
dummy = TreeNode(float('inf'))
dummy.left = root
print(root)
# default: cur is valid
def dfs(cur):
if not cur:
return
while cur.right and cur.right.val > R:
cur.right = cur.right.left
while cur.right and cur.right.val < L:
cur.right = cur.right.right
while cur.left and cur.left.val > R:
cur.left = cur.left.left
while cur.left and cur.left.val < L:
cur.left = cur.left.right
dfs(cur.left)
dfs(cur.right)
dfs(dummy)
return dummy.left
# def trimBST(self, root: 'TreeNode', L: int, R: int) -> 'TreeNode':
# # for R, if R is left child records all left parents, remove right child of all
# cur = root
# parents = []
# while cur:
# if cur.val == R:
# parents.append(cur)
# break
# elif cur.val < R:
# parents.clear()
# cur = cur.right
# else:
# parents.append(cur)
# cur = cur.left
#
# for p in parents:
# p.right = None
#
# # for L, find the node who left than L, replace by its left node,
# # and right node add to left node's right most, if no left node, replace by right node
# def dfs():
#
#
# cur = root
# while cur:
# if cur.val < L:
|
ca3c063234cc3ef126caf33bef40352ab751fdba | LuisHenrique01/Questoes_URI | /uri2369.py | 174 | 3.640625 | 4 | qtd = int(input())
valor = 7
for i in range(11, qtd+1):
if i < 31:
valor += 1
elif i < 101:
valor += 2
else:
valor += 5
print("%d"%valor) |
a4e31579248138c45117541dba680987262836ce | LEO147/list | /3list/range.py | 678 | 3.796875 | 4 | nums = list(range(5,0,-1))
print(nums)
nums[2] = 100
print(nums)
#range是一個類別(class),藍圖,給參數就做出這個類別的物件。沒有定義中括號,所以拿不到東西。
#List也是一種類別,把range放在nums裡面,就是建立一個新List把Range的質放在心的list,就是nums裡面。
a=[1,2,3,4,5]
total = 0
for el in a:
total+=el
total2=sum(a)
print(total,total2)
b = range(5,0,-1)
print(sum(b))
strA = 'Stone'
strA = list(strA) #沒有轉換成list無法做改變。
strA[0] = 'Y'
print(strA) #印出來是['Y', 't', 'o', 'n', 'e']
strA = ''.join(strA) #再將strA轉換成字串str
print(strA) #印出來是Ytone |
3d2beee7278c4df1610a275b2bf4ce1a1f69ff99 | Aptoppole/LaTech-CSC-132-Final-Project-Tutoial-keyboard | /piano_lesson.py | 1,343 | 3.828125 | 4 | ######################################################################################
# This file is for creating the lesson GUI. These be the libraries we used.
from Tkinter import *
######################################################################################
#the main part of the program
class Lesson(Frame):
def __init__(self, master, activity, instructions):
Frame.__init__(self, master)
self.activity = activiity
self.instrucitons = instructions
def setUpGUI(self):
#this function will display an activity and verify that it is done correctly
#Alex and Jonah, I thought this function simplified our original design--Eddie
self.instructions.grid(row=0, column=0, sticky=N+E+W)
self.activity.grid(row=1, column=0, sticky=E+W+S)
######################################################################################
#main part of the gui program
#So, here's the problem. We need the sheet music and the keys to play on the keyboard.
#Once we get that, I can build the GUI to match our specifications. --Eddie
length=800
width=800
A = Key("A", )
B = Key("B", )
C = Key("C", )
D = Key("D", )
E = Key("E", )
F = Key("F", )
G = Key("G", )
A2 = Key("A2", )
window = Tk()
window.title("Piano Teacher--Final Project for CSC 132")
window.geometry("{}X{}".format(length, width))
window.mainloop()
|
be49f994e8fafa0da3f36e686c3cef0e00f005f9 | mikalaikarol/Hangman-Python-Project | /Hangman/task/hangman/hangman.py | 3,564 | 3.96875 | 4 | import random
print("H A N G M A N")
new_word_list = ["java", "kotlin", "python", "javascript"]
new_word = random.choice(new_word_list)
hidden_word = ("-" * len(new_word))
number_of_tries = 8
used_letters = []
decision = input('Type "play" to play the game, "exit" to quit: ')
result = "".join(hidden_word)
while decision == "play":
if result == new_word:
break
print()
while number_of_tries != 0:
print(result)
user_input = input('Input a letter: ')
number_of_tries -= 1
for letter in user_input:
if len(user_input) > 1:
print("You should input a single letter")
number_of_tries += 1
if number_of_tries < 1:
pass
else:
print()
break
else:
if user_input.islower() is False:
print("It is not an ASCII lowercase letter")
number_of_tries += 1
if number_of_tries < 1:
pass
else:
print()
break
if user_input in used_letters:
print("You already typed this letter")
number_of_tries += 1
if number_of_tries < 1:
pass
else:
print()
break
else:
if letter not in new_word:
print("No such letter in the word")
used_letters.append(letter)
if number_of_tries < 1:
pass
else:
print()
if letter in result:
print("You already typed this letter")
number_of_tries += 1
if number_of_tries < 1:
pass
else:
print()
else:
if letter in new_word:
hidden_word = list(hidden_word)
index = new_word.find(letter)
hidden_word[index] = letter
number_of_tries += 1
count_letter = new_word.count(letter)
n = 1 # n represents the number of i to be found
while count_letter > 1:
n += 1
x = new_word.find(letter, n)
hidden_word[x] = letter
count_letter -= 1
result = "".join(hidden_word)
if number_of_tries > 0 and result == new_word:
print()
break
elif number_of_tries == 0 and result != new_word:
pass
else:
print()
if result == new_word:
print(result)
print("You guessed the word " + result + "!")
print("You survived!")
print()
break
elif result != new_word and number_of_tries == 0:
print("You lost!")
print()
break
if decision == 'exit':
break
else:
break
|
392d857f71be44f3ab5a6a8ddba445ddc1c494d7 | christopher-burke/warmups | /python/misc/missing_third_angle.py | 1,204 | 4.8125 | 5 | #!/usr/bin/env python3
"""Missing Third Angle.
You are given 2 out of 3 of the angles in a triangle, in degrees.
Write a function that classifies the missing angle as either "acute", "right",
or "obtuse" based on its degrees.
Source:
https://edabit.com/challenge/PKPmS5zwefc7M5emK
"""
def calc_missing_angle(a: int, b: int) -> int:
"""Return the missing angle of a triangle in degrees."""
return 180 - (a + b)
def angle_classifier(a: int) -> str:
"""Classify the angle.
An acute angle is one smaller than 90 degrees.
A right angle is one that is exactly 90 degrees.
An obtuse angle is one greater than 90 degrees
(but smaller than 180 degrees).
"""
if a > 90 and a < 180:
return "obtuse"
elif a < 90 and a > 0:
return "acute"
return "right"
def missing_angle(a: int, b: int) -> str:
"""Determine the class of the missing angle."""
missing_angle = calc_missing_angle(a, b)
result = angle_classifier(missing_angle)
return result
def main():
"""Run missing angle."""
print(missing_angle(27, 59))
print(missing_angle(135, 11))
print(missing_angle(45, 45))
if __name__ == "__main__":
main()
|
5fbbf55aaaf64ca3756f1621679d3985a625ac53 | sebarias/python_classes_desafioltm | /ejercicios_ciclos/desafio_ciclos_metodos/generar_patron.py | 140 | 3.875 | 4 | numero_usuario = int(input("Ingrese un numero: "))
cadena = ""
for i in range(numero_usuario):
cadena += str(i + 1)
print(cadena)
|
5e060740996a12a8fda890d7381d5d3c1ee05562 | dblueblood/ROLL-THE-DICE | /Dictionary Extract.py | 3,125 | 3.6875 | 4 | """
Author: Ayo Asekun
Date Created: Oct 18th, 2019
Last Date Modified: Oct 19th, 2019
Program Description: Extracting & Analyzing a python dictionary
PsuedoCode:
<START PROGRAM>
INPUTS: Using provided files; Extract source files & save data to reachable directory
"path" = file path of data on OS HD
Variables:
path = location of file in directory
MC = Python readable format
ext = print out of file
PROCESS: 3 Main actions performed in Analysis
POINT 1: Using os import to access files, print file to view for easy access
POINT 2: 'if' & 'else' loops:
+ Determine length of file
- lines & Characters
+ Determine if lowercase 'a' in file
+ Determine if uppercase 'A' in file
+ Determine if uppercase 'a' not in file
POINT 3: Determine the file name
OUTPUTS: (1) Full readable file in Python terminal
(2) Count of lines/Newlines in File
(3) Count of total noo. of characters in file
(4) Result of request if 'a' in File
(5) Result of request if 'A' in File
(6) Result of request if 'a' not in File
(7) Directory/Host Name of File
<END PROGRAM>: End of Pay-roll
"""
import os
# Import Library
path = "C:\\Users\\ayoas_spsqm2u\\PycharmProjects\\morsecode.py"
MC = open(path, "r")
ext = MC.read()
print("=========== FILE IMPORT TO BE ANALYZED ===========")
print(ext)
print("===================================================")
# To print the number of lines in imported file
MC = open(path, "r")
print("No. of lines in File")
print(len(MC.readlines()))
print("===================================================")
# To print total no. of elements in in imported file
print("No. of characters in File")
MC = open(path, "r")
print(len(MC.read()))
print("===================================================")
# To confirm if lowercase 'a' is in imported file
MC = open(path, "r")
print("If lowercase 'a' in file, it will print")
x = "a"
if x in MC.read():
print("Value "+x+" is present")
else:
print("No Value")
print("===================================================")
# To confirm if uppercase 'A' is in imported file
MC = open(path, "r")
print("If capital letter 'A' in file, show below")
x = "A"
if x in MC.read():
print(x)
else:
print("*Value Unavailable*")
print("===================================================")
# To confirm if lowercase 'a'( or any value required) is not in imported file
MC = open(path, "r")
x = "a"
print("Is '" + x + "' in the file; True/False")
if x not in MC.read():
x = False
print(x)
else:
x = True
print(x)
print("===================================================")
# Pulling the name of above file from the directory
MC = open(path, "r")
path2 = os.path.basename("C:\\Users\\ayoas_spsqm2u\\PycharmProjects\\morsecode.py")
print("Name of file being worked on: " + path2.upper())
MC.close()
|
826d1cd20816cb12bd7a5d90fd317714aaf978a4 | IoanaMelinte/Beginner-Projects | /Computer_guessing.py | 557 | 4.25 | 4 | # the computer will guess the number that we provide
import random
inf= int(input("Minimum value of the number to guess: "))
sup= int(input("Maximum value of the number to guess: "))
feedback= ""
while feedback != "c":
guess = random.randint(inf,sup) #this variable will return the guesses of the computer
feedback = input(f'The number {guess} is too high(h), too low(l) or correct(c): ').lower()
if feedback == "h":
sup = guess - 1
elif feedback == "l":
inf = guess+1
print (f"This is the correct number: {guess}.")
|
528c3ddebccee21a1f09a6ee0f49bc23ee9e9fd3 | lamvdoan/challenge | /learning/encapsulation/customer.py | 1,607 | 3.859375 | 4 | class Customer(object):
customer_id = None
name = None
age = None
gender = None
nickname = None
username = None
password = None
def __init__(self, customer_id):
self.customer_id = customer_id
def set_username(self, customer_id, username):
"""
Update username for customer
:param customer_id: customer_id
:param username: desired username
:return: None
"""
self.username = username
print "Updated customer_id {customer_id}: username = {username}".format(customer_id=customer_id,
username=self.username)
print
def set_password(self, password):
"""
Update password for customer
:param password: desired password
:return: None
"""
self.password = password
print "Updated customer_id {customer_id}: password = ********".format(customer_id=self.customer_id)
print
def set_nickname(self):
"""
Set the nickname as the concatenation of name and age
:return: None
"""
# TODO (4): Based on bad coding, this may produce a TypeError. Implement a logic to handle this exception
self.nickname = self.name + self.age
print "Updated customer_id {customer_id}: nickname = {nickname}".format(customer_id=self.customer_id,
nickname=self.nickname)
print
# TODO (1): Implement getters and setters
|
c72f53ddae11dca755891b2a8b75c9f7d20b6d07 | mmdaz/python_course | /codes-2021/prime.py | 238 | 4.0625 | 4 | def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
n = int(input("Enter Your Number: "))
for i in range(2, n + 1):
if is_prime(i):
print("Prime Number: {}".format(i))
|
d421fc1f784f84f364cd124f235218708ed9a242 | joestalker1/leetcode | /src/main/scala/PowerSetWithoutDuplicates.py | 452 | 3.5 | 4 | def powerset_without_dup(nums):
def get_power_set(start, res, buf):
if buf:
res.append(buf[::])
for i in range(start, len(nums)):
if i > start and nums[i-1] == nums[i]:
continue
buf.append(nums[i])
get_power_set(i+1, res, buf)
buf.pop()
res = []
nums.sort()
get_power_set(0, res, [])
return res
print(powerset_without_dup([1,1,2,3,2,4])) |
45f71d944e5255dc199826addd031a87505e87f9 | coucoulesr/leetcode | /033-search-in-rotated-array/033-search-in-rotated-array.py | 2,468 | 3.78125 | 4 | class Solution:
def search(self, nums, target):
def binarySearch(nums, target, left_bound = 0):
if not nums or (len(nums) == 1 and nums[0] != target):
return -1
if len(nums) == 2:
if nums[0] == target:
return left_bound
elif nums[1] == target:
return left_bound + 1
else:
return -1
halfway = len(nums) // 2
halfway_val = nums[halfway]
if halfway_val == target:
return halfway + left_bound
else:
target_bigger = True if target > halfway_val else False
right_bigger = True if nums[halfway + 1] > halfway_val else False
if right_bigger:
if target_bigger:
return binarySearch(nums[halfway + 1:len(nums)], target, left_bound + halfway + 1)
else:
return binarySearch(nums[0:halfway], target, left_bound)
else:
if target_bigger:
return binarySearch(nums[0:halfway], target, left_bound)
else:
return binarySearch(nums[halfway + 1:len(nums)], target, left_bound + halfway + 1)
def rotatedSearch(nums, target, left_bound = 0):
if not nums or (len(nums) == 1 and nums[0] != target):
return -1
left, right, middle = nums[0], nums[len(nums) - 1], nums[len(nums) // 2]
if target == middle:
return left_bound + len(nums) // 2
if target == left:
return left_bound
if target == right:
return left_bound + len(nums) - 1
if middle > left:
if target > left and target < middle:
return binarySearch(nums[0:len(nums) // 2], target, left_bound)
else:
return rotatedSearch(nums[(len(nums) // 2) + 1:len(nums)], target, left_bound + (len(nums) // 2) + 1)
else:
if target > middle and target < right:
return binarySearch(nums[(len(nums) // 2) + 1:len(nums)], target, left_bound + (len(nums) // 2) + 1)
else:
return rotatedSearch(nums[0:len(nums) // 2], target, left_bound)
return rotatedSearch(nums, target) |
1a45e5e364e80034670e5e9f6733b4316bfc871a | jdleo/Leetcode-Solutions | /solutions/1379/main.py | 942 | 3.578125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not original: return None
# stack for dfs
stack = [(original, cloned)]
# until stack is empty
while stack:
# pop cur
curOriginal, curCloned = stack.pop()
# check if this is target
if curOriginal == target:
# return same node in cloned tree
return curCloned
# add left and right subtrees (if non null)
if curOriginal.left: stack.append((curOriginal.left, curCloned.left))
if curOriginal.right: stack.append((curOriginal.right, curCloned.right))
# never found one
return None |
3bb6fe5414a507449862b6dbd51e2d48e2c1d8ec | xuan-linker/linker-python-study | /demo/TryExcept.py | 769 | 4 | 4 | while True:
try:
x = int(input("please input a number:"))
break
except ValueError:
print("your input not number , please try again")
import sys
try:
# raise Exception("error exception")
f = open('myfile,txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("cloud not convert data to a integer")
except:
print("Unexpected error", sys.exc_info()[0])
raise
else:
print("1")
finally:
print('2')
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2 * 2)
except MyError as e:
print("MyError value:", e.value)
|
77d46997ccafc64e8fab2b239b6bddc67f275d14 | Omega094/lc_practice | /reverse_nodes_in_k_group/ReverNodesInKGroup.py | 1,484 | 3.578125 | 4 | import sys
sys.path.append("/Users/jinzhao/leetcode/")
from leetcode.common import *
class Solution(object):
#this helper returns reversed linked list with start and end node.
'''
def reverseHelper(self, startNode, endNode):
if not startNode.next or not startNode:
return (startNode, startNode)
tempStart, tempEnd = self.reverseHelper(startNode.next, endNode)
startNode.next = None
tempEnd.next = startNode
return (tempStart, startNode)
'''
def reverse(self, start, end):
newhead=None; newhead.next=start
while newhead.next!=end:
tmp=start.next
start.next=tmp.next
tmp.next=newhead.next
newhead.next=tmp
return [end, start]
def reverseKGroup(self, head, k):
if head==None: return None
nhead=ListNode(0); nhead.next=head; start=nhead
while start.next:
end=start
for i in range(k-1):
end=end.next
if end.next==None: return nhead.next
res=self.reverse(start.next, end.next)
start.next=res[0]
start=res[1]
return nhead.next
#test
if __name__ == "__main__":
l1 = construct_node_from_list([1,2,3,4,5])
sol = Solution()
print sol.reverseKGroup(l1, 2)
# end = l1;
# while end.next :
# end = end.next
# start , end = sol.reverseHelper(l1, end)
# print start
# print end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.