text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# coding: utf-8
# # KNN on Customer Dataset
#
#
# <h1>Table of contents</h1>
#
# <div class="alert alert-block alert-info" style="margin-top: 20px">
# <ol>
# <li><a href="#1">KNN Theory</a></li>
# <li><a href="#2">KNN Algorithm</a></li>
# <li><a href="#3">Calculating the distance</a></li>
# <li><a href="#4">Dataset</a></li>
# <li><a href="#5">Label-encoding using Scikit learn library</a></li>
# <li><a href="#6">Data Visualization and Analysis</a></li>
# <li><a href="#7">Train Test Split</a></li>
# <li><a href="#8">Claasification</a></li>
# <li><a href="#12">What about other K</a></li>
# <li><a href="#13">Plot model accuracy for different number of neighbors</a></li>
# </ol>
# </div>
# <br>
# <hr>
#
# <div id="1">
# <h2>KNN Theory</h2>
# </div>
#
# K-Nearest Neighbors is an algorithm for supervised learning. Where the data is trained with data points corresponding to their classification. Once a point is to be predicted, it takes account the K nearest points to it to determines it's classification
#
#
# <div id="2">
# <h2>KNN Algorithm</h2>
# </div>
#
# 1. Pick a value of K
#
# 2. Calculate the distance of unknown case from all the cases(Euclidian, Manhattan, Minkowski or Weighted)
#
# 3. Select the K-observations in the training data that are nearest to the unknown data point
#
# 4. Predict the response of the unknown data point using the most popular response value from the K-Nearest Neighbors
#
# ### Here's an visualization of the K-Nearest Neighbors algorithm.
#
#
# <img src="https://d1jnx9ba8s6j9r.cloudfront.net/blog/wp-content/uploads/2019/03/How-does-KNN-Algorithm-work-KNN-Algorithm-In-R-Edureka-528x250.png">
#
#
# Here we have two data points of Class A and B. We want to predtict what the red circle (test data point) is. If we consider a k value of 3. We will obtain a predtiction of Class A. Yet if we consider a k value of 6, we will obtain a prediction of Class B.
#
# Looking at from this perspective we can say that it is important to consider the value of K. In this diagram it considers the K Nearest Neighbors when it predicts the classification of the test point (Red Circle).
# <div id="3">
# <h2>Calculating the distance</h2>
# </div>
#
# To calculate the distance between two points with one point being the unknown case and the other being the data you have in your dataset. To calculate there are several ways, we are gonna use euclidean distance.
#
# ### Euclidean distance formule
#
# <img src="https://i.stack.imgur.com/RtnTY.jpg">
#
# let's consider you have 6 columns and 5 rows. The last column is the prediction columns have different Class labels.
#
# Step 1.
#
# **Subtraction**
#
# Subtract each attribute(column) from row 1 with the attribute from row 2.
#
# Example = (2-3) = -1
#
# Step 2.
#
# **Exponention**
#
# After the subtracting column 1 from row 1, with column 1 from row 2, we will get squared root.
#
# **Important**
# Results are always positive
#
# Example = (2-3)** 2 = (-1)** 2 = 1
#
# Step 3.
#
# **Sum**
#
# Once you are done performing step 1 and 2 on all the attribute(column) from row 1 with the attribute from row 2. Sum all the results.
#
# Example = (2-3)** 2 + (2-3)** 2 + (4-5)** 2 + (5-6)** 2 + (2-3)** 2 = 5
#
#
# Step 4.
#
# **Square root**
#
# After step 3, we will square root the result and that the euclidean distance from line 1 to line 2.
#
# Perform the same steps with respect to other lines and you will have the euclidean distance from line 1 to all other lines. Once that is done. We will check which is the class that most appears. The class which appears more time will be the class that we will use to classify the unknown case.
# ### Import Libraries
# In[102]:
import numpy as np
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
import seaborn as sns
get_ipython().run_line_magic('matplotlib', 'inline')
# <div id="4">
# <h2>Dataset</h2>
# </div>
#
#
# Imagine a telecommunications provider has segmented its customer base by service usage patterns, categorizing the customers into four groups. If demographic data can be used to predict group membership, the company can customize offers for individual prospective customers. It is a classification problem. That is, given the dataset, with predefined labels, we need to build a model to be used to predict class of a new or unknown case.
#
# The example focuses on using demographic data, such as region, age, and marital, to predict usage patterns.
#
# The target field, called **custcat**, has four possible values that correspond to the four customer groups, as follows:
# 1- Basic Service
# 2- E-Service
# 3- Plus Service
# 4- Total Service
#
# Our objective is to build a classifier, to predict the class of unknown cases. We will use a specific type of classification called K nearest neighbour.
#
# You can find this dataset in IBM SPSS.
#
# ### Load the dataset
# In[14]:
df = pd.read_excel("telco2.xlsx")
df.head()
# In[113]:
#making a copy of the dataset
df1 = df.copy()
# ### Data Exploration
# In[114]:
df1.shape
# In[115]:
#Checking for any missing values
df1.isna().sum()
# We can see that the column logtoll, logequi, logcard and logwire are having missing values. As we are not gonna be using these columns for over analysis we will drop them.
# In[116]:
df1 = df1.drop(["loglong","logtoll","logequi","logcard","logwire"],axis =1)
df1.head()
# In[117]:
df1.isna().values.sum()
# There are no missing values
# In[118]:
df1.info()
# In[119]:
df1.describe(include="all")
# In[120]:
df1.fillna(0)
# In[121]:
df1.isna().values.sum()
# For our analysis we will take the columns tenure, age, marital, address, income, ed, employ, retire, gender, reside and custcat
# In[122]:
df1 = df1.drop(["tollfree","equip","callcard","wireless","longmon","tollmon","equipmon","cardmon","wiremon","longten","tollten","equipten","cardten","wireten","multline","voice","pager","internet","callid","callwait","forward","confer","ebill","lninc","churn"],axis=1)
# In[123]:
df1.head()
# <div id="5">
# <h2>Label-encoding using Scikit learn library </h2>
# </div>
# In[124]:
#Import label encoder
from sklearn import preprocessing
#laabel_encoder object knows how to understand word labels
label_encoder = preprocessing.LabelEncoder()
#Encode labels in column region, marital, ed, retire, gender, custcat
df1['region'] = label_encoder.fit_transform(df1['region'])
df1['marital'] = label_encoder.fit_transform(df1['marital'])
df1['ed'] = label_encoder.fit_transform(df1['ed'])
df1['retire'] = label_encoder.fit_transform(df1['retire'])
df1['gender'] = label_encoder.fit_transform(df1['gender'])
df1['custcat'] = label_encoder.fit_transform(df1['custcat'])
# In[125]:
df1.head()
# Now that we have the proper data. We can do Data visualization and Analysis on it.
# <div id="6">
# <h2>Data Visualization and Analysis</h2>
# </div>
# Let's see how many of each class is in our dataset
# In[126]:
df1["custcat"].value_counts()
# 0. **Basic-service = 266**
#
# 1. **E-Service Customer = 217**
#
# 2. **Plus Service = 281**
#
# 3. **Total Service = 236**
# In[127]:
df1.hist(column ='income',bins=50)
# In[128]:
ax = sns.countplot(y=df1['custcat'], data=df1)
plt.title('Distribution of custcat')
plt.xlabel('Number of Axles')
total = len(df1['custcat'])
for p in ax.patches:
percentage = '{:.1f}%'.format(100 * p.get_width()/total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height()/2
ax.annotate(percentage, (x, y))
plt.show()
# 0. **Basic-service = 266**
#
# 1. **E-Service Customer = 217**
#
# 2. **Plus Service = 281**
#
# 3. **Total Service = 236**
# We can see from the countplot the Plus Service is been used more then other services.
# ## Feature set
# In[129]:
df1.columns
# In[130]:
X = df1[['region', 'tenure','age', 'marital', 'address', 'income', 'ed', 'employ','retire', 'gender', 'reside']] .values #.astype(float)
X[0:5]
# In[133]:
y = df['custcat'].values
y[0:5]
# ## Normalize Data
#
# Data Standardization give data zero mean and unit variance, it is good practice, especially for algorithms such as KNN which is based on distance of cases:
# In[135]:
X = preprocessing.StandardScaler().fit(X).transform(X.astype(float))
X[0:5]
# <div id = "7">
# <h2>Train Test Split</h2>
# </div>
#
# Out of Sample Accuracy is the percentage of correct predictions that the model makes on data that that the model has NOT been trained on. Doing a train and test on the same dataset will most likely have low out-of-sample accuracy, due to the likelihood of being over-fit.
#
# It is important that our models have a high, out-of-sample accuracy, because the purpose of any model, of course, is to make correct predictions on unknown data. So how can we improve out-of-sample accuracy? One way is to use an evaluation approach called Train/Test Split.
# Train/Test Split involves splitting the dataset into training and testing sets respectively, which are mutually exclusive. After which, you train with the training set and test with the testing set.
#
# This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset is not part of the dataset that have been used to train the data. It is more realistic for real world problems.
# In[136]:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state =4)
print("Train set:", X_train.shape, y_train.shape)
print("Test set:", X_test.shape, y_test.shape)
# <div id="8">
# <h2> Claasification </h2>
# </div>
#
# K-Nearest neighbor (KNN)
# In[137]:
#import library
from sklearn.neighbors import KNeighborsClassifier
# <div id="9">
# <h2>Training </h2>
# </div>
# In[175]:
#Let's start the algorithm with k = 5 and keep on updating to see which one is close
k = 9
#Train model and Predict
neigh = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)
neigh
# <div id="10">
# <h2> Predicting</h2>
# </div>
# In[164]:
yhat = neigh.predict(X_test)
yhat[0:5]
# <div id="11">
# <h2> Accuracy evaluation </h2>
# </div>
#
# In multilabel classification, **accuracy classification score** is a function that computes subset accuracy. This function is equal to the jaccard_score function. Essentially, it calculates how closely the actual labels and predicted labels are matched in the test set.
# In[174]:
from sklearn import metrics
print("Train set Accuracy: ", metrics.accuracy_score(y_train, neigh.predict(X_train)))
print("Test set Accuracy: ", metrics.accuracy_score(y_test,yhat))
# <div id="12">
# <h2> What about other K</h2>
# </div>
#
# K in KNN, is the number of nearest neighbors to examine. It is supposed to be specified by the User. So, how can we choose right value for K?
# The general solution is to reserve a part of your data for testing the accuracy of the model. Then chose k =1, use the training part for modeling, and calculate the accuracy of prediction using all samples in your test set. Repeat this process, increasing the k, and see which k is the best for your model.
#
# We can calculate the accuracy of KNN for different Ks.
#
# In[173]:
Ks = 10
mean_acc = np.zeros((Ks-1))
std_acc = np.zeros((Ks-1))
for n in range(1,Ks):
#Train Model and Predict
neigh = KNeighborsClassifier(n_neighbors = n).fit(X_train,y_train)
yhat=neigh.predict(X_test)
mean_acc[n-1] = metrics.accuracy_score(y_test, yhat)
std_acc[n-1]=np.std(yhat==y_test)/np.sqrt(yhat.shape[0])
mean_acc
# <div id="13">
# <h2> Plot model accuracy for different number of neighbors </h2>
# </div>
# In[171]:
plt.plot(range(1,Ks),mean_acc,'g')
plt.fill_between(range(1,Ks),mean_acc - 1 * std_acc,mean_acc + 1 * std_acc, alpha=0.10)
plt.fill_between(range(1,Ks),mean_acc - 3 * std_acc,mean_acc + 3 * std_acc, alpha=0.10,color="green")
plt.legend(('Accuracy ', '+/- 1xstd','+/- 3xstd'))
plt.ylabel('Accuracy ')
plt.xlabel('Number of Neighbors (K)')
plt.tight_layout()
plt.show()
# In[172]:
print( "The best accuracy was with", mean_acc.max(), "with k=", mean_acc.argmax()+1)
|
import numpy as np
def pi_bound(x):
return (x + np.pi) % (2 * np.pi) - np.pi
def cross_product(a, b):
assert len(a) == len(b) == 3, 'Vectors a, b must be three-dimensional'
out = np.array(
[a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]]
)
return out |
import Tree
def pretty_print_tree(root):
"""
This function pretty prints a binary tree
:param root: root of tree
:return: none
"""
lines, _, _, _ = _pretty_print_tree(root)
for line in lines:
print(line)
def _pretty_print_tree(root):
"""
Code credits: Stack overflow
:param root: root of tree
:return: none
"""
if root.right is None and root.left is None:
line = '%s' % root.key
width = len(line)
height = 1
middle = width // 2
return [line], width, height, middle
# Only left child.
if root.right is None:
lines, n, p, x = _pretty_print_tree(root.left)
s = '%s' % root.key
u = len(s)
first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s
second_line = x * ' ' + '/' + (n - x - 1 + u) * ' '
shifted_lines = [line + u * ' ' for line in lines]
return [first_line, second_line] + shifted_lines, n + u, p + 2, n + u // 2
# Only right child.
if root.left is None:
lines, n, p, x = _pretty_print_tree(root.right)
s = '%s' % root.key
u = len(s)
first_line = s + x * '_' + (n - x) * ' '
second_line = (u + x) * ' ' + '\\' + (n - x - 1) * ' '
shifted_lines = [u * ' ' + line for line in lines]
return [first_line, second_line] + shifted_lines, n + u, p + 2, u // 2
# Two children.
left, n, p, x = _pretty_print_tree(root.left)
right, m, q, y = _pretty_print_tree(root.right)
s = '%s' % root.key
u = len(s)
first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s + y * '_' + (m - y) * ' '
second_line = x * ' ' + '/' + (n - x - 1 + u + y) * ' ' + '\\' + (m - y - 1) * ' '
if p < q:
left += [n * ' '] * (q - p)
elif q < p:
right += [m * ' '] * (p - q)
zipped_lines = zip(left, right)
lines = [first_line, second_line] + [a + u * ' ' + b for a, b in zipped_lines]
return lines, n + m + u, max(p, q) + 2, n + u // 2
tree = Tree.AvlTree()
tree.insert(1, 1)
tree.insert(5, 1)
tree.insert(10, 1) #left rotation
pretty_print_tree(tree.root)
print()
tree.insert(9, 1)
tree.insert(8, 1) #right-left rotation
pretty_print_tree(tree.root)
print()
if tree.contains(8):
tree.delete(8)
if tree.contains(10):
tree.delete(10)
if tree.contains(17): #doesn't contain
tree.delete(17)
pretty_print_tree(tree.root)
print()
tree.insert(-1, 1)
tree.insert(-2, 1) #right rotation
pretty_print_tree(tree.root)
print()
tree.insert(2, 1) #left-right rotation
pretty_print_tree(tree.root)
print()
if tree.contains(-2):
tree.delete(-2)
if tree.contains(-1):
tree.delete(-1) #left rotation
pretty_print_tree(tree.root)
print()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 13:39:26 2019
@author: zoureni
"""
#Entrer le nombre d'heure
nombre_d_heure = int(input("entrer le nombre d'heure "))
#On multiplie le nombre d'heure par 60
nombre_de_minutes = nombre_d_heure * 60
#On imprime le résultat
print(("le nombre de minutes est égale à "),(nombre_de_minutes)) |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 6 15:23:39 2019
@author: 3300116973
"""
print(3 + 2) # Addition
print(2 * 3) # multiplication
print(3 // 3)# division entiere
print(7 / 2)#Division
print(5 % 2)# modulo
print(5 - 2)# soustraction
print(2 ** 8)# exposant
# comparaison
print(50 > 10)# strictement superieur
print(2 >= 1)# superieur ou egal
print(8 < 2)# strictement inferieur
print(10 <= 5)#
print(2 == 3)#egalite
print(4 != 5)#difference
#member
print("br" in "bracelet")#membre
print("co"not in "corrola")#not member
#logique
print (True and True)
print(False and True)
print (True or False)
print(False or False)
#combinaison
print( 3 < 2 ** 3 and 3 == 3)
print(0 != 4 or (3/3 == 1 and (5 + 1) / 3 == 2) )
print ('a' in 'code' or 'b' in 'python'and len("programm") ==7)
x = 4
if (x % 4 == 0):
print("pair")
elif (x < 0 ) :
print("impair nefatif")
else : ("impair positif")
|
Created on Tue Nov 06 18:24:03 2019
@author: idira
"""
# creer une variable Ch contenant le chaine ma chaine
ch = 'Tombouctou'
#afficher tout le caractere 'Tombouctou'
print (ch)
# afficher le premier caractere(T).
print(ch[0])
# afficher le caractere t
print(ch[7])
# afficher la chaine de caractere "ob" dans la chaine ma chaine
print(ch[1:5:2])
# afficher la chaine de caractere 'uc' dans la chaine 'ma chaine'
print(ch[5:7:1])
|
# calcul de fonction f
def f( x):
return x+1
x=1
print(f(1))
# chercher un resultat qui sera inerieur ou egale a 10.
n =0
while n <=10:
n = n+1
print (n)
#le resultat la racine
x = 0
while x <=10:
x = x + 1
from math import sqrt
print(sqrt(f(x)))
|
# Ma variable en mémoire
# Type Inference
x=1
print(2*x)
# Integer
x=4
print(2*x)
if (x == 4):
print('x = 4')
else:
print('on ne sait pas')
a = 'x = 4'
print ( a )
#string
a = 'x = 4'
print ( a )
# Double
d = 2.56
print (2 * d)
|
# -*- coding: utf-8 -*-
# les operateurs
print(5+2) # addtion
print(6-2) # soustraction
print(47/3) # division
print(14//9) # division entière
print(9 % 2) # le reste de la division ou modulo
print(4**5) # l'exposant
# comparateurs
print(4>5) # superieur
print(5<10) # inferieur
print(4!=4) # different
print(4==8) # egale
print(45<=1) # inferieur
print(8>=3) #superieur
# membre ou appartenance
print("fr" in "franck") # appartient
print("au" not in "douala") # n'appartient pas
# operateur logique
print("bl" in "bloguer" or 5//2 == 1)
# combinaison
print(4==8 or 4>5 and (54 > 5))
# bloc d'instruction
x= int(input("entrer une valeur: "))
if x % 2 == 0 :
print("nombre paire")
elif x<0:
print("nombre negative")
else:
print("nombre impaire")
|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 4 14:26:20 2019
@author: 300117806
"""
def f(x):
return x + 1
print (f(1))
#Creation de boucle avec while
i=0
while i < 10:
print(f(i))
i = i + 1
#creation de boucle avec racine carree de 1 a 10
import math
def f(x):
return x + 1
i =1
while i < 10:
print(math.sqrt(f(i)))
i = i + 1
|
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 14:23:41 2019
@author: Amir
"""
print('hello')
#tuple t1 vide
t1 = ()
print ( t1 )
# tuple t2 une paire de meme type
t2 = (4, 5)
print ( t2 )
#tuple t3 une paire de type different
t3 = ('a', '2' )
print( t3 )
#tuple t4 un trio de type de types differents
t4 = ('a1', 2.5, False)
print ( t4 )
# imprimer la longueur de t4 (length)
print (len(t4) )
# imprimer la longueur d'un tuple vide
print (len(()))
#imprimer la valeur de t4 a l'index 2
print( t4 [2] )
|
"""
@author: Morti
"""
print("welcome to the mashup game")
name1=input("inter one full name(First Last) :")
name2=input("enter another full name(First Last) :")
space=name1 . find (" ")
name1_first=name1[0:space]
name1_last=name1[space+1:len(name1)]
space=name2.find(" ")
name2_first=name2[0:space]
name2_last=name2[space+1:len(name2)]
print(name1_first)
print(name1_last)
print(name2_first)
print(name2_last)
len_name1_first=len(name1_first)
len_name2_first=len(name2_first)
len_name1_last=len(name1_last)
len_name2_last=len(name2_last)
index_name1_first= int(len_name1_first/2)
index_name2_first= int(len_name2_first/2)
index_name1_last= int(len_name1_last/2)
index_name2_last= int(len_name2_last/2)
lefthalf_name1_first= name1_first[0:index_name1_first]
righthalf_name1_first= name1_first[index_name1_first:len_name1_first]
lefthalf_name2_first= name2_first[0:index_name2_first]
righthalf_name2_first= name2_first[index_name2_first:len_name2_first]
lefthalf_name1_last= name1_last[0:index_name1_last]
righthalf_name1_last= name1_last[index_name1_last:len_name1_last]
lefthalf_name2_last= name2_last[0:index_name2_last]
righthalf_name2_last= name2_last[index_name2_last:len_name2_last]
newname1_first=lefthalf_name1_first.capitalize() + \
righthalf_name2_first.lower()
newname1_last=lefthalf_name1_last.capitalize() + \
righthalf_name2_last.lower()
newname2_first = lefthalf_name2_first.capitalize() + \
righthalf_name1_first.lower()
newname2_last = lefthalf_name2_last.capitalize() + \
righthalf_name1_last.lower()
print("All done! Here are two possibilities, pick the one you like \
best!")
print(newname1_first, newname1_last)
print(newname2_first, newname2_last)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 17:56:17 2019
@author: Nathalie
"""
print("bienvenue au mashup game")
# l'utilisateur doit entre son nom et son prenom
nom1 = str(input("entre le premier nom (FIRST LAST) : "))
# l'utilisateur a la possibilite d'entrer deux autres noms
nom2 = str(input("entre un autre nom complet (FIRST LAST): "))
# definir les premiers et dernier noms comme une variable
space = nom1.find(" ")
nom1_first = nom1 [0:space]
nom1_last = nom1 [space+1:len(nom1)]
space = nom2.find(" ")
nom2_first = nom2 [0:space]
nom2_last = nom2[space+1:len(nom2)]
print(nom1_first)
print(nom1_last)
print(nom2_first)
print(nom2_last)
# definir la motie de chaque noms
len_nom1_first = len(nom1_first)
len_nom2_first = len(nom2_first)
len_nom1_last = len(nom2_last)
len_nom2_last = len(nom2_last)
index_nom1_first = int(len_nom1_first/2)
index_nom2_first = int(len_nom2_first/2)
index_nom1_last = int(len_nom1_last/2)
index_nom2_last = int(len_nom2_last/2)
lefthalf_nom1_first = nom1_first [0:index_nom1_first]
righthalf_nom1_first = nom1_first [index_nom1_first:len_nom1_first]
lefthalf_nom2_first = nom2_first [0:index_nom2_first]
righthalf_nom2_first = nom2_first [index_nom2_first:len_nom2_first]
lefthalf_nom1_last = nom1_first [0:index_nom1_last]
righthalf_nom1_last = nom1_first [index_nom1_last:len_nom1_first]
lefthalf_nom2_last = nom2_first [0:index_nom2_last]
righthalf_nom2_last = nom2_first [index_nom2_last:len_nom2_first]
# combinaison des differents noms
nouveaunom1_first = lefthalf_nom1_first.capitalize() + \
righthalf_nom2_first.lower()
nouveaunom1_last = lefthalf_nom1_last.capitalize() + \
righthalf_nom2_last.lower()
nouveaunom2_first = lefthalf_nom2_first.capitalize() + \
righthalf_nom1_first.lower()
nouveaunom2_last = lefthalf_nom2_last.capitalize() + \
righthalf_nom1_last.lower()
# afficher les noms combines premier et deuxieme noms
print("Fin! ici vous avez deux possibilitees, choississez ce que vous aimez le plus!")
print(nouveaunom1_first, nouveaunom1_last)
print(nouveaunom2_first, nouveaunom2_last)
#afficher chaque nom combine
print("vous avez termine! choississez ce que vous aimez le plus")
print(nouveaunom1_first)
print(nouveaunom1_last)
print(nouveaunom2_first)
print(nouveaunom2_last)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 16:13:44 2019
@author: 10
"""
for v in range(3):
print ("var v is" ,v)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 14:03:09 2019
@author: zoureni
"""
for v in range(3):
print('var is' , v) |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 15:31:58 2019
@author: User
"""
# Declaration de la variable heure
heures= int(input('veuillez entrez votre heure: '))
# calcul de la conversation d'heure en minutes
minutes = heures*60
# affichage du resultat obtenue apres convertion
print('la converstion de', heures, 'heures', 'egale:', minutes, 'minutes')
|
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 11:24:00 2019
@author: willfrid boris
"""
###recherche la chaine 'and' dans la varaible who
who="me myself and I"
print(who.find("and"))
print(len(who))
fruit="pomme"
#imprimer le nombre de fois que le caracter "m" apparait dans fruit
print(fruit.count('m'))
print(fruit.replace("mm","ir"));
concat='raptors'+ ' vs ''Golden State Warrios'
print(concat)
t1=()
print(t1)
t2=(4,5)
print(t2)
t3=('a',2)
print(t3)
t4=('a1',2.5,False)
print(t4)
print(len(t4))
#imprimer la longueur d'un tuple vide
print(len(()))
#imprimer la valeu de t4 a l'index 2
print(t4[2])
|
import turtle
import math
# everything is in base SI units, scale just helps keep everything on a normal-sized screen
t = turtle.Turtle()
# parameters
x = 0.1 # x value of the spaceship. Has to be greater than 0, or else the program will crash from the first calculation.
y = 160 # y value of the spaceship
dx = 5 # x velocity (delta-x)
dy = 0 # y velocity (delta-y)
ax = 0 # x acceleration
ay = 0 # y acceleration
pr = 80 # planet radius
pm = 6.67*10**16 # planet mass
scale = 1000 # see function above. Essentially saying 1 turtle unit = scale meters
t.penup() # draw planet
t.goto(0,-pr)
t.pendown()
t.circle(pr)
t.penup()
t.goto(x,y)
t.pendown()
while True:
theta = math.atan(abs(y/x))
g = -(6.67*10**-11)*pm/(x**2+y**2) # newton's law of gravitation modified for calculating gravitaitional field strength
ax = abs(g*math.cos(theta)) # calculating magnitude of accelerations in each direction
ay = abs(g*math.sin(theta))
ax /= scale # adjusting scale
ay /= scale
if x > 0 and y > 0: # changing direction of acceleration depending on orientation relative to planet
ax *= -1
ay *= -1
elif x > 0 and y < 0:
ax *= -1
elif x < 0 and y > 0:
ay *= -1
dx += ax # changing dx, dy, x, and y values
dy += ay
x += dx
y += dy
t.goto(x,y)
|
from math import sin, cos, atan2, hypot, exp, floor, tan, sqrt
from assignment_3.geometry import to_index, to_world, to_grid
# ------------------------------------------------------------------------------
# Given two integer coordinates of two cells return a list of coordinates of
# cells that are traversed by the line segment between the centers of the input
# cells
def line_seg(x0, y0, x1, y1):
points = []
# Setup initial conditions
dx = abs(x1 - x0)
dy = abs(y1 - y0)
x = x0
y = y0
n = 1 + dx + dy
x_inc = 1 if x1 > x0 else -1
y_inc = 1 if y1 > y0 else -1
error = dx - dy
dx *= 2
dy *= 2
# Traverse
while n > 0:
points.append((x, y))
if error >= 0:
x += x_inc
error -= dy
else:
y += y_inc
error += dx
n-=1
# Return
return points
#-------------------------------------------------------------------------------
# Given a ray find the coordinates of the first occupied cell in a ray
# Parameters:
# x0, y0 map coordinates of a cell containing ray origin
# angle angle of a ray
# the_map map
# Return:
# first occupied cell
def ray_tracing(x0, y0, angle, the_map):
print 'ray_tracing'
print 'the_map', the_map
print 'x0,y0,angle' ,x0,y0,angle
####
# if angle > 0:
# if angle < 1.57:
# x_ext = the_map.info.width / the_map.info.resolution
# y_ext = the_map.info.height / the_map.info.resolution
# else:
# x_ext = 0
# y_ext = the_map.info.height / the_map.info.resolution
# else:
# if abs(angle) < 1.57:
# x_ext = the_map.info.width / the_map.info.resolution
# y_ext = 0
# else:
# x_ext = 0
# y_ext = 0
# #
# opp_value = abs(x_ext-x0) * tan(angle)
# adj_value = abs(y_ext-y0) / tan(angle)
# y_new = y0 + opp_value
# x_new = x0 + adj_value
# # print 'x_new,y_new', x_new,y_new
# if y_new >= 0:
# if y_new <= (the_map.info.height / the_map.info.resolution):
# y1 = y_new
# x1 = x_ext
# else:
# y1 = y_ext
# x1 = x_new
# else:
# y1 = y_ext
# x1 = x_new
# # print 'x_ext,y_ext', x_ext,y_ext
# print 'x1,y1', x1,y1
#####
hyp = 1.5 * (sqrt(pow(the_map.info.height,2) + pow(the_map.info.width,2)))
x1 = x0 + (hyp * cos(angle))
y1 = y0 + (hyp * sin(angle))
points = line_seg(x0, y0, x1, y1)
print 'points', points
# print points[0]
# print points[0][0]
# print points[0][1]
stopWhile = 1
k = 1
while stopWhile == 1:
# if points[k][1] > 1:
index_value = (points[k][0] - 1) * the_map.info.width / the_map.info.resolution
index_value = index_value + points[k][1]
# else:
# index_value = points[k][0]
index_value = int(index_value)
# print 'index_value', index_value
# print 'data point:', the_map.data[index_value]
if the_map.data[index_value] == 100:
stopWhile = 0
pointFound = 1
elif k == len(points):
stopWhile = 0
else:
k = k + 1
if pointFound == 1:
print points[k]
range_value = sqrt( pow((points[k][1]-y0),2) + pow((points[k][0]-x0),2) )
print 'range_value',range_value
return range_value
else:
return None
#-------------------------------------------------------------------------------
# Returns a laser scan that the robot would generate from a given pose in a map
# Parameters:
# x0, y0 robot position in map coordinates
# theta robot orientation
# min_angle minimum angle of laserscan
# increment laserscan increment
# n_readings number of readings in a laserscan
# max_range maxiimum laser range
# the_map map
# Return:
# array of expected ranges
def expected_scan(x, y, theta, min_angle, increment, n_readings, max_range, the_map):
print 'expected_scan'
ranges = []
print x, y, theta, min_angle, increment, n_readings, max_range
start_angle = theta + min_angle
print 'start_angle: ', start_angle
if start_angle > 3.14:
diff_angle = start_angle - 3.14
start_angle = -3.14 + diff_angle
elif start_angle < -3.14:
diff_angle = abs(start_angle) - 3.14
start_angle = 3.14 - diff_angle
print 'start_angle: ', start_angle
for i in range(n_readings):
# print 'i', i
theta = start_angle + (i*increment)
if theta > 3.14:
diff_angle = theta - 3.14
theta = -3.14 + diff_angle
elif theta < -3.14:
diff_angle = abs(theta) - 3.14
theta = 3.14 - diff_angle
range_value = ray_tracing(x,y,theta, the_map)
if range_value > max_range:
range_value = max_range
ranges.append(range_value)
elif range_value != None:
ranges.append(range_value)
# print 'the_map is:'
# print the_map
# print 'data', len(the_map.data)
# print 'n_readings', n_readings
print 'ranges:', ranges
return ranges
#-------------------------------------------------------------------------------
# Computes the similarity between two laserscan readings.
# Parameters:
# ranges0 first scan
# ranges1 second scan
# max_range maximum laser range
# Return:
# similarity score between two scans
def scan_similarity(ranges0, ranges1, max_range):
print 'scan_similarity'
# print ranges0
# print 'length of ranges0', len(ranges0)
print 'length of ranges0', len(ranges0)
print 'length of ranges1', len(ranges1)
print 'ranges0', ranges0
print 'ranges1', ranges1
count_1 = 0.0
for i in range(len(ranges1)):
diff = abs(ranges0[i] - ranges1[i])
if diff < 0.5:
count_1 = count_1 + 1
print 'count_1', count_1
#
count_2 = 0
v = len(ranges1) - 1
for u in range(len(ranges1)):
diff = abs(ranges0[u] - ranges1[v])
v = v - 1
if diff < 0.5:
count_2 = count_2 + 1
print 'count_2', count_2
score = (count_1/90)
return score |
import time
print("Hallo, welkom bij me beroeps opdracht. \nJe krijgt straks verschillende vragen en elke vraag beinvloed het spel, sommige kunnen je dus af laten gaan. Succes! ")
def vraag1():
vraag1 = input("Je zit thuis en hoort ineens een knal. Wat doe je? \n A) Je doet niks en hoopt op het beste. B) Je vlucht en bent van plan naar nederland te gaan. ")
if vraag1.lower() == "b":
vraag2()
elif vraag1.lower() == "a":
print("Je bent meteen ontploft je bent af probeer het opnieuw.")
vraag1
def vraag2():
vraag2 = input("Alright we gaan naar Nederland. Je pakt je spullen en bent van plan te gaan. Maar hoe ga je er heen?\nA) Met de boot B) Lopend en proberen te mee liften met mensen. ")
if vraag2.lower() == "a":
vraag3()
elif vraag2.lower() == "b":
vraag4()
def vraag4():
vraag4 = input("Een auto stopt en wilt je helpen over de grens. Hij stelt je eerst een vraag en dat bepaalt of je mee mag of niet. De vraag is: is het friet of patat. A) Friet B) Patat")
if vraag4.lower() == "a":
vraag8()
elif vraag4.lower() == "b":
vraag15()
def vraag3():
vraag3 = input("d")
if vraag3.lower() == "a":
vraag5()
elif vraag3.lower() == "b":
vraag5()
def vraag5():
vraag5 = input("Interesant!\nWaar ben je van plan te wonen? A) Noord-Holland B) Zuid-Holland")
if vraag5.lower() == "a":
vraag6()
elif vraag5.lower() == "b":
vraag6()
def vraag6():
vraag6 = input("Ahh oke!\nEr komen flinken golven met tegen wind. Blijf je door varen op de hoop dat je het nog red of blijf je drijven terwijl je terug drijft A) Door varen B) Drijven")
if vraag6.lower() == "a":
vraag7()
elif vraag6.lower() == "b":
vraag7()
def vraag7():
vraag7 = input("Je bent veilig in nederland aangekomen. Bedank je de bestuurder?\n A) Ja B) Nee")
if vraag7.lower() == "a":
print("Dat is netjes, hij geeft je 50% korting!\nJe word gewaardeerd in nederland. Je hebt je droom baan en woont op de plek waar je wou!\n Je hebt het gehaald!")
elif vraag7.lower() == "b":
print("Dat is niet zo netjes.. Hij wou je korting geven maar die kan je nu vergeten\nJe word gewaardeerd in nederland. Je hebt je droom baan en woont op de plek waar je wou!\n\n Gefeliciteerd je hebt het gehaald!")
def vraag8():
vraag8 = input("De helper is hier totaal NIET blij mee.. Hij besluit je te ontvoeren. Werk je mee of stribel je tegen? \nA) Je werkt mee B) Je stribelt tegen")
if vraag8.lower() == "a":
print("Goede keus, hij slaat je in de boeie en doet een blindoek om.")
vraag9()
elif vraag8.lower() == "b":
print("Je bent veel te vervelend en hij slaat je KO, zet je in het voertuig en gaat er vandoor.")
vraag9()
def vraag9():
vraag9 = input("Je zit op een stoel. En de ontvoerder komt naar je toe. Hij begint je te ondervragen waarom je friet koos.. A) Je zegt: Het is toch gwn friet?.. B) Je zegt dat je z.s.m antwood wou geven waardoor je maar wat zij")
if vraag9.lower() == "a":
vraag10()
elif vraag9.lower() == "b":
vraag10()
def vraag10():
vraag10 = input ("Je had gwn patat moeten zeggen Ik geef je de keus uit 2 items.. We gaan vechten wat kies je? A) Een Walther P99 B) Een Knuppel")
if vraag10.lower() == "a":
vraag11()
elif vraag10.lower() == "b":
vraag12()
def vraag12():
vraag12 = input("Je gaat hem proberen te slaan waar sla je? A) Hoofd B) Been")
if vraag12.lower() == "a" "b":
vraag14()
def vraag11():
vraag11 = input ("Je krijgt het wapen in je handen en wilt hem schieten. Waar schiet je? A) Been B) Hoofd")
if vraag11.lower() == "a" "b":
vraag13()
def vraag13():
vraag13 = input ("Er zaten geen kogels in het wapen.. Hij komt op je af wat doe je? A) Je gooit het wapen naar hem toe B) Je doet alsof er een kogel in zit")
if vraag13.lower() == "a":
print("Je mist\nHij gaat het gevecht met je aan en wint.. Je bent af, probeer het opnieuw!")
time.sleep(1)
vraag1
elif vraag13.lower() == "b":
print("Hij is niet gek hij heeft de kogels er zelf uit gehaald..\nHij gaat het gevecht met je aan en wint..\nJe bent af, probeer het opnieuw!")
time.sleep(1)
vraag1
def vraag14():
vraag14 = input("Je houte knuppel breekt door 2e das balen. Wat doe je nu? A) Je gooit het kleine deel B) Je probeert met een kleine helft over door te vechten.")
if vraag14.lower() == "a":
print("Je mist.. Hij gaat het gevecht met je aan en wint.\n Je hebt verloren probeer het opnieuw!")
time.sleep(1)
vraag1
elif vraag14.lower() == "b":
print("Je was verbaast toen je knuppel brak. De overvaller was er snel bij en pakte de knuppel af\nHij gaat het gevecht met je aan en wint..\nJe hebt verloren probeert het opnieuw!")
time.sleep(1)
vraag1
def vraag15():
vraag15 = input ("De helper vond dat het goede antwoord en wilt je meenemen de grens over.\nNa wat gesprekken gaat het over je toekomst in nederland. Wat wil je later worden? A) Software Developer B) 2D Designer")
if vraag15.lower() == "a" "b":
vraag16()
def vraag16():
vraag16 = input("Goede keus zegt ie, maar waar ben je van plan te wonen? A) Zuid Holland B) Noord Holland")
if vraag16.lower() == "a" "b":
vraag17()
def vraag17():
vraag17 = input("Heb je nog Hobby's A) Vissen B) Muziek")
if vraag17.lower() == "a":
vraag18()
elif vraag17.lower() == "b":
vraag19()
def vraag18():
vraag18 = input("Vis je op roof vis of van alles? A) Roof B) van alles")
if vraag18.lower() == "a" "b":
vraag20()
def vraag19():
vraag19 = input("leuk luister je er alleen naar of speel je ook zelf? A) Luisteren B) Zelf")
if vraag19.lower() == "a" "b":
vraag20()
def vraag20():
vraag20 = input("Interesant en leuk! Ga je dit ook doen in nederand? A) Ja B) Nee")
if vraag20.lower() == "a":
print("Ah oke, je bent veilig afgezet en de helper wenst je veel succes!\nJe hebt het gehaald gefeliciteerd!")
elif vraag20.lower() == "b":
vraag21()
def vraag21():
vraag21 = input("Oh, hoezo niet ga je het niet missen? A) Helaas wel B) Nee hoor")
if vraag21.lower() == "a" "b":
print("Ah oke, je bent veilig afgezet en de helper wenst je veel succes!")
vraag1() |
from neuralnet import *
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import generallib as gl
#le dataset
y_column = -1
data = pd.read_csv("data/Churn_Modelling_Edited.csv") #abre arquivo
y = np.array(pd.DataFrame(data.iloc[:, y_column]))
dataset = np.array(data.drop(data.columns[y_column], axis=1))
dataset = gl.normalization(dataset)
n = NeuralNet(dataset, y) #cria a rede neural.... já treina ela?
n.fit() #?
n.savetofile()
result = n.classify(dataset) #?
result = (result > 0.5)
expected = (y > 0.5)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(expected, result) # ? resultado do teste com a rede neural?
#n.save_to_txt("test2.txt")
|
l=lambda x:'EVEN'if x%2==0 else 'ODD'
k=int(input("enter a number"))
print(l(k)) |
# *** coding: utf-8 ***
#@Time : 2020/12/4 15:25
#@Author : xueqing.wu
#@Email : wuxueqing@126.com
#@File : test.py
# num1 = input('请输入第一个数字:')
# num2 = input('请输入第二个数字:')
# num3 = input('请输入第三个数字:')
#
# if num1.isdigit() and num2.isdigit() and num3.isdigit():
# num1 = int(num1)
# num2 = int(num2)
# num3 = int(num3)
# all_num = [num1, num2, num3]
# print(all_num)
# sort_num = []
# for i in range(0, len(all_num)):
# sort_num.append(max(all_num))
# all_num.remove(max(all_num))
# print(sort_num)
#
#
# # all_num.sort(reverse=False)
# # for i in range(0, len(all_num)):
# # for j in range(0, len(all_num)-1-i):
# # if all_num[j] > all_num[j+1]:
# # temp = all_num[j]
# # all_num[j] = all_num[j+1]
# # all_num[j+1] = temp
# # print('排序的结果是:{}'.format(all_num))
# else:
# print('非法的数字')
# def Fibonacci(num):
# if num <= 0:
# print('请输入一个正整数')
# if num == 1:
# print('斐波拉契数列:[0]')
# elif num == 2:
# print('斐波拉契数列:[0, 1]')
# else:
# n1 = 0
# n2 = 1
# count = 2
# fib_list = [0, 1]
# while count < num:
# n3 = n1 + n2
# fib_list.append(n3)
# n1 = n2
# n2 = n3
# count += 1
# print('斐波拉契数列:{}'.format(fib_list))
#
# def Fib(num):
# if num == 1 or num == 2:
# return 1
# else:
# return Fib(num - 1) + Fib(num - 2)
#
#
# if __name__ == '__main__':
# num = input('请输入斐波拉契数列项数:')
# if num.isdigit():
# fib_list = Fibonacci(int(num))
# else:
# print('非法项数')
#
# for i in range(1, 11):
# print(Fib(i), end=' ')
a = ['a', 'b', 'c']
b = ', '.join(a)
print(b) |
class Cat:
def __init__(self,name):
self.name = name
self.kind = "cat"
self.next = None
def __str__(self):
return f"I am a cat, my name is {self.name}"
class Dog:
def __init__(self,name):
self.name = name
self.kind = "dog"
self.next = None
def __str__(self):
return f"I am a dog, my name is {self.name}"
class AnimalShelter:
def __init__(self,front=None):
self._front = front
self._rear = self._front
def enqueue(self,animal,name):
if animal == "cat":
new_animal = Cat(name)
elif animal == "dog":
new_animal = Dog(name)
else:
raise Exception("This sheltor only accepts cats and dogs")
if self._rear is None:
self._front = self._rear = new_animal
else:
self._rear.next = new_animal
self._rear = new_animal
def dequeue(self,pref=None):
if pref is None:
return "Null"
else:
try:
if self._front.kind == pref:
dequeue_animal = self._front
self._front = self._front.next
return dequeue_animal
else:
current = self._front
while True:
if current.next.kind == pref:
dequeue_animal = current.next
current.next = current.next.next
return dequeue_animal
current = current.next
except:
print(f'The shelter does not have {pref} now')
def __str__(self):
output = ""
current = self._front
while current:
output += f"{current.kind} {current.name} & "
current = current.next
return output + "are in the shelter now"
|
# a function to reverse an input array
def reverseArray(inputArray):
for i in range(len(inputArray)//2):
inputArray[i],inputArray[-i-1]=inputArray[-i-1],inputArray[i]
return inputArray
# print(reverseArray([1,2,3,4,5]))
# print(reverseArray([89, 2354, 3546, 23, 10, -923, 823, -12]))
# method #2.
def reverseArray2(inputArray):
outputArray=[]
for i in range(len(inputArray)):
outputArray.append(inputArray[-i-1])
return outputArray
# print(reverseArray2([1,2,3,4,5,6,7]))
#method #3
def reverseArray3(inputArray):
return inputArray[::-1]
# print(reverseArray3([1,2,3,4,5]))
|
locations = [["The Porch", "An old, wooden porch lies before the entrance to the house.", {"key": ["A rusty old key.", False, [False, None]]}],
["Hallway", "The hallway is laden with dust. Old paintings hang from the crumbling walls.", {"painting": ["An old painting. '07/10/1873' is written in the lower right corner.", True, [False, None]],
"safe": ["A steel safe. It ain't coming open with brute force.", True, [True, ["NUM", ["7183", "REMOVE REPETITIONS"]]]]}],
] # <- Final List Bracket (Needed)
# Items #
# [[PLACE NAME, PLACE DESCRIPTION, {ITEMS: [ITEM DESCRIPTION: STATIC(TRUE) OR NOT STATIC(FALSE), SPECIAL [YES(TRUE) OR NO(FALSE), TYPE(OR JUST 'NONE' IF IT SAYS FALSE BEFOREHAND)]]}]]
import os
position = 0
inventory = {}
def displayStats(position):
print(locations[position][0])
print(locations[position][1])
def parseUse(item, location, Object):
go = False
if item.lower() == "key" and location == "The Porch" and (Object.lower() in ["door", "the door"]):
go = True
del inventory[item]
print("")
else:
print("Nothing happened. Are you sure you're thinking straight?")
return go
def parseSpecial(details):
if details[0] == "NUM":
correct = False
# Number Puzzle #
print("There's a number lock on this.")
print("A piece of paper is stuck to the wall beside it.")
print("")
print("'" + details[1][1] + "'")
print("")
guess = int(input("Please enter your guess > "))
if guess == details[1][0]:
correct = True
else:
print("...nothing happens.")
return correct
def prompt(position):
print("")
user = input("Enter a command, or type 'help' > ")
print("")
user.lower()
itemKeys = list(locations[position][2].keys())
if user == "look":
if len(itemKeys) > 0:
print("")
print("Looking around, you see the following items: ")
for x in range(0, len(itemKeys)):
print(" " + itemKeys[x].title())
print(" " + locations[position][2][itemKeys[x]][0] + "\n")
elif len(itemKeys) == 0:
print("There's nothing at this location....")
elif user[:7] == "inspect":
if locations[position][2][user[8:]][2][0]:
correct = parseSpecial((locations[position][2][user[8:]][2][1]))
else:
print(" " + locations[position][2][user[8:]][0])
elif user[:4] == "take":
if user[5:] in itemKeys and not(locations[position][2][user[5:]][1]): # if the item you're trying to take is at the location and it's not a static item then take it
print("Took the " + user[5:] + ".")
inventory[user[5:]] = locations[position][2][user[5:]]
del locations[position][2][user[5:]]
elif len(user) == 4:
print("Tell me what to take.")
print("e.g. take item")
try:
if locations[position][2][user[5:]][1] and not(locations[position][2][user[5:]][2][0]):
print("You can't pick that up. It won't budge!")
except KeyError:
if not(user[5:] in itemKeys):
print("That item's not here....")
elif user == "help":
print("PROJECT-SIXTH")
print("")
print("The aim of PROJECT-SIXTH is to advance from one room to the next. It might be as simple as walking through the door, others will require the finding of small object")
print("")
print("Items in brackets show the syntax with which the command must be used.")
print("An x is specified by you, the player, when using the command.")
print("")
print("look - look around for items")
print("take (take x) - take an item")
print("use (take x) - use an item")
elif user[:4] == "move":
if user[5:] == "left":
position -= 1
elif user[5:] == "right":
position += 1
elif user[:3] == "use":
itemToUse = user[4:]
if itemToUse in list(inventory.keys()):
toUseOn = input("On what? > ")
go = parseUse(itemToUse, (locations[position][0]), toUseOn)
if go:
position += 1
print("Moved forward.")
else:
print("You don't have that item.")
elif user == "items":
itemKeys = list(inventory.keys())
if len(itemKeys) > 0:
for x in range(0, len(itemKeys)):
print(" " + itemKeys[x].title())
else:
print("You haven't got anything yet!")
else:
print("Eh?")
input("\nPlease press any key....")
return user, position
os.system("title PROJECT-SIXTH - A Puzzle Game by Jake Stringer")
while 1<2:
os.system("cls")
displayStats(position)
user, position = prompt(position)
input("") |
"""
Description:
Create blank Omnigo Data Object & fill in data
Convert Python Class Object to JSON string
Create JSON file if it doesn't exist
Append new JSON string to the file
"""
#import sys
import json
import sys
class OmniData:
CLIENT_NAME = 'TSE'
PROJECT_KIT_ID = 515151515
STAGE = 'NULL'
NO_OF_BOARDS = 0
NO_OF_PANELS = 0
STAFF_ID = 000
TIME = '00:00'
DATE = '01-01-2020'
START = '00:00'
STOP = '00:00'
FAULT = 'NULL'
SERIAL_NO = 121212121
def main():
exists = 0 # append after printing contents
# New Data to Class Object
OmniData1 = OmniData()
OmniData1.CLIENT_NAME = 'Omnigo'
OmniData1.PROJECT_KIT_ID = 123456789
OmniData1.STAGE = 'SMT'
OmniData1.NO_OF_BOARDS = 1000
OmniData1.NO_OF_PANELS = 50
OmniData1.STAFF_ID = 456
OmniData1.TIME = '12:35'
OmniData1.DATE = '11-06-2020'
OmniData1.START = '08:35'
OmniData1.STOP = '00:00'
OmniData1.FAULT = 'NULL'
OmniData1.SERIAL_NO = 987654321
#convert to JSON string
jsonStr = json.dumps(OmniData1.__dict__)
#print(jsonStr) #print json string
# Check if the file exists & read contents
try: # Skip if file doesn't exist
file = open('test.json', 'r') # Open to read file
print (file.read()) # Print the contents
file.close() # Close the file
except:
exists = 1 # Don't append twice if file exists
file= open("test.json","a+") # Create/open file then Append data
file.write(jsonStr + "\n") #
file.close() # Exit the opened file
# If file exists, append new string
if exists == 0: # append after printing contents
file= open("test.json","a+") # Create/open file then Append data
file.write(jsonStr + "\n") #
file.close() # Exit the opened file
else: #
print ("\nFile Didn't exist..." ) # notification
if __name__ == "__main__": main()
|
#================================
CAPTURING A SINGLE FRAME:
#================================
from cv2.cv import *
# Initialize the camera
capture = CaptureFromCAM(0) # 0 -> index of camera
if capture: # Camera initialized without any errors
NamedWindow("cam-test",CV_WINDOW_AUTOSIZE)
f = QueryFrame(capture) # capture the frame
if f:
ShowImage("cam-test",f)
WaitKey(0)
DestroyWindow("cam-test")
#To capture video, capture frames in a loop with appropriate waitkey.
#This method of capturing frames is similar to that of OpenCV 2.1
#================================
VIDEOCAPTURE
CAPTURING A SINGLE FRAME:
#================================
from cv2 import *
# initialize the camera
cam = VideoCapture(0) # 0 -> index of camera
s, img = cam.read()
if s: # frame captured without any errors
namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
imshow("cam-test",img)
waitKey(0)
destroyWindow("cam-test")
#This method is most extensively used to capture frames in OpenCV 2.3.1.
#https://jayrambhia.wordpress.com/2012/05/10/capture-images-and-video-from-camera-in-opencv-2-3-1/ |
# -*- coding: utf-8 -*-
"""
Description: Get image size in pixels
Resize 2 images to screen length [800]
width = scaled % of original width
"""
import PIL
from PIL import Image
file0 = "/home/antz/0_Python/image/Armadillo/img1.jpg" # path to woring directory
file1 = "/home/antz/0_Python/image/Armadillo/img2.jpg" # path for new images
def main():
# Get image pixel size (width x height)
with Image.open(file0) as img:
width, height = img.size
print('{0}, {1}'.format(width, height))
basewidth = 1600
img = Image.open(file0)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
img.save('img3.jpg')
baseheight = 1600
img = Image.open(file1)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
img.save('img4.jpg')
if __name__ == "__main__": main()
|
"""
70 Examples:
https://www.programcreek.com/python/example/83064/tkinter.OptionMenu
"""
import Tkinter as tk
OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
]
app = tk.Tk()
app.geometry('100x200')
variable = tk.StringVar(app)
variable.set(OptionList[0])
opt = tk.OptionMenu(app, variable, *OptionList)
opt.config(width=90, font=('Helvetica', 12))
opt.pack()
app.mainloop()
|
# -*- coding: utf-8 -*-
"""
Python 2.7 (virtual env)
-> If directory doesn't exist, it is created
-> If it exists, opens existing directory & prints contents
"""
import sys
import os
def main():
exists = 0 # variable to append after printing contents
cnt = 0 #
file_path1 = "/home/antz/0Python/files/notes.txt" #
file_path2 = "/home/antz/0Python/image" #
directory = os.path.dirname(file_path1)
if not os.path.exists(directory):
os.makedirs(directory)
print("Create Directory")
else:
print("Already Exists")
for file in os.listdir(file_path2):
print("{0}".format(os.listdir(file_path2)[cnt]))
cnt += 1
if __name__ == "__main__": main()
|
# -*- coding: utf-8 -*-
"""
Description: Description: Displays all images in full screen mode
Images found in given file path
Loops continuously [ctrl+C to exit]
"""
import pygame
import sys
import os
def main():
cnt = 0 # new file counter
#file_path1 = "/home/pi/Pictures/pics" # actual path
#file_path1 = "/home/pi/Documents/python/image/pic_frame/pic" # test path
file_path1 = "/home/pi/Documents/python/image/pic_frame" # test path
pygame.init()
screen = pygame.display.set_mode((0, 0))
clock = pygame.time.Clock() # setup the clock
## Check for directory, if not then create it ##
directory = os.path.dirname(file_path1) # check in images file path
if not os.path.exists(directory): # if directory doesn't exist
print("File path doesn't exist!") # Notify that directory was created
else:
try:
for file in os.listdir(file_path1): # each file in that folder
if file.endswith(".jpg"): # only do if .jpg file
pics = os.path.join(file_path1, file)
# Display different image on each iteration
try:
image = pygame.image.load(pics)
pygame.display.flip()
screen.fill((255,255,255))
screen.blit(image,(0,0))
clock.tick(0.5)
except KeyboardInterrupt:
print("Exit!")
sys.exit(0)
except KeyboardInterrupt:
print("Exit!")
sys.exit(0)
if __name__ == "__main__": main()
|
""" Created 8-bit Port for Raspberry Pi """
import wiringpi2 as wiringpi
from time import sleep # allows us a time delay
wiringpi.wiringPiSetupGpio()
wiringpi.pinMode(24, 1) # sets GPIO 24 to output
wiringpi.digitalWrite(24, 0) # sets port 24 to 0 (0V, off)
var=1
try:
print "Start loop"
while var==1 :
wiringpi.digitalWrite(24, 0) # sets port 24 to 0 (0V, off)
sleep(5) # 5sec
wiringpi.digitalWrite(24, 1) # sets port 24 to 1 (3V3, on)
sleep(5) # 5sec
wiringpi.digitalWrite(24, 0) # sets port 24 to 0 (0V, off)
wiringpi.pinMode(24, 0) # sets GPIO 24 back to input Mode
finally: # when you CTRL+C exit, we clean up
wiringpi.digitalWrite(24, 0) # sets port 24 to 0 (0V, off)
wiringpi.pinMode(24, 0) # sets GPIO 24 back to input Mode
# GPIO 25 is already an input, so no need to change anything
|
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
names = {
"tim": {
"age": 19,
"gender": "male"
},
"suyash": {
"age": 25,
"gender": "male"
},
"sonal": {
"age": 25,
"gender": "female"
}
}
class HelloWorld(Resource):
def get(self, name):
"""Handle GET requests at the URL registered for
the resource.
The name is a URL argument passed as a String.
Returns the response as a dict (formatted
as a JSON object) because it support serialization i.e.,
conversion of an object into a sequence of bits/byte stream.
"""
return names[name]
def post(self):
"""Handle POST requests at the URL registered for
the resource. Returns the response as a dict.
"""
return {"data": "Posted"}
api.add_resource(HelloWorld, "/helloworld/<string:name>")
if __name__ == "__main__":
app.run(debug=True)
|
name = "Vladut"
#Difference between Tuples () and Arrays [] is, that Tuples are immutable! It is recommended to use them, when we don't want values from it modified
months = ("January","February","March")
students = ["John","Diana","George"]
print(students)
print(students[0])
students.append("Kate")
print(students[-1])
students.insert(2,"Vladut")
print(students) |
# wip
# def insertion_sort(A, n, g):
# count = 0
# for i in range(g, n):
# v = A[i]
# j = i - g
# while j >= 0 and A[j] > v:
# A[j+g] = A[j]
# j= j - g
# count += 1
# A[j+g] = v
# return count
# def shell_sort(A, n):
# count = 0
# m =
# G[] = {}
# for i in range(0, m):
# insertion_sort(A, n, G[i])
# if __name__ == "__main__":
# N = int(input())
|
slowa = ['aaabaaa', 'aa', 'c', 'bbaa', 'baba', 'abba']
def palindrom(slowo):
print(slowo)
a=len(slowo)
b=a/2
i=0
while i < b:
if slowo[i] == slowo[-1-i]:
pass
else:
print("to nie jest palindrom")
return False
i=i+1
print("to jest palindrom")
return True
palindrom("aaabaaa")
palindrom("aa")
palindrom("c")
palindrom("bbaa")
palindrom("baba")
palindrom("abba")
palindrom(slowa[0])
def twopal(dlugosc):
if dlugosc== 1:
return "b"
elif dlugosc==2:
return "bb"
else:
return "b"+(dlugosc-2)*"a"+"b"
print("WPISZ DLUGOŚC PALINDROMU:")
slowo=twopal(int(input()))
print(slowo)
def genpal(dlugosc):
if dlugosc%2==1: #nieparzysty
return int(dlugosc/2)*"a"+"b"+int(dlugosc/2)*"a"
else: #parzysty
return int(dlugosc/2-1)*"a"+"bb"+int(dlugosc/2-1)*"a"
print("Generator palindromów. Wpisz liczbę:")
slowo=genpal(int(input()))
print(slowo)
def genpal(dlugosc):
if dlugosc%2==1: #nieparzysty
return int(dlugosc/2)*"a"+"b"+int(dlugosc/2)*"a"
else: #parzysty
return int(dlugosc/2-1)*"a"+"bb"+int(dlugosc/2-1)*"a"
lista=list()
x=0
while x <=99:
x+=1
print("Palindromy od 0 do 99")
print(genpal(x))
lista.append(genpal(x))
print(lista)
print(lista[3])
print(lista[7])
print(lista[15])
print(lista[62]) #nie wiem jak wypisać z listy na raz cztery rekordy?
lista2=list()
print("Wpisz liczbę aby wygenerować palindrom (1):")
a=int(input())
print(genpal(a))
lista2.append(genpal(a))
print("Wpisz liczbę aby wygenerować palindrom (2):")
a=int(input())
print(genpal(a))
lista2.append(genpal(a))
print("Wpisz liczbę aby wygenerować palindrom (3):")
a=int(input())
print(genpal(a))
lista2.append(genpal(a))
print("Wpisz liczbę aby wygenerować palindrom (4):")
a=int(input())
print(genpal(a))
lista2.append(genpal(a))
print("Wpisz liczbę aby wygenerować palindrom (5):")
a=int(input())
print(genpal(a))
lista2.append(genpal(a))
print("lista wygenerowanych palindromów")
print(lista2)
#6
a=1
palindrom1="aaaabaaaa"
palindrom1==palindrom1[::-1]
__author__ = "Paweł Lech" |
#!/usr/bin/env python
# coding: utf-8
# In[21]:
#1 Define a function named is_two. It should accept one input and return
#True if the passed input is either the number or the string 2,
#False otherwise.
def is_two(num):
return int(num) == 2
is_two(2)
# In[23]:
#2 Define a function named is_vowel. It should return True if the
#passed string is a vowel, False otherwise.
def is_vowel(let):
vowels = 'aeiouAEIOU'
return let in vowels
is_vowel('z')
# In[33]:
#3 Define a function named is_consonant. It should return True if
#the passed string is a consonant, False otherwise. Use your
#is_vowel function to accomplish this.
def is_consonant(con):
consonants = 'bcdfghjklmnpqrstvxzwy'
return con in consonants
is_consonant('c')
# In[32]:
#4 Define a function that accepts a string that is a word.
#The function should capitalize the first letter of the word
#if the word starts with a consonant.
def is_consonant(con):
consonants = 'bcdfghjklmnpqrstvxzwy'
return con in consonants
def first_consonant(word):
if str(word).isdigit():
return(word)
elif is_consonant(word[0]):
return(word[0].upper() + word[1:])
else:
return word
first_consonant('bomb')
# In[64]:
#5 Define a function named calculate_tip. It should accept a
#tip percentage (a number between 0 and 1) and the bill total,
#and return the amount to tip.
def calculate_tip(tip, bill):
return (tip * bill)
calculate_tip(.2, 78.99)
# In[4]:
#6 Define a function named apply_discount. It should accept a
#original price, and a discount percentage, and return the
#price after the discount is applied.
def apply_discount(disc, orig_price):
return (1 - disc) * orig_price
apply_discount(.15, 45.65)
# In[14]:
#7 Define a function named handle_commas. It should accept a
#string that is a number that contains commas in it as input,
#and return a number as output.
def handle_commas(s):
s = s.replace(',', '')
return s
handle_commas('1,000,000,000')
# In[2]:
#8 Define a function named get_letter_grade. It should accept
#a number and return the letter grade associated with that
#number (A-F).
def get_letter_grade():
grade = int(input("What was your grade?\t"))
print()
if grade >= 88 and grade <= 100:
print("You received an A")
elif grade >= 80 and grade <= 87:
print("You received a B")
elif grade >= 67 and grade <= 79:
print("You received a C")
elif grade >= 60 and grade <= 66:
print("You received a D")
elif grade >=0 and grade <= 59:
print("You failed with an F")
return grade
get_letter_grade()
#or
def get_letter_grade(num):
if num >= 90:
return 'A'
elif num >= 80:
return 'B'
elif num >= 70:
return 'C'
elif num >= 60:
return 'D'
else:
return 'F'
get_letter_grade(70)
# In[27]:
#9 Define a function named remove_vowels that accepts a
#string and returns a string with all the vowels removed.
def remove_vowels(c):
newstr = c
vowels = ('a', 'e', 'i', 'o', 'u')
for x in c.lower():
if x in vowels:
newstr = newstr.replace(x,"")
return newstr
remove_vowels('apple')
# In[ ]:
#10 Define a function named normalize_name. It should accept a
#string and return a valid python identifier, that is:
#anything that is not a valid python identifier should be removed
#leading and trailing whitespace should be removed
#everything should be lowercase
#spaces should be replaced with underscores
def normalize_name(string):
normalized_string = ''
stripped_string = string.strip()
if stripped_string[0].isdigit():
stripped_string = '_' + stripped_string
for letter in stripped_string:
if (letter.isalpha() or letter == '_') and not letter == ' ':
normalized_string += letter.lower()
elif letter.isdigit():
normalized_string += letter
elif letter == ' ':
normalized_string += '_'
return normalized_string
# In[3]:
#11 Write a function named cumulative_sum that accepts a list of
#numbers and returns a list that is the cumulative sum of the
#numbers in the list.
def cumulative_sum(lists):
cu_list = []
length = len(lists)
cu_list = [sum(lists[0:x:1]) for x in range(0, length + 1)]
return cu_list[1:]
cumulative_sum([1,5,10,56,99])
# In[ ]:
|
# Importing modules that are required.
import sympy as sp # Required for dictating the sub-shells with number of electrons.
from mendeleev import * # Required for synthesis of data from Periodic Table.
sp.init_printing()
# Taking the value from the user.
o = input('Enter the Symbol of element : ')
# Synthesising the Atomic Number from the symbol.
o = element(o)
z = o.atomic_number
# Declaring the Variables and Lists.
r = 0
e = z
n = 1
econ = list()
k = list()
# Creating a Nested Dictionary of Sub-shells.
c = {0: {'s': 2},
1: {'p': 6},
2: {'d': 10},
3: {'f': 14},
4: {'g': 18},
5: {'h': 22},
6: {'i': 26}}
# Inserting Frame Model for the Electrons Number to be entered later.
for n in range(1, 8):
for j in range(n):
a = n + j
sb = list(c[j].keys())
g = c[j][sb[0]]
k.append([a, n, sb[0], g])
# Sorting the list.
k.sort()
# Basic Calculation and Entering the data in the frame and making ready to be displayed.
for n in range(1, 8):
for j in range(n):
if e == 0:
break
elif len(k) == 0:
break
elif e < k[0][3]:
u = sp.symbols(k[0][2])
v = k[0][1] * u ** e
econ.append(v)
k.pop(0)
e = 0
break
elif len(k) == 1:
u = sp.symbols(k[0][2])
r = k[0][3]
v = k[0][1] * u ** k[0][3]
econ.append(v)
k.pop(0)
e = 0
break
else:
r = k[0][3]
u = sp.symbols(k[0][2])
v = k[0][1] * u ** k[0][3]
econ.append(v)
e -= k[0][3]
k.pop(0)
# Declaring Output for the Exceptions.
s = sp.symbols('s')
p = sp.symbols('p')
d = sp.symbols('d')
if z == 24:
econ = [s ** 2, 2 * s ** 2, 2 * p ** 6, 3 * s ** 2, 3 * p ** 6, 4 * s ** 1, 3 * d ** 5]
if z == 29:
econ = [s ** 2, 2 * s ** 2, 2 * p ** 6, 3 * s ** 2, 3 * p ** 6, 4 * s ** 1, 3 * d ** 10]
# Printing the Output.
print('Electronic Configuration of', z, ',', o.name, 'is : ', econ)
|
import time
# Given an array [10,9,8,7,6,5,4,3,2,1]
# Sort the array in Ascending order
def insertion_sort(arr: list):
start = time.time()
for i in range(1, len(arr)):
for j in range(0, i):
if arr[i] < arr[j]:
popped = arr.pop(i)
arr.insert(j, popped)
done = time.time() - start
print(arr)
print('{:f}'.format(done))
if __name__ == "__main__":
insertion_sort([10, 5, 3, 8, 2, 6, 4, 7, 9, 1])
|
class SplayTree(object):
"""Splay Tree object.
A splay tree is a self balancing binary search tree with operations that run
in O(log(n)) amortized time, where n is the number of entries in the tree.
This particular implementation uses a dictionary interface; it may be
extended to use a key only interface however.
Member Variables:
_size the number of entries in this splay tree.
_root the root of this tree; an empty tree has a value of None.
"""
def __init__(self):
"""Initialize an empty splay tree object."""
self._size = 0
self._root = None
def __len__(self):
"""Return the size(number of entries) of the splay tree."""
return self._size
def insert(self, key, value):
"""Insert an item into the splay tree, increasing its size.
Keys will be inserted in O(log(n)) amortized time and then splayed to the
root of the tree. Duplicates are **not** allowed in the sense that only
one copy of a key is allowed in the tree at a time. Further insertions
with that key will overwrite previous keys.
"""
if self._root:
node = self.binaryHelper(key,self._root)
if key == node.key: #Replace a duplicate key
node._key = key
node._value = value
return
elif key < node.key:
node.left = TreeNode(key,value,node)
node = node.left
elif key > node.key:
node.right = TreeNode(key,value,node)
node = node.right
self.splay(node)
else:
self._root = TreeNode(key,value)
self._size+=1
def insertHelper(self, key, node):
"""Insert an item into the splay tree given a node.
Recursive helper function that inserts keys into a binary tree. The node
that the key is inserted to is returned.
"""
if key < node.entry:
if node.left:
return self.insertHelper(key,node.left)
else:
node.left = TreeNode(key,parent=node)
return node
else:
if node.right:
return self.insertHelper(key,node.right)
else:
node.right = TreeNode(key,parent=node)
return node
def find(self, key):
"""Return the value that corresponds to the given key.
Search the tree for the given key and return its corresponding value in
O(log(n)) amortized time. If the key is not in this tree, return None.
The node that the search ends on is splayed to the root of the tree. No
duplicates are allowed in this implementation.
"""
if self._root:
node = self.binaryHelper(key,self._root)
self.splay(node) #Splay the found node to the root
if node.key == key:
return node.value
def __contains__(self, key):
"""Determine if a given key is within the tree. Wrapper for find().
This function returns false negatives if the entries in the tree are None.
"""
return (self.find(key) != None)
def remove(self, key):
"""Remove an item from the splay tree.
Given a key, it will be removed in O(log(n)) amortized time and its parent
will be splayed to the root of the tree. If the operation is successful,
the size of the tree will decrease be one and the value of the key will be
returned, otherwise, a value of None will be returned. Calling remove() on
a duplicate key will result in an arbitrary key being removed.
"""
if not self._root: #nothing to remove
return
remove = self.binaryHelper(key, self._root)
splayMe = None
#remove is not None
if remove.key != key: #node is not in the tree
splayMe = remove
elif remove is self._root:
assert not remove.parent
if not remove.left and not remove.right: #0 children
self._root = None
elif remove.left and not remove.right: #left child only
self._root = remove.left
remove.left.parent = None
remove.left = None
elif remove.right and not remove.left: #right child only
self._root = remove.right
remove.right.parent = None
remove.right = None
elif remove.right and remove.left: #both children
replace = self.minNode(remove.right)
assert replace
assert not replace.left
if replace is remove.right:
replace.left = remove.left
replace.left.parent = replace
remove.left = None
replace.parent = None
remove.right = None
self._root = replace
else:
assert replace.isLeftChild
replace.left = remove.left
replace.left.parent = replace
remove.left = None
if replace.right:
replace.right.parent = replace.parent
replace.parent.left = replace.right
else:
replace.parent.left = None
replace.parent = None
remove.right.parent = replace
replace.right = remove.right
remove.right = None
self._root = replace
else: #handle not root
assert remove.parent
if not remove.left and not remove.right: #0 children
if remove.isLeftChild:
remove.parent.left = None
elif remove.isRightChild:
remove.parent.right = None
splayMe = remove.parent
remove.parent = None
elif remove.left and not remove.right: #left child only
if remove.isLeftChild:
remove.parent.left = remove.left
remove.left.parent = remove.parent
remove.left = None
splayMe = remove.parent
remove.parent = None
elif remove.isRightChild:
remove.parent.right = remove.left
remove.left.parent = remove.parent
remove.left = None
splayMe = remove.parent
remove.parent = None
elif remove.right and not remove.left: #right child only
if remove.isLeftChild:
remove.parent.left = remove.right
remove.right.parent = remove.parent
remove.right = None
splayMe = remove.parent
remove.parent = None
elif remove.isRightChild:
remove.parent.right = remove.right
remove.right.parent = remove.parent
remove.right = None
splayMe = remove.parent
remove.parent = None
elif remove.left and remove.right: #both children
splayMe = replace = self.minNode(remove.right)
assert replace
assert not replace.left
if remove.isLeftChild:
if replace is remove.right:
replace.left = remove.left
replace.left.parent = replace
remove.left = None
remove.parent.left = replace
replace.parent = remove.parent
remove.parent = None
else:
assert replace.isLeftChild
replace.left = remove.left
replace.left.parent = replace
remove.left = None
if replace.right:
replace.parent.left = replace.right
replace.right.parent = replace.parent
else:
replace.parent.left = None
replace.right = remove.right
replace.right.parent = replace
remove.right = None
replace.parent = remove.parent
replace.parent.left = replace
remove.parent = None
elif remove.isRightChild:
if replace is remove.right:
replace.left = remove.left
replace.left.parent = replace
remove.left = None
remove.parent.right = replace
replace.parent = remove.parent
remove.parent = None
else:
assert replace.isLeftChild
replace.left = remove.left
replace.left.parent = replace
remove.left = None
if replace.right:
replace.right.parent = replace.parent
replace.parent.left = replace.right
else:
replace.parent.left = None
replace.right = remove.right
replace.right.parent = replace
remove.right = None
replace.parent = remove.parent
replace.parent.right = replace
remove.parent = None
self.splay(splayMe)
self._size -= 1
def _removeRoot():
"""Remove the root from the tree.
Helper function that removes the root from the tree and links up its
replacement.
The root either has one or both children, but no parent
"""
def _removeParented(remove):
"""Remove a node in the tree that has a parent.
Helper function given a node that has a parent, removes the node from the
tree regardless of how many children it has.
"""
#remove has a parent
#unknown what kind of child remove is
c = self.minNode(remove.right)
if not c: #no right child ; left child unknown
remove.parent
def minNode(self, node):
"""Return the node that contains the minimum key.
Helper function that returns the node with the minimum key in a tree given
the root of that tree. If the given node is None, return None.
"""
if not node or not node.left:
return node
return self.minNode(node.left)
def maxNode(self, node):
"""Return the node that contains the maximum key.
Helper function that returns the node with the maximum key in a tree given
the root of that tree.
"""
if not node or not node.right:
return node
return self.maxNode(node.right)
def binaryHelper(self, key, node):
"""Find a node that is *right* for the given key.
Helper function that returns the node that suits the key. If the key is not
currently in the tree, return the parent node. If the key is already in the
tree, return the node that contains it. This function returns None if the
given node is equal to None.
"""
if not node or key == node.key:
return node
elif key < node.key:
if node.left:
return self.binaryHelper(key,node.left)
else:
return node #Return the parent node
elif key > node.key:
if node.right:
return self.binaryHelper(key,node.right)
else:
return node
def splay(self, node):
"""Splay a node up to the root.
Mutate this splay tree so that the given node becomes the root of the tree.
There are three named cases:
zig-zig:
The node is a right child of a right child OR a left of a left.
In this case, rotate up through the parent, then through the grandparent.
zig-zag:
The node is a right child of a left child OR a left of a right.
In this case, rotate the parent up through the grandparent, then rotate
the node up through the parent.
zig(base-case):
The node is either a right child or a left child of the root. Rotate up.
When the given node is the root of the tree, stop recursion. If node is
None, return.
"""
if not node or node is self._root:
return
elif node.parent is self._root: #Zig
if node.isLeftChild:
return self.rotateRight(node)
elif node.isRightChild:
return self.rotateLeft(node)
#right left zig-zag
elif node.isRightChild and node.parent.isLeftChild:
self.rotateLeft(node)
self.rotateRight(node)
#left right zig-zag
elif node.isLeftChild and node.parent.isRightChild:
self.rotateRight(node)
self.rotateLeft(node)
#left zig-zig
elif node.isLeftChild and node.parent.isLeftChild:
self.rotateRight(node.parent)
self.rotateRight(node)
#right zig-zig
elif node.isRightChild and node.parent.isRightChild:
self.rotateLeft(node.parent)
self.rotateLeft(node)
return self.splay(node)#recurse
def rotateRight(self, node):
"""Rotate a given node right in the tree.
P n
/ \ rotateRight() / \
n ^ ------------> ^ P
/ \ /C\ /A\ / \
^ ^ ^ ^
/A\/B\ /B\/C\
>>> s = SplayTree()
>>> a = TreeNode(3,0)
>>> b = TreeNode(2,1)
>>> b.parent = a
>>> c = TreeNode(1,2)
>>> c.parent = b
>>> s._root = a
>>> s._root.left = b
>>> s._root.left.left = c
>>> s.rotateRight(b)
>>> s._root is b
True
>>> s._root.left is c
True
>>> s._root.right is a
True
"""
node.parent.left = node.right
if node.right:node.right.parent = node.parent
node.right = node.parent
node.parent = node.parent.parent
node.right.parent = node
if node.parent: #If node's new parent is not None
if node.parent.left is node.right:
node.parent.left = node
elif node.parent.right is node.right:
node.parent.right = node
else:
self._root = node
def rotateLeft(self, node):
"""Rotate a given node left in the tree.
P n
/ \ rotateLeft() / \
^ n ----------> P ^
/A\ / \ / \ /C\
^ ^ ^ ^
/B\/C\ /A\/B\
"""
node.parent.right = node.left
if node.left:node.left.parent = node.parent
node.left = node.parent
node.parent = node.parent.parent
node.left.parent = node
if node.parent: #If node's new parent is not None
if node.parent.left is node.left:
node.parent.left = node
elif node.parent.right is node.left:
node.parent.right = node
else:
self._root = node
def __str__(self):
"""Return the string representation of the tree.
Return a string representing the tree sideways.
Left nodes are below its parent, right above. Each level is indented with
two spaces.
"""
q = []
def traversalHelper(n, d=0):
if not n:
return
traversalHelper(n.right, d+1)
q.append((d, n))
traversalHelper(n.left, d+1)
traversalHelper(self._root)
return "".join(p[0]*" "+str(p[1].key)+":"+str(p[1].value)+"\n" for p in q)
class TreeNode(object):
"""Tree Node object.
A tree node is an entry within a binary tree that holds a key value pair.
Member Variables:
_key the key that this node contains. TreeNodes are searched by key.
_value the value that corresponds to the stored key.
parent the parent of this node.
left the left child node which has a key less than this node.
right the right child node which has a key less than this node.
"""
def __init__(self, key, value, parent=None, left=None, right=None):
"""Initialize a Tree Node object given certain values."""
self._key = key
self._value = value
self.parent = parent
self.left = left
self.right = right
@property
def key(self):
"""Return the key stored by this tree node."""
return self._key
@property
def value(self):
"""Return the value stored by this tree node."""
return self._value
@property
def isLeftChild(self):
"""Return whether this node is a left child."""
if self.parent:
return (self.parent).left is self
@property
def isRightChild(self):
"""Return whether this node is a right child."""
if self.parent:
return (self.parent).right is self
if __name__ == "__main__":
s = SplayTree()
from random import randint
r = set()
#s.splay = lambda a: None
for i in xrange(20):
a = randint(-10000, 10000)
r.add(a)
s.insert(a, True)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 23:03:25 2021
@author: andrewtuckman
"""
class Board:
""" a data type for a Connect Four board with arbitrary dimensions
"""
def __init__(self, height, width):
""" constructs a new Board object
inputs: two positive numbers for height and width
"""
self.height = height
self.width = width
self.slots = [[' '] * width for row in range(self.height)]
def __repr__(self):
""" Returns a string representation of a Board object.
"""
s = ''
for row in range(self.height):
s += '|'
for col in range(self.width):
s += self.slots[row][col] + '|'
s += '\n'
s += (2 * self.width + 1) * '-'
s += '\n'
s += ' '
for col in range(self.width):
if col > 9:
col = col % 10
s += str(col)
s += ' '
return s
def add_checker(self, checker, col):
assert(checker == 'X' or checker == 'O')
assert(col >= 0 and col < self.width)
row = -1
for i in range(self.height):
if self.slots[row][col] == ' ':
self.slots[row][col] = checker
break
else:
row -= 1
def reset(self):
""" reset the Board object on which it is called by setting all slots
to contain a space character
"""
for row in range(self.height):
for col in range(self.width):
self.slots[row][col] = ' '
def add_checkers(self, colnums):
""" takes a string of column numbers and places alternating
checkers in those columns of the called Board object,
starting with 'X'.
input: colnums is a string of valid column numbers
"""
checker = 'X' # start by playing 'X'
for col_str in colnums:
col = int(col_str)
if 0 <= col < self.width:
self.add_checker(checker, col)
if checker == 'X':
checker = 'O'
else:
checker = 'X'
def can_add_to(self, col):
""" returns True if it is valid to place a checker in the column col
on the calling Board object. Otherwise, it should return False
"""
if 0 > col or col > (self.width - 1):
return False
elif self.slots[0][col] == ' ':
return True
else:
return False
def is_full(self):
""" returns True if the called Board object is completely full of
checkers, and returns False otherwise
"""
for col in range(self.width):
if self.can_add_to(col):
return False
return True
def remove_checker(self, col):
""" removes the top checker from column col of the called Board
object. If the column is empty, then the method should do nothing
"""
for row in range(self.height):
if self.slots[row][col] != ' ':
self.slots[row][col] = ' '
break
def is_horizontal_win(self, checker):
""" Checks for a horizontal win for the specified checker.
"""
for row in range(self.height):
for col in range(self.width - 3):
if self.slots[row][col] == checker and \
self.slots[row][col + 1] == checker and \
self.slots[row][col + 2] == checker and \
self.slots[row][col + 3] == checker:
return True
return False
def is_vertical_win(self, checker):
""" Checks for a vertical win for the specified checker.
"""
for row in range(self.height-3):
for col in range(self.width):
if self.slots[row][col] == checker and \
self.slots[row+1][col] == checker and \
self.slots[row+2][col] == checker and \
self.slots[row+3][col] == checker:
return True
return False
def is_up_diagonal_win(self, checker):
""" Checks for a diagonal-up win for the specified checker
"""
for row in range(3,self.height):
for col in range(self.width-3):
if self.slots[row][col] == checker and \
self.slots[row-1][col+1] == checker and \
self.slots[row-2][col+2] == checker and \
self.slots[row-3][col+3] == checker:
return True
return False
def is_down_diagonal_win(self, checker):
""" Checks for a diagonal-down win for the specified checker
"""
for row in range(self.height-3):
for col in range(self.width-3):
if self.slots[row][col] == checker and \
self.slots[row+1][col+1] == checker and \
self.slots[row+2][col+2] == checker and \
self.slots[row+3][col+3] == checker:
return True
return False
def is_win_for(self, checker):
""" accepts a parameter checker that is either 'X' or 'O', and returns
True if there are four consecutive slots containing checker on the board.
Otherwise, returns False.
"""
assert(checker == 'X' or checker == 'O')
if self.is_down_diagonal_win(checker) == True:
return True
if self.is_up_diagonal_win(checker) == True:
return True
if self.is_vertical_win(checker) == True:
return True
if self.is_horizontal_win(checker) == True:
return True
return False
class Player:
def __init__(self, checker):
""" constructs a new Player object
"""
assert(checker == 'X' or checker == 'O')
self.checker = checker
def __repr__(self):
""" returns a string representing a Player object
"""
return 'Player ' + str(self.checker)
def opponent_checker(self):
""" returns a one-character string representing the checker of
the Player object’s opponent
"""
if self.checker == 'X':
return 'O'
else:
return 'X'
import random
import time
def connect_four(p1, p2, bet):
if p1.checker not in 'XO' or p2.checker not in 'XO' \
or p1.checker == p2.checker:
print('need one X player and one O player.')
return None
print('Welcome to Connect Four!', '\n')
b = Board(6, 7)
print(b)
while True:
if process_move(p1, b, bet) == True:
return b
if process_move(p2, b, bet) == True:
return b
def process_move(p, b, bet):
""" takes two parameters: a Player object p for the player whose move
is being processed, and a Board object b for the board on which the
game is being played.
It returns True if a win or a tie, and False otherwise
"""
global coordinates
nxt_move = p.next_move(b)
b.add_checker(p.checker, nxt_move)
#time.sleep(.6)
print(b)
for x in range(len(b.slots)):
for y in range(len(b.slots[0])):
if b.slots[x][y]!=' ' and [x,y] not in coordinates:
coordinates +=[[x,y]]
print(coordinates)
if b.is_win_for(p.checker):
print(str(p.checker), ' wins.')
if (p.checker == bet):
global bet_validity
bet_validity = True
print('Congratulations! You bet correctly!')
else:
print('You idiot, you guessed wrong.')
return True
elif b.is_full():
print('\n' + "It's a tie!")
return True
else:
return False
class AIPlayer(Player):
""" creates a more “intelligent” computer player – one that uses
techniques from artificial intelligence (AI) to choose its next move
"""
def __init__(self, checker, tiebreak, lookahead):
""" constructs a new AIPlayer object
"""
assert(checker == 'X' or checker == 'O')
assert(tiebreak == 'LEFT' or tiebreak == 'RIGHT' or tiebreak == 'RANDOM')
assert(lookahead >= 0)
super().__init__(checker)
self.tiebreak = tiebreak
self.lookahead = lookahead
def __repr__(self):
""" returns a string representing an AIPlayer object
"""
return 'Player ' + str(self.checker) + ' (' + str(self.tiebreak) \
+ ', ' + str(self.lookahead) + ')'
def max_score_column(self, scores):
""" takes a list scores containing a score for each column of the
board, and that returns the index of the column with the maximum
score
"""
max_scores = []
for i in range(len(scores)):
if scores[i] == max(scores):
max_scores += [i]
if self.tiebreak == 'LEFT':
return max_scores[0]
if self.tiebreak == 'RIGHT':
return max_scores[-1]
if self.tiebreak == 'RANDOM':
return random.choice(max_scores)
def scores_for(self, b):
""" takes a Board object b and determines the called AIPlayer‘s
scores for the columns in b
"""
scores = [10] * len(range(b.width))
for col in range(b.width):
if not b.can_add_to(col):
scores[col] = -1
elif b.is_win_for(self.checker):
scores[col] = 100
elif b.is_win_for(self.opponent_checker()):
scores[col] = 0
elif self.lookahead == 0:
scores[col] = 50
else:
b.add_checker(self.checker, col)
opponent = AIPlayer(self.opponent_checker(), self.tiebreak, self.lookahead - 1)
opp_scores = opponent.scores_for(b)
if max(opp_scores) == 0:
scores[col] = 100
elif max(opp_scores) == 100:
scores[col] = 0
elif max(opp_scores) == 50:
scores[col] = 50
b.remove_checker(col)
return scores
def next_move(self, b):
""" return the called AIPlayer‘s judgment of its best possible move
"""
scores = self.scores_for(b)
return self.max_score_column(scores)
bet = input("Which player do you think will win?: ")
bet_validity = False
coordinates = []
p1 = AIPlayer('X', 'RANDOM', 2)
p2 = AIPlayer('O', 'RANDOM', 2)
connect_four(p1, p2, bet)
print(coordinates)
|
# BOJ 1922 네트워크 연결
def find_set(x):
if parent[x] < 0:
return x
parent[x] = find_set(parent[x])
return parent[x]
def union(x, y):
x = find_set(x)
y = find_set(y)
if x < y:
parent[x] += parent[y]
parent[y] = x
else:
parent[y] += parent[x]
parent[x] = y
return
def kruskal():
MST = []
result = 0
count = 0
for m in range(M):
a, b, c = route[m]
if find_set(a) == find_set(b):
continue
result += c
MST.append(route[m])
union(a, b)
count += 1
if count == N - 1:
break
return result
N = int(input())
M = int(input())
route = []
for m in range(M):
a, b, c = map(int, input().split())
route.append([a, b, c])
route.sort(key=lambda x: x[2])
parent = [0] + [-1] * N
print(kruskal()) |
# BOJ 1197 최소 스패닝 트리
def find_set(x):
if parent[x] < 0:
return x
parent[x] = find_set(parent[x])
return parent[x]
def union(x, y):
x = find_set(x)
y = find_set(y)
if x < y:
parent[x] += parent[y]
parent[y] = x
else:
parent[y] += parent[x]
parent[x] = y
return
def kruskal():
MST = []
result = 0
count = 0
for e in range(E):
w, x, y = edge[e]
if find_set(x) == find_set(y) and find_set(x) > 0:
continue
result += w
MST.append(edge[e])
union(x, y)
count += 1
if count == V - 1:
break
return result
V, E = map(int, input().split())
edge = []
for e in range(E):
a, b, w = map(int, input().split())
edge.append([w, a, b])
edge.sort(key=lambda x: x[0])
parent = [0] + [-1] * V
print(kruskal()) |
# BOJ 1978 소수 찾기
def is_prime(number):
if number == 1:
return False
i = 2
while i * i <= number:
if number % i == 0:
return False
i += 1
return True
N = int(input())
numbers = list(map(int, input().split()))
numbers.sort(reverse=True)
prime = []
for i in range(1, numbers[0] + 1):
if is_prime(i):
prime.append(i)
count = 0
for i in numbers:
if i in prime:
count += 1
print(count) |
# BOJ 6497 전력난_kruskal
def find_parent(x):
if parent[x] < 0:
return x
parent[x] = find_parent(parent[x])
return parent[x]
def union(x, y):
x = find_parent(x)
y = find_parent(y)
if x == y:
return
if x < y:
parent[x] += parent[y]
parent[y] = x
return
else:
parent[y] += parent[x]
parent[x] = y
return
def kruskal():
result = 0
count = 0
for route in routes:
w, x, y = route
if find_parent(x) == find_parent(y):
continue
result += w
count += 1
union(x, y)
if count == M - 1:
break
return result
while True:
M, N = map(int, input().split())
if M == 0:
break
routes = []
before = 0
for n in range(N):
x, y, z = map(int, input().split())
routes.append([z, x, y])
before += z
routes.sort(key=lambda x: x[0])
parent = [-1] * N
print(before - kruskal()) |
from Tkinter import *
m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
left = Label(m1 , text = "left pane")
m1.add(left)
m2 = PanedWindow(m1, orient = VERTICAL)
m1.add(m2)
top = Label(m2,text = "top pane")
m2.add(top)
bottom = Label(m2,text="bottom pane")
m2.add(bottom)
mainloop()
|
# First and last occurrences of X
"""
Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.
Note: If the number x is not found in the array just print '-1'.
Input:
The first line consists of an integer T i.e number of test cases. The first line of each test case contains two integers n and x. The second line contains n spaced integers.
Output:
Print index of the first and last occurrences of the number x with a space in between.
Constraints:
1<=T<=100
1<=n,a[i]<=1000
Example:
Input:
2
9 5
1 3 5 5 5 5 67 123 125
9 7
1 3 5 5 5 5 7 123 125
Output:
2 5
6 6
"""
def getFirstIndex(arr, x, n):
lowest = -1
l, h = 0, n - 1
while l <= h:
mid = (l + h) >> 1
if arr[mid] == x:
lowest = mid
h = mid - 1
elif x < arr[mid]:
h = mid - 1
else:
l = mid + 1
return lowest
def getLastIndex(arr, x, n):
highest = -1
l, h = 0, n - 1
while l <= h:
mid = (l + h) >> 1
if arr[mid] == x:
highest = mid
l = mid + 1
elif x < arr[mid]:
h = mid - 1
else:
l = mid + 1
return highest
t = int(input().strip())
for _ in range(t):
n, x = [int(x) for x in input().strip().split()]
arr = [int(x) for x in input().strip().split()]
fi = getFirstIndex(arr, x, n)
li = getLastIndex(arr, x, n)
if fi == -1 and li == -1:
print(-1)
else:
print(fi, li)
|
import turtle
def drawSpiral(t, length, color):
if length != 0:
newcolor = (int(color[1:],16) + 2**20)%(2**24)
newcolor = hex(newcolor)[2:]
newcolor = "#"+("0"*(6-len(newcolor)))+newcolor
t.color(newcolor)
t.forward(length)
t.left(200)
drawSpiral(t, length - 1, newcolor)
def main():
t = turtle.Turtle()
screen = t.getscreen()
t.speed(100)
t.penup()
t.goto(-100,0)
t.pendown()
drawSpiral(t, 200, "#A52A2A")
drawSpiral(t, 300, "#A52A2A")
screen.exitonclick()
main()
|
import binascii
import hashlib
import os
import sqlite3
import string
import smtplib
import ssl
import uuid
from random import choice, randint
import yaml
from DBInfo import DBInfo
from weight import Weight
def create_connection(db_file):
"""
Create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Exception as e:
print(e)
return conn
def create_table(conn, create_table_sql):
"""
Create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Exception as e:
print(e)
create_commands = """ CREATE TABLE IF NOT EXISTS Accounts (
id integer PRIMARY KEY,
name text NOT NULL,
surname text NOT NULL,
username text NOT NULL UNIQUE,
salt text NOT NULL,
pwd text NOT NULL UNIQUE,
email text NOT NULL UNIQUE,
height real,
weight real,
state text NOT NULL,
uID text UNIQUE
); """
arg = """ INSERT INTO Accounts (name, surname, username, salt, pwd, email, height, weight, state, uID)
VALUES(?,?,?,?,?,?,?,?,?,?)"""
def get_random_string(length):
"""
Create a random string
:param length: length of the string
:return: a random string
"""
letters = string.ascii_lowercase
result_str = ''.join(choice(letters) for i in range(length))
return result_str
def hash_password(password):
"""
Hash a password for storing.
:param password: plain text password
:return: an array in which the first 64 elements represent the salt, and the second represent the hashed pwd itself
"""
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'),
salt, 100000)
pwdhash = binascii.hexlify(pwdhash)
return (salt + pwdhash).decode('ascii')
class Account():
"""
Main class for now
"""
def __init__(self, name=None, surname=None, username=None, passwd=None, email=None, height=None, weight=None,
state='metric'):
"""
Constructor for a first time user if username is given, or an empty constructor otherwise
:param name: name
:param surname: surname
:param username: username -REQUIRED FOR A NEW USER @TODO: add name, surname and email to required parameters
:param email: email
:param height: height @TODO: add a height class for imperial/metric conversion on the fly
:param weight: weight Class already implemented, @TODO: Test thoroughly
:param state: metric/imperial measurement standard @TODO: Rename/Refactor to something more descriptive
@TODO: Reorganize the code into smaller, more readable parts
@TODO: Detailed comments
"""
if username is not None:
self.name = name
self.surname = surname
self.username = username
self.uID = uuid.uuid4()
self.email = email
if len(passwd) < 8:
raise Exception("Password too short. Minimum length is 8 characters")
pwd = hash_password(passwd)
salt = pwd[:64]
stPwd = pwd[64:]
self.DBInfo = DBInfo(uID=self.uID)
conn = create_connection("Acc.db")
create_table(conn, create_commands)
cur = conn.cursor()
cur.execute(arg, (name, surname, username, salt, stPwd, email, height, weight, state, str(self.uID)))
conn.commit()
if height is None:
self.height = -1
else:
self.height = height
if weight is None:
self.weight = None
else:
self.weight = Weight(weight, state=state)
def logIn(self, username, pwd):
"""
Logs in a user
:param username: username
:param pwd: password
:return: None @TODO: Maybe return True/False?
(Exceptions implemented, don't think it's worth doing)
@TODO: Detailed comments
"""
conn = create_connection("Acc.db")
cur = conn.cursor()
try:
cur.execute("SELECT * FROM Accounts WHERE Accounts.username=?", (username,))
except sqlite3.OperationalError:
raise Exception("User doesn't exist")
rows = cur.fetchall()
for row in rows:
salt = row[4]
stPwd = row[5]
pwdhash = hashlib.pbkdf2_hmac('sha512', pwd.encode('utf-8'), salt.encode('ascii'), 100000)
pwdhash = binascii.hexlify(pwdhash).decode('ascii')
print()
if pwdhash != stPwd:
raise Exception("Invalid password")
self.name = row[1]
self.surname = row[2]
self.username = row[3]
self.email = row[6]
self.height = row[7]
self.weight = Weight(row[8], row[9])
self.uID = row[10]
self.DBInfo = DBInfo(self.uID)
def __repr__(self):
"""
String representation of the Account class
:return: Returns the uID for now @TODO: A nice log for the developer maybe
"""
return str(self.uID)
def measure(self, wght):
"""
Measure current body mass
:param wght: New mass in preferred unit @TODO: Test with different standard
:return: None
"""
self.weight.set(wght)
self.DBInfo.add(wght)
@staticmethod
def resetPassword(email):
"""
STATIC METHOD
Resets the password for the given email after verification
:param email: email
:return:
@TODO: Improve the email server/gmail account handling (NO HARDCODED PASSWORDS)
@TODO: Detailed comments
"""
port = 465 # For SSL
# Create a secure SSL context
context = ssl.create_default_context()
strchk = get_random_string(randint(5, 10))
"""
FOR THIS TO WORK YOU HAVE TO CREATE THE FILE IN conf/application.yml in this format:
user:
email: YOUR@MAIL.COM
password: YOURPASSWORD
"""
conf = yaml.safe_load(open('conf/application.yml'))
senderemail = conf['user']['email']
senderpwd = conf['user']['password']
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(senderemail, senderpwd)
server.sendmail("wfaccloss@gmail.com", email, "Subject: Password recovery string: \n\n" + strchk)
chckinput = input("Input the code that was sent to your email: ")
if strchk == chckinput:
newpwd = input("Enter your new password: ")
if len(newpwd) < 8:
raise Exception("Password too short. Minimum length is 8 characters")
pwd = hash_password(newpwd)
salt = pwd[:64]
stPwd = pwd[64:]
conn = create_connection("Acc.db")
create_table(conn, create_commands)
cur = conn.cursor()
cur.execute("UPDATE Accounts SET salt = ?, pwd = ? WHERE email = ?", (salt, stPwd, email))
conn.commit()
cur.close()
else:
raise Exception("Wrong recovery code")
def resetEmail(self, newmail):
"""
Resets the email
:param newmail: New email
:return: None
@TODO: Confirmation of email
"""
conn = create_connection("Acc.db")
create_table(conn, create_commands)
cur = conn.cursor()
cur.execute("UPDATE Accounts set email = ? WHERE username = ?", (newmail, self.username))
conn.commit()
cur.close()
def display(self):
"""
Displays the collected data in a chart
:return: None
@TODO: Implement this in the GUI
@TODO: Different types of charts?
@TODO: Detailed comments
"""
import matplotlib.pyplot as plt
wghts = self.DBInfo.allWeights()
w = []
for i in wghts:
w.append(i[0])
print(i)
dates = self.DBInfo.allDates()
k = []
import numpy as np
for i in dates:
k.append(i[0])
# i = i[0].split()
# k.append(i[1][3:])
print(type(i))
print(k)
plt.plot(k, w, linestyle='-', linewidth=1, color='red')
plt.title(self.username)
# plt.xticks(np.arange(0, 60, step=5))
plt.show()
# @TODO: Username is already taken error
# @TODO: Confirmation of email when registering
# @TODO: Email confirmation when changing email
# @TODO: Variable height
# @TODO: BIG ONE GUI
# @TODO: Overall more detailed comments
# @TODO: Better exception handling
# @TODO: DJANGO vs Remi vs offline only
'''Far future todos'''
# @TODO: Add a table with nutrients?
# @TODO: Connection with MyFitnessPal
# @TODO: Connection with Mi API
|
from collections import defaultdict
from collections import Counter
sequenceString = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"
class Sequence:
def __init__(self, seq):
self.sequence = seq
class SequenceCountService:
def __init__(self, sequence):
if not isinstance(sequence, Sequence):
print("sequence object is not instance of Sequence")
else:
self.sequence = sequence
def calculate(self):
pass
class DefaultDicSequenceCountService(SequenceCountService):
def calculate(self):
elementsCount = defaultdict(int)
sequenceObject = self.sequence
for c in sequenceObject.sequence:
elementsCount[c] += 1
print("DefaultDicSequenceCountService count = " + str(elementsCount))
class CounterSequenceCountService(SequenceCountService):
def calculate(self):
sequenceObject = self.sequence
print("CounterSequenceCountService count = " + str(Counter(sequenceObject.sequence)))
def main():
seqObject = Sequence(sequenceString)
services = [DefaultDicSequenceCountService(seqObject), CounterSequenceCountService(seqObject)]
for impl in services:
impl.calculate()
if __name__ == "__main__":
main()
|
from collections import defaultdict
from collections import Counter
seq = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"
#print(len(seq))
class Sequence:
def __init__(self, seq):
self.seq = seq
def calc(self):
pass
seq2 = Sequence(seq)
class SequenceCountService:
def __init__(self, sequence):
if not isinstance(sequence, Sequence):
print('Error')
else:
self.sequence = sequence
def calc(self):
pass
class DefSequenceCountService(SequenceCountService):
def calc(self):
defDic = defaultdict(int)
for c in self.sequence.seq:
defDic[c] += 1
print(defDic)
class CounterSequenceCountService(SequenceCountService):
def calc(self):
print(Counter(self.sequence.seq))
def main():
service = DefSequenceCountService(seq2)
service.calc()
service2 = CounterSequenceCountService(seq2)
service2.calc()
arr = [service, service2]
for tt in arr:
tt.calc()
def main1():
print(seq)
countElem = {}
for c in seq:
if not countElem.get(c):
countElem[c] = 1
else:
countElem[c] += 1
print(countElem)
defDic = defaultdict(int)
for c in seq:
defDic[c] += 1
print(defDic)
print(Counter(seq))
if __name__ == "__main__":
main() |
def reverseString(str_data):
return str_data[::-1]
def reverseString2(str_data):
stack = []
for ch in str_data:
stack.append(ch)
result = ""
while len(stack) > 0:
result += stack.pop()
return result
print(reverseString2("asdbqwe1234")) |
#!/usr/bin/env python
from functools import wraps
from datetime import datetime as DateTime
def print_name( old_func ):
@wraps(old_func)
def new_func( *args, **kwargs ):
print " ==> Calling function {0} at {1}".format(old_func.__name__, DateTime.now())
return old_func( *args, **kwargs ) # call the 'real' function
return new_func # return the new function object
@print_name
def hello( greeting, whom ):
print "%s, %s" % ( greeting, whom )
@print_name
def goodbye():
print "Goodbye!"
hello('hello','world')
hello('hi','Earth')
goodbye()
goodbye()
print
print goodbye.__name__ |
#!/usr/bin/env python
presidents = []
with open('../DATA/presidents.txt') as PRES:
for line in PRES:
fields = line.split(':')
last_name = fields[1]
first_name = fields[2]
presidents.append(first_name + ' ' + last_name)
pres_upper = [ p.upper() for p in presidents ]
for pres in pres_upper:
print pres
|
#!/usr/bin/env python
class AddProperty(object):
def __init__(self, property_name, **kw):
'''Add one property to a class.
fixed parameter:
property_name->str or unicode Name of the property
keyword parameters:
readwrite->Boolean Whether the property is writable
value->object Initial value of property
self._property_name = property_name
self._is_readwrite = kw.get('readwrite', False)
self._value = kw.get('value', None)
'''
self._property_name = property_name
self._is_readwrite = kw.get('readwrite', False)
self._value = kw.get('value')
def __call__(self, old_class):
private_name = '_' + self._property_name.lower()
get_function = lambda self_: getattr(self_, private_name)
get_method = property(get_function)
setattr(old_class, self._property_name, get_method )
setattr(old_class, private_name, self._value)
if self._is_readwrite:
def set_function(self, new_value):
setattr(self, private_name, new_value)
set_method = get_method.setter(set_function)
setattr(old_class, self._property_name, set_method)
return old_class # return the original class
if __name__ == '__main__':
@AddProperty('Spam', value='Fried')
@AddProperty('Eggs', value='Poached', readwrite=True)
class Breakfast(object):
'''"empty" class'''
pass
b = Breakfast()
print 'b.Spam:', b.Spam
print 'b.Eggs:', b.Eggs
b.Eggs = 'Scrambled'
print 'b.Eggs:', b.Eggs
print type(b.Spam)
print type(b.Eggs)
print type(Breakfast.Spam)
print
print dir(b) |
#!/usr/bin/env python
from datetime import datetime as DateTime
class PrintName(object):
def __init__(self, old_function):
self._old_function = old_function
self.__name__ = self._old_function.__name__
def __call__( self, *args, **kwargs ):
print " ==> Calling function {0} at {1}".format(self._old_function.__name__, DateTime.now())
return self._old_function( *args, **kwargs )
@PrintName
def hello( greeting, whom ):
print "%s, %s" % ( greeting, whom )
@PrintName
def goodbye():
print "Goodbye!"
hello('hello','world')
hello('hi','Earth')
goodbye()
goodbye()
print
print goodbye.__name__ |
#!/usr/bin/env python
# (c)2014 John Strickler
people = [
[ 'Ann', 'Whittier', 'TX' ],
[ 'Raul', 'Rodriguez', 'NV' ],
[ 'Jim', 'Benson', 'VA' ],
[ 'Srini', 'Singh', 'IL' ],
]
for p in people:
print p[0], p[2]
print
for first_name, last_name, state in people:
print first_name, state
|
#!/usr/bin/env python
def pres_upper():
with open('../DATA/presidents.txt') as PRES:
for line in PRES:
# trim line, make it upper case, split on ':',
# then grab fields 1 through 2
lname, fname = line[:-1].upper().split(':')[1:3]
# yield (return) "Firstname Lastname"
yield '{0} {1}'.format(fname,lname)
for pres in pres_upper():
print pres
|
#!/usr/bin/env python
LIMIT=99
if len(sys.argv) > 1:
limit = int(sys.argv[1])
values = [ True for val in range(LIMIT+1) ]
primes = []
#print list(enumerate(values))
for addr in range(2, LIMIT+1):
if values[addr]:
primes.append(addr)
for val in xrange(2*addr, LIMIT+1, addr):
values[val] = False
print primes
|
#!/usr/bin/env python
import re
# sum the squares of a list of numbers
# using list comprehension, entire list is stored in memory
s1 = sum([x*x for x in range(10)])
# only one square is in memory at a time with generator expression
s2 = sum(x*x for x in range(10))
print s1,s2
print
# set constructor -- does not put all words in memory
pg = open("../DATA/mary.txt")
s = set(word.lower() for line in pg for word in re.split(r'\W+',line))
pg.close()
print s
print
keylist = ['OWL','Badger','bushbaby','Tiger','GORILLA','AARDVARK']
# dictionary constructor
d = dict( (k.lower(),k) for k in keylist)
print d
print
with open("../DATA/mary.txt") as MARY:
m = max(len(line) for line in MARY if line.strip())
print "Maximum line length:", m
|
#!/usr/bin/env python
FRUITS = ['watermelon', 'apple', 'kiwi', 'lime', 'orange', 'cherry',
'banana', 'raspberry', 'grape', 'lemon', 'durian', 'guava', 'mango',
'papaya', 'mangosteen', 'breadfruit']
KV_SEQ = ('red', 5, 'blue', 3, 'yellow', 7, 'purple', 2, 'pink', 8)
EVEN_SLICE = slice(0, None, 2) # even elements
ODD_SLICE = slice(1, None, 2) # odd elements
def main():
basic_slices()
print
convert_iterable_to_dictionary()
convert_iterable_to_dictionary_briefer()
def basic_slices():
s = slice(5) # first 5
print FRUITS[s]
print
s = slice(-5,None) # last 5
print FRUITS[s]
print
s = slice(3,8) # 4th through 8th
print FRUITS[s]
print
s = slice(None,None,2) # every other fruit starting with element 0
print FRUITS[s]
def convert_iterable_to_dictionary():
'''build a dictionary from an iterable in k1,v1,k2,v2 order'''
keys = KV_SEQ[EVEN_SLICE]
values = KV_SEQ[ODD_SLICE]
kv_tuples = zip(keys, values) # generates key/value pairs as tuples
print "kv_tuples:", kv_tuples
color_dict = dict(kv_tuples) # initialize a dictionary from key/value pairs
print "color_dict:", color_dict
def convert_iterable_to_dictionary_briefer():
'''Same, but without intermediate variables'''
color_dict = dict(zip(KV_SEQ[EVEN_SLICE],KV_SEQ[ODD_SLICE]))
print "color_dict:", color_dict
if __name__ == '__main__':
main() |
# coding: utf-8
# # Exercise Sheet 11 (Bonus)- MLP
# Yiping Deng, Shalom-David Anifowoshe
# In[36]:
# initialize numpy enviroment
get_ipython().magic(u'matplotlib notebook')
import numpy as np
from numpy import square
import matplotlib.pyplot as plt
# In[2]:
# Code for visualizing MLP structure
def draw_neural_net(ax, left, right, bottom, top, layer_sizes):
'''
Draw a neural network cartoon using matplotilb.
:usage:
>>> fig = plt.figure(figsize=(12, 12))
>>> draw_neural_net(fig.gca(), .1, .9, .1, .9, [4, 7, 2])
:parameters:
- ax : matplotlib.axes.AxesSubplot
The axes on which to plot the cartoon (get e.g. by plt.gca())
- left : float
The center of the leftmost node(s) will be placed here
- right : float
The center of the rightmost node(s) will be placed here
- bottom : float
The center of the bottommost node(s) will be placed here
- top : float
The center of the topmost node(s) will be placed here
- layer_sizes : list of int
List of layer sizes, including input and output dimensionality
'''
n_layers = len(layer_sizes)
v_spacing = (top - bottom)/float(max(layer_sizes))
h_spacing = (right - left)/float(len(layer_sizes) - 1)
# Nodes
for n, layer_size in enumerate(layer_sizes):
layer_top = v_spacing*(layer_size - 1)/2. + (top + bottom)/2.
for m in range(layer_size):
circle = plt.Circle((n*h_spacing + left, layer_top - m*v_spacing), v_spacing/4.,
color='w', ec='k', zorder=4)
ax.add_artist(circle)
# Edges
for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
layer_top_a = v_spacing*(layer_size_a - 1)/2. + (top + bottom)/2.
layer_top_b = v_spacing*(layer_size_b - 1)/2. + (top + bottom)/2.
for m in range(layer_size_a):
for o in range(layer_size_b):
line = plt.Line2D([n*h_spacing + left, (n + 1)*h_spacing + left],
[layer_top_a - m*v_spacing, layer_top_b - o*v_spacing], c='k')
ax.add_artist(line)
# ## Structure of the Multiple Layer Perceptron
# We use the classic structure of Multiple Layer Perceptron, with
#
# 1. Input Layer: 2 input neurons and 1 bias unit
# 2. One Hidden Layer: 2 hidden neurons with 1 bias Unit
# 3. Output Layer: 1 output neurons
#
# ### Bias unit
# Bias unit guarantees that it is a affine combination of previous layer inside of the neuron, increasing the model flexibility of each neurons.
#
#
# The following is the visualization of the MLP ( note that bias unit is emitted)
# In[3]:
mlp_fig = plt.figure(figsize=(6, 6))
draw_neural_net(mlp_fig.gca(), .2, .8, .1, .9, [2, 2, 1])
# ## Implementation of the MLP
# Firstly, let's define the necessary activation function $\sigma$ and the quadratic loss function
# In[4]:
def sigmoid(x):
"""Sigmoid Function
Input: A vector in any dimension
Output: Applying Sigmoid function elementwise
"""
exp_part = np.exp(-x)
return 1 / (1 + exp_part)
def sigmoid_grad(x):
"""Gradient of the sigmoid function
Input: A vector in any dimension
Output: Calculate Gradient of Sigmoid function elementwise
"""
sig = sigmoid(x)
return np.multiply(sig, 1 - sig)
def loss(y_pred, y):
diff = y_pred - y
np.sum(np.square(diff))
def mean_square_error(y_pred, y):
m, n = y_pred.shape
l = loss(y_pred, y)
return l / m / n
# The Gradient of the Sigmoid function is calculated using the following formula:
# $$ \sigma'(x) = \sigma(x) \cdot (1 - \sigma(x)) $$
# Given two weight matrix $W_1, W_2$, representing the weight from the input layer to the hidden layer and from the hiddden layer to the output layer, including the bias term, we can conclude that $W_1 \in \mathbb{R}^{2 \times 3}$ and $W_2 \in \mathbb{R}^{1 \times 3}$.
#
# ## Forward Propagation
# Our Entire Neural Network can be represent as a single function:
# $$ N: \mathbb{R}^2 \to \mathbb{R} $$
# Such function will:
# 1. Assiciate the input $X \in \mathbb{R}^2$ with a bias term, forming $X_{biased}$
# 2. Calculate the offine combination
# $$ z_2 = W_1 \cdot X_{biased} $$, where $z_2 \in \mathbb{R}^2$
# 3. Apply the Sigmoid function, obtaining the value of the neurons
# $$ a_2 = \sigma(z_2) $$, where $a_2 \in \mathbb{R}^2$
# 4. Assiciate $a_2$ with a bias term
# 5. Calculate the affine combination and return
# $$ z_3 = W_2 \cdot a_2 $$, where $z_3 \in \mathbb{R}$
# 6. Calculate $a_3 = \sigma(z_3)$. Note that in the lecture note, we do not apply sigmoid function for the last layer.
# However, we applied sigmoid here because we want the result to be in the inteval $[0,1]$ instead of $\mathbb{R}$
# In[5]:
def neural_net(X, W1, W2):
"""Implementation of the MLP
Input: takes input data X in 2 dimension, 2 weight matrix
"""
# bias term
X_b = np.ones((3,1))
X_b[1:] = X
a_1 = X_b
# calculate z_2
z_2 = np.matmul(W1, a_1)
# calculate a_2
a_2 = sigmoid(z_2)
# associate with bias
b_2 = np.ones((3, 1))
b_2[1:] = a_2
a_2 = b_2
# calculate z_3
z_3 = np.matmul(W2, a_2)
# calculate a_3
a_3 = sigmoid(z_3)
return a_3[0][0]
# ## Calculate the gradient with respect to $W_1$ and $W_2$ using Backpropagation
# We are using backpropagation to train $W^{(1)}$ and $W^{(2)}$
#
# First, perform a full forward propagation of the neural network to obtain
# $a_1, a_2, a_3, z_2, z_3$
#
# Second, calculate
# $$ \delta^{(3)} = a_k^{(3)} - y_k $$
# $$ \delta^{(2)} = W_2' \delta^{(3)}.*\sigma'(z^{(2)}) $$
#
# Finally, calculate the gradient at layer $l$ using
# \begin{equation}
# \frac{\partial}{\partial W_{ij}^{(l)}} = \delta^{(l + 1)} \cdot (a^{(l)})'
# \end{equation}
# In[6]:
def neural_net_train(X, W1, W2, Y):
"""Implementation of the MLP
Input: takes input data X in 2 dimension, 2 weight matrix, y
Output:
"""
# bias term
X_b = np.ones((3,1))
X_b[1:] = X
a_1 = X_b
# calculate z_2
z_2 = np.matmul(W1, a_1)
# calculate a_2
a_2 = sigmoid(z_2)
# associate with bias
b_2 = np.ones((3, 1))
b_2[1:] = a_2
a_2 = b_2
# calculate z_3
z_3 = np.matmul(W2, a_2)
a_3 = sigmoid(z_3)
# forward propagation end
# -----------------------
# start of backpropagation
# delta 3 in 1 x 1
delta_3 = a_3 - Y
# delta 2 in 2 x 1
delta_2 = np.multiply(np.matmul(W2.T, delta_3)[1:], sigmoid_grad(z_2))
# we don't have delta 1
grad_w_1 = np.matmul(delta_2, a_1.T)
grad_w_2 = np.matmul(delta_3, a_2.T)
# grad_w_2 = np.matmul(delta_3.T, a_2)
return a_3, grad_w_1, grad_w_2# grad_w_2
# ## Dealing with Multiple training data at the same time
# The gradient formula is averaged. Namely
# $$\frac{\partial}{\partial W_{ij}^{(l)}} = \frac{1}{m} \sum_{i = 1}^{m} \delta_{(i)}^{(l + 1)} \cdot (a_{(i)}^{(l)})' $$
# In[7]:
# accumulate the gradient result
def batch_neural_net_train(X, W1, W2, Y):
# X contains m training examples as row vectors
# X is m x 3
m, _ = X.shape
grad_w_1_acc = np.zeros((2,3))
grad_w_2_acc = np.zeros((1,3))
pred_all = np.zeros((m, 1))
for i in range(m):
pred, grad_w_1, grad_w_2 = neural_net_train(np.asmatrix(X[i]).T, W1, W2, np.asmatrix(Y[i]))
grad_w_1_acc = grad_w_1_acc - grad_w_1
grad_w_2_acc = grad_w_2_acc - grad_w_2
pred_all[i] = pred[0][0]
error = np.sum(np.square(pred_all - Y)) / m
return pred_all, grad_w_1_acc / m, grad_w_2_acc / m, error
# ## Gradient Decent
# We optimize our weight using gradient decent.
# We update the weight using the following formula:
# $$ W_{ij}^{(l)} = W_{ij}^{(l)} - \alpha * \frac{\partial}{\partial W_{ij}^{(l)}} $$
# In[8]:
def train(X, Y, step = 2000, alpha = 4.0):
# initiate w_1, w_2
w_1 = np.random.randn(2,3)
w_2 = np.random.randn(1, 3)
# train
for i in range(step):
pred, grad_w_1, grad_w_2, err = batch_neural_net_train(X, w_1, w_2, Y)
w_1_new = w_1 + alpha * grad_w_1
w_2_new = w_2 + alpha * grad_w_2
w_1 = w_1_new
w_2 = w_2_new
print('step: {} - error: {}'.format(i, err))
return w_1, w_2
# We explicitly print the training error, and after the experiment, we find the optimal $\alpha = 4.0$ and $step = 2000$
# In[9]:
# build up a training data
X = np.asmatrix([[1,1], [1,0], [0,1], [0, 0]])
Y = np.asmatrix([[0], [1], [1], [0]])
# train the neural network
w_1, w_2 = train(X, Y)
# The prediction is just performing the forward propagation algorithms.
# In[10]:
def predict(X, w_1, w_2):
m, _ = X.shape
pred = np.zeros((m, 1))
for i in range(m):
if neural_net(np.asmatrix(X[i]).T, w_1, w_2) > 0.5:
pred[i][0] = 1
else:
pred[i][0] = 0
return pred
# In[11]:
predict(X, w_1, w_2)
# # Bonus Question
# We use the same neural network architecture. However, we give a different training set for the neural network.
#
# ## Understanding $Sign$ function
# \begin{equation}
# Sign(x) =
# \begin{cases}
# -1 & x < 0 \\
# 0 & x = 0 \\
# 1 & x > 0
# \end{cases}
# \end{equation}
#
# However, we can safely ignore the second case when $x = 0$, since the propability for such a case is $0$.
#
# ### Mapping the data into inteval $[0, 1]$
# We simply define $S(Sign(x)) = \frac{Sign(x) + 1}{2}$. To recover, we have $S^{-1}(x) = 2x - 1$
# In[12]:
def sign(x):
if x > 0:
return 1
elif x == 0:
return 0
return -1
def S(x):
return (sign(x) + 1) / 2
def S_inv(x):
return 2 * x - 1
# ## Initiate the data set
# We initiate the dataset using a standard normal detribution.
# Let's take $m = 4000$
# In[13]:
Xs = np.random.randn(4000, 2)
Ys = []
for data in Xs:
Ys.append(S(data[0] * data[1]))
Ys = np.asmatrix(Ys).T
# ## Train the dataset
# We use the same function for the training.
# In[14]:
M_1, M_2 = train(Xs, Ys, 500, 2.0)
# In[15]:
Ys_pred = predict(Xs, M_1, M_2)
# In[18]:
# calculathe the error ratio
np.sum(np.square(Ys_pred - Ys)) / 4000
# ## Error Analysis
# $24.725\%$ of error is acceptable for such a simple neural network structure. Now we construct a function using the neural net and plot the function together with the original function
# In[41]:
def original_fct(x, y):
return S(x * y)
def approximate_fct(x, y):
if neural_net(np.asmatrix([x, y]).T, M_1, M_2) > 0.5:
return 1
return 0
# In[42]:
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization!
fig = plt.figure()
ax = ax = Axes3D(fig)
x = y = np.arange(-1.0, 1.0, 0.05)
X, Y = np.meshgrid(x, y)
z1s = np.array([original_fct(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z1 = z1s.reshape(X.shape)
z2s = np.array([approximate_fct(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z2 = z2s.reshape(X.shape)
ax.plot_surface(X, Y, Z1)
ax.plot_surface(X, Y, Z2)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Value')
plt.show()
|
# defining the class named Person
# it has 3 parameters that each instance of the class will need
# first name, last name, and age
class Person:
def __init__(self, first, last, age):
self.__first = first
self.__last = last
self.__age = age
# declaring a public function that returns the full name of the instance of the class
def getFullName(self):
return self.__first + " " + self.__last
def getAge(self):
return self.__age
# creating an instance of the class
# we can do this as many times as we have people that we want to make a class instance for
p1 = Person("Jane", "Doe", 26)
# prints the full name of the individual
print(p1.getFullName())
print(p1.getAge())
try:
print(p1.__first)
except:
print("calling the __first variable failed")
|
import random
import turtle
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
def task1(steps, prob, move):
x = 0
if not move:
return x
for _ in range(steps):
if random.random() < prob:
x -= 1
else:
x += 1
return x
# Task 1
# expected1 = 0
# walks1=[]
# for i in range(1000):
# walks1.append(task1(100, 0.5, True))
# expected1= sum(walks1)/1000
# print(expected1)
# plt.title('Distances travelled')
# plt.hist(walks1, bins=50, color='blue')
# plt.xlabel('Distance from starting point')
# plt.ylabel(' Frequency')
# plt.grid(True)
# plt.show()
# pyplot.plot(random_walk(100, 50))
# pyplot.plot(random_walk(100, 20))
# pyplot.legend(["Walk1", "Walk2"])
# pyplot.show()
def task2(prob, move1, move2):
x, y = 0, 50
steps = 0
while x != y:
if random.random() < prob:
x -= 1
x*= move1
y += 1
y *= move2
else:
x += 1
x *= move1
y -= 1
y *= move2
steps += 1
return steps
# Task 2
expected2 = 0
walks2 = []
for i in range(100):
# We assume the speed of a random walk to be 1.4 m/s
walks2.append(task2(0.5, True, False))
expected2 = sum(walks2)/100
print(walks2)
plt.title('Time taken')
plt.hist(walks2, bins=50, color='blue')
plt.xlabel('Time to meet')
plt.ylabel(' Frequency')
plt.grid(True)
plt.show()
def task3(steps, p1, p2):
orientation_prob = [1/8, 1/8, 1/8, 1/8, 1/8, 1/8, 1/8, 1/8]
step_prob = [1/3, 1/3, 1/3]
orientation = [0, 45, 90, 135, 180, 225, 270, 315]
step_size = [0, 0.5, 1]
# if prob of each orientation isn't equally likely
if not p1:
orientation_prob = [0.3, 0.2, 0.1, 0.4]
# if prob of each step isn't equally likely
if not p2:
step_prob = [1/2, 0.2, 0.3]
for _ in range(steps):
# if turtle goes out or circle's boundary, it sends it back
# choosing turtle's orientation and steps using thier prob, randomly
angle = np.random.choice(orientation, p=orientation_prob)
dist = np.random.choice(step_size, p=step_prob)
# 1 cm = approximately 38 pixels
dist *= 38
if angle == 0:
path.forward(dist)
elif angle == 90:
path.right(90)
path.forward(dist)
elif angle == 180:
path.backward(dist)
elif angle == 270:
path.left(90)
path.forward(dist)
if path.distance(0, 0) >= 100:
# path.setheading(path.towards(0,0))
path.penup()
path.goto(0, 0)
path.pendown()
# Task 3
# circle = turtle.Turtle()
# circle.penup()
# circle.sety(-100)
# circle.pendown()
# circle.circle(100)
# path = turtle.Turtle()
# path.color("red")
# task3(100, True,True)
def task4(steps, prob, move):
x = 0
if not move:
return x
for _ in range(steps):
if random.random() < prob:
x -= np.random.uniform(0, 1)
else:
x += np.random.uniform(0, 1)
return x
# Task 4
# expected3 = 0
# walks3=[]
# for i in range(1000):
# walks3.append(task4(100, 0.5, True))
# expected3= sum(walks3)/1000
# print(expected3)
# plt.title('Distances travelled')
# plt.hist(walks3, bins=50, color='blue')
# plt.xlabel('Distance from starting point')
# plt.ylabel(' Frequency')
# plt.grid(True)
# plt.show()
def task5(steps, p1, p2):
orientation_prob = [0.25, 0.25, 0.25, 0.25]
step_prob = [1/3, 1/3, 1/3]
orientation = [0, 90, 180, 270]
step_size = [0, 0.5, 1]
# orientation_prob =
# if prob of each orientation isn't equally likely
if not p1:
orientation_prob = [0.3, 0.2, 0.1, 0.4]
# if prob of each step isn't equally likely
if not p2:
step_prob = [1/2, 0.2, 0.3]
for _ in range(steps):
# if turtle goes out or circle's boundary, it sends it back
# choosing turtle's orientation and steps using thier prob, randomly
angle = np.random.choice(np.random.uniform(0, 360), p=orientation_prob)
dist = np.random.choice(step_size, p=step_prob)
# 1 cm = approximately 38 pixels
dist *= 38
if angle == 0:
path.forward(dist)
elif angle == 90:
path.right(90)
path.forward(dist)
elif angle == 180:
path.backward(dist)
elif angle == 270:
path.left(90)
path.forward(dist)
if path.distance(0, 0) >= 100:
# path.setheading(path.towards(0,0))
path.penup()
path.goto(0, 0)
path.pendown()
|
from collections import Counter
import re
def _merge_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
def replace(clicks):
clicks = clicks.replace('blue', 'B')
clicks = clicks.replace('red', 'R')
clicks = clicks.replace('yellow', 'Y')
clicks = clicks.replace('green', 'G')
clicks = clicks.replace(',', '')
return clicks
def remove_sequences(clicks):
return re.sub(r"([A-Z])\1+", "\\1", clicks)
def find(clicks, counter):
result = {}
times=2
length_a = len(clicks)
for n in range(1,length_a/times+1)[::-1]:
substrings=[clicks[i:i+n] for i in range(length_a-n+1)]
freqs=Counter(substrings)
fmc = freqs.most_common(1)[0][1]
if fmc>=times and n > 1:
seq=freqs.most_common(1)[0][0]
for i in range(fmc):
clicks = clicks.replace(seq, str(counter), 1)
counter = counter + 1
result[seq] = fmc
r = find(clicks, counter)
result = _merge_dicts(result, r)
break
return result |
def check_palindrome(word):
letters = list(word.lower())
for i in letters:
j = letters.index(i) + 1
if i == letters[-j]:
pass
else:
return False
return True
def palindrome_two(word):
letters = list(word.lower())
letter_dict = {a+b:True for a, b in zip(letters, letters[::-1]) if a == b}
return True if len(letter_dict) == (len(letters)/2) else False
def palindrome_three(word):
a = list(word.lower())
b = a[::-1]
return True if a == b else False
words = ['hannah', 'Hannah', 'alanna']
for word in words:
print(word), ':', check_palindrome(word)
print(word), ':', palindrome_two(word)
print(word), ':', palindrome_three(word)
|
print("------------------------------------Exercise A -----------------------------------------------")
print("Display all numbers 1-5, using list of numbers.")
for num in (1,2,3,4,5):
print (num, end=' ')
print ("\n")
print("------------------------------------Exercise B --------------------------------------------------")
print("Print Hello World five times using range function with for loop.")
for num in range(5):
print ("Hello World")
print("\n")
print("------------------------------------Exercise C --------------------------------------------------")
print("Display all numbers 1-10, using range function with for loop.")
for a in range(11):
print (a, end=' ')
print ("\n")
print("------------------------------------Exercise D --------------------------------------------------")
print("Print all the even numbers between 1-10, using range function with for loop.")
for b in range(2,11,2):
print (b, end=' ')
print("\n")
print("------------------------------------Exercise E --------------------------------------------------")
print("Print all the odd numbers between 1-10, using range function with for loop.")
for c in range(1,10,2):
print (c, end=' ')
print("\n")
print("------------------------------------Exercise F --------------------------------------------------")
num = int(input("Enter a number, I will print all the numbers from one to this number: "))
i = num
print("Numbers in forward direction.")
for num in range(1,num+1):
print(num, end=' ')
print("\n")
print("\nNumbers in backward direction.")
for i in range(i,0,-1):
print(i, end=' ') |
def personal_info():
print("My name is Ashur Motlagh")
print("In live in California.")
print("My phone number is: 714-726-4503")
def work_info():
name=str(input("Enter your name: "))
age=int(input("Enter your age: "))
salary=int(input("Enter your salary: "))
bonus=int(input("Enter your bonus: "))
pay=float(salary+bonus)
print("\nHere is your information!")
print("Your name: ", name)
print("Your Age: ", age)
print("Your total pay: ", pay)
def main():
print("I am inside the main function. \n")
print("Calling \"personal_info\" function.")
print("Here \"programmer\" is giving his information.\n")
personal_info()
print("\nCalling \"work_info\" function.")
print("Here \"user\" is giving his information.\n")
work_info()
print("\nDone writing personal information and work information inside main")
main() |
def main():
n1=int(input("Enter your first number: "))
n2=int(input("Enter your second number: "))
print()
print("Calling method \"sum_two\" inside main function")
s=sum_two(n1, n2)
print("Sum of ", n1, "and", n2, "inside \'main\' function is: ", s)
print()
print("Calling method \"min_two\" inside main function")
minimum=min_two(n1, n2)
print("Minimum of", n1, "and", n2, "inside \'main\' function is: ", minimum)
print()
print("Calling method \"max_two\" inside the main function")
maximum=max_two(n1, n2)
print("Maximum of", n1, "and", n2, "inside \'main\' function is: ", maximum)
print()
average=find_average(n1, n2)
print("Average of ", n1, "and", n2, "inside \'main\' function is: ", average)
find_range=maximum-minimum
print("Value of Range inside main function is: ", find_range)
def sum_two(a, b):
sum =a+b
return sum
def min_two(c, d):
mi = min(c, d)
return mi
def max_two(e, f): #this is another way to do it with if else.
if e>f:
ma=e
else:
ma=f
return ma
def find_average(g, h):
average=(g+h)/2
return average
main()
|
# This lab is teaching us to use file append mode
ans = "yes"
while ans[0].lower() == "y":
print("I am writing 3 numbers to the file.")
f1 = int(input("Enter first number: "))
f2 = int(input("Enter second number: "))
f3 = int(input("Enter third number: "))
myfile = open('lab25.txt', 'a')
myfile.write(str(f1) + "\n")
myfile.write(str(f2) + "\n")
myfile.write(str(f3) + "\n")
myfile.close()
print("Done writing to the file")
total = 0
print("\nNow reading these numbers from the file")
infile = open('lab25.txt', 'r')
line = infile.readline()
while(line != ''):
total = total + 1
line = infile.readline()
print("Total number of numbers inside the file is: ", total)
infile.close()
ans = str(input("\nDo you want to try out again? "))
print('Thanks for using this program')
|
def main():
n1 = int(input("Enter a number: "))
print()
print("Calling\'show_double\' function inside main function.")
show_double(n1)
print()
print("Back to \'main\' function.")
def show_double(a):
print("Double of",a,"inside \'show_double\' is:",a*2)
main() |
#!/usr/bin/python
class WordNode:
"""
Object representing a word and it's followers
"""
def __init__(self, word):
"""
Initialize with a string
"""
self.word = word
self.followers = {}
#can be used to begin a sentence
self.starter = False
#can be used to end a sentence
self.ender = False
#empty/base nodes should be allowed
if word != None:
try:
#characters that denote the end of a sentence
if word[-1] in ['!','?','.']:
self.ender = True
except IndexError as e:
print(e)
else:
self.ender = False
def add(self, f):
"""
Add a follower
"""
if f not in self.followers.keys():
self.followers[f] = 0
self.followers[f] += 1
class WordWeb:
"""
A collection of WordNodes
"""
def __init__(self):
"""
Initialize with a base node
"""
self.nodes = {None: WordNode(None)}
def add(self, front, follow):
"""
Add a new wordNode
"""
if follow not in self.nodes.keys():
#create a new WordNode
self.nodes[follow] = WordNode(follow)
#add it to a previously exising WordNode
self.nodes[front].add(self.nodes[follow])
if front == None:
self.nodes[follow].starter = True
def getSentence(self, start_node = None):
"""
Holds metadata for recursive method
"""
import random
#metadata
sentence = []
#recursive method
def _getSentence(node):
"""
Recursively traverses web to produce a sentence
"""
if node.word != None:
sentence.append(node.word)
if node.ender == True or len(node.followers) <= 0:
return
#weighted random choose next word
choices = []
for follower in node.followers:
for _ in range(node.followers[follower]):
choices.append(follower)
return _getSentence(random.choice(choices))
if start_node == None:
start_node = self.nodes[None]
elif isinstance(start_node, WordNode) == False:
raise TypeError('Argument to .getSentence must be of type WordNode')
_getSentence(node = start_node)
return (' '.join(sentence))
|
#TIC-TAC
board=['_','_','_','_','_','_','_','_','_',]
pp1=[]
pp2=[]
def rules():
print("Positions:\t 1 | 2 | 3")
print("\t\t____|___|____")
print("\t\t 4 | 5 | 6")
print("\t\t____|___|____")
print("\t\t 7 | 8 | 9")
print("\t\t | | ")
def check(pos):
#Checking Weather the requested place is empty
if(board[pos-1]=='_'):
return True
return False
def won(player):
print()
print("\n\n\t\t",player," Won The Match")
def check_row(symbol):
for i in range (3):
count=0
for j in range (3):
if(board[(3*i)+j]==symbol):
count+=1
else:
break
if count==3:
print(i+1,'Row')
return True
return False
def check_column(symbol):
for i in range (3):
count=0
for j in range (3):
if(board[i+(3*j)]==symbol):
count+=1
else:
break
if count==3:
print(i+1,'Column')
return True
return False
def check_dia(symbol):
if board[0]==symbol and board[4]==symbol and board[8]==symbol:
return True
elif board[2]==symbol and board[4]==symbol and board[6]==symbol:
return True
else :
return False
def result(symbol):
return (check_row(symbol) or check_column(symbol) or check_dia(symbol))
def display():
print("\t\t ",board[0]," | ",board[1]," | ",board[2],)
print("\t\t_____|_____|_____")
print("\t\t ",board[3]," | ",board[4]," | ",board[5],)
print("\t\t_____|_____|_____")
print("\t\t ",board[6]," | ",board[7]," | ",board[8],)
print("\t\t | | ")
def play():
print('*************************************************TIC-TAC*************************************************')
print('Player 1:" X "')
print('Player 2:" O "')
rules()
print('Enter Names')
p1=input("Player 1:")
p2=input("Player 2:")
turn=0
while turn<9:
if turn%2==0:
#player 1
print(p1," It's Your Turn:-")
while 1:
pos=int(input("Enter the block no."))
if pos<1 or pos>9:
pass
elif(check(pos)):
break
print("Bosdike Dekh k Daal:\tChutiya")
board[pos-1]='X'
pp1.append(pos)
display()
if (result('X')):
won(p1)
break
else:
#player 2
print(p2," It's Your Turn:-")
while 1:
pos=int(input("Enter the block no."))
if pos<1 or pos>9:pass
elif(check(pos)):
break
print("Bosdike Dekh k Daal:\tChutiya")
board[pos-1]='O'
pp2.append(pos)
display()
if (result('O')):
won(p2)
break
turn+=1
if turn==10:
print('************DRAW************')
print(board)
play()
|
import random
def miller_test(n, iterations):
if n == 2: # corner case even prime 2
return True
if n % 2 == 0: # if n is even it can't be prime except for 2 handled above
return False
m = n - 1
k = 0
# finding m where m is the least integer = n-1/2^k
while m % 2 == 0:
m //= 2
k += 1
# choose a where a is a random number and 1<a<n-1
for _ in range(iterations):
prime = False
a = random.randrange(2, n)
# according to fermat n is prime if a^(n-1) - 1 mod n = 0
# we express a^(n-1) - 1 as (a^m-1)(a^m+1)(a^2m)...(a^2) (difference of squares factorization)
# if n is divisible by any of the terms in the expansion it's probably prime
b = pow(a, m, n)
if b == 1 or b == n - 1:
# testing divisibility of first two terms (a^m-1),(a^m+1)
prime = True
for _ in range(k):
# testing divisibility of the remaining terms (a^2m)...(a^2)
b = pow(b, 2, n)
if b == n - 1:
prime = True
if not prime:
return False
return True
|
def favGenre(userSongs, songGenres):
"""
TC:O(m*n*l) , m=len of genre, n= len of songs, l=len of users
SC:(m*n), {song:genre} hashmap
https://leetcode.com/discuss/interview-question/373006
"""
songMapGenre = {}
res = defaultdict(list)
# mapping each song to genre
for key in songGenres:
songs = songGenres[key]
for song in songs:
songMapGenre[song] = key
print(songMapGenre)
for user in userSongs:
songlist = userSongs[user]
temp = defaultdict(int)
maxval = -inf
maxgenre = []
for songg in songlist:
gen = songMapGenre[songg]
temp[gen] += 1
maxval = max(maxval, temp[gen])
for gen in temp:
if temp[gen] == maxval:
maxgenre.append(gen)
res[user] = maxgenre
print(res)
return res
userSongs = {
"David": ["song1", "song2", "song3", "song4", "song8"],
"Emma": ["song5", "song6", "song7"]
}
songGenres = {
"Rock": ["song1", "song3"],
"Dubstep": ["song7"],
"Techno": ["song2", "song4"],
"Pop": ["song5", "song6"],
"Jazz": ["song8", "song9"]
}
favGenre(userSongs, songGenres)
|
# Explorar el tema de conceptos y turnos
# Continua en test7, aquí realmente destaca el "colocador de texto"
import pygame
import pygame_widgets
import random
from Constantes import *
from Clases import *
from Funciones import *
# Creamos la ventana donde se muestra todo
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Test7')
# Mezcla las cartas
def shuffle():
grupo_cartas.empty()
# Generamos 8 cartas
for i in range(8):
# Escojemos al azar entre dos tipos de cartas
if random.choice([True, False]):
carta_n = Carta([100 + i * (WIDTH - 100) / 8, HEIGHT - 150], [90, 100], NEGRO, 'LADRILLO1', texto_reparar,
LADRILLO1)
else:
carta_n = Carta([100 + i * (WIDTH - 100) / 8, HEIGHT - 150], [90, 100], NEGRO, 'ESPADA1', texto_daño,
ESPADA1)
# Creamos y añadimos las animaciones a la carta creada
expandir_carta_n = Animador(carta_n, 0.3, ['dimen', [150, 150]], 'expandir')
encojer_carta_n = Animador(carta_n, 0.3, ['dimen', [50, 50]], 'encojer')
carta_n.loadObject(expandir_carta_n)
carta_n.loadObject(encojer_carta_n)
grupo_cartas.add(carta_n)
# "Pinta" la pantalla
def renderWindow():
WIN.fill(AZUL_CLARO)
# Mostramos las cartas
grupo_cartas.update(WIN)
grupo_cartas.draw(WIN)
for carta in grupo_cartas:
carta.redraw(WIN)
# Mostramos los recursos
grupo_recursos1.update(WIN)
grupo_recursos1.draw(WIN)
for carta_rec in grupo_recursos1:
carta_rec.redraw(WIN)
# Mostramos las bases y torres
grupo_base1.update(WIN)
grupo_base1.draw(WIN)
grupo_base2.update(WIN)
grupo_base2.draw(WIN)
for base in bases:
base.update(WIN)
base.redraw(WIN)
# Testeo. Mostramos los widgets
for widget in lWidgets:
widget.draw()
# Se actualiza la ventana
pygame.display.update()
# Gestiona la posición del raton respecto a otras entidades
def mouseHandler(pos):
for carta in grupo_cartas:
if carta.mouseOver(pos):
cardHandler(carta.tipo)
# Gestiona las pulsaciones de teclas
def keyHandler(key):
pass
# Gestiona la activación de botones y widgets
def botonHandler(tipo):
if tipo == 1:
if not bases[0].anim['resta hp'].busy:
bases[0].anim['resta hp'].target = ['hp', clamp(bases[0].get('hp') - 25, 0, 100)]
bases[0].anim['resta hp'].start()
elif tipo == 2:
if not bases[0].anim['resta hp_muro'].busy:
bases[0].anim['resta hp_muro'].target = ['hp_muro', clamp(bases[0].get('hp_muro') - 25, 0, 100)]
bases[0].anim['resta hp_muro'].start()
elif tipo == 3:
for recurso in grupo_recursos1:
recurso.posicion[0] = textbox_posX.getText()
recurso.posicion[1] = textbox_posY.getText()
# Gestiona el uso de cartas
def cardHandler(tipo):
if tipo == 'ESPADA1':
if not bases[1].anim['resta hp'].busy:
bases[1].anim['resta hp'].target = ['hp', clamp(bases[1].get('hp') - 25, 0, 100)]
bases[1].anim['resta hp'].start()
elif tipo == 'LADRILLO1':
if not bases[0].anim['suma hp_muro'].busy:
bases[0].anim['suma hp_muro'].target = ['hp_muro', clamp(bases[0].get('hp_muro') + 25, 0, 100)]
bases[0].anim['suma hp_muro'].start()
# Genera los castillos al principio
def generaCastillos():
for i in range(2):
torrel = Torre(TORRESENCILLA2, 1, 1, 25, 125)
torrer = Torre(TORRESENCILLA2, 1, 1, 25, 125)
torrec = Torre(TORRESENCILLA2, 1, 1, 30, 150)
muralla = Torre(MURALLA2, 1, 1, 175, 55)
hp = 100
hp_texto = TextoColgado(100, TEST_FONT_DESCR, AZUL)
hp_muro = 100
hp_muro_texto = TextoColgado(100, TEST_FONT_DESCR, ROJO)
if i == 0:
grupo_base1.add(torrel, torrer, torrec, muralla)
else:
grupo_base2.add(torrel, torrer, torrec, muralla)
base = Base(225 + i * (WIDTH - 450), 150, 1, 1, torrel, torrer, torrec, muralla, hp, hp_texto, hp_muro,
hp_muro_texto)
bases.append(base)
anim_base1 = Animador(bases[i], 1.2, ['hp', bases[i].get('hp') - 5], 'resta hp')
anim_base2 = Animador(bases[i], 1.2, ['hp', bases[i].get('hp') + 5], 'suma hp')
anim_mura1 = Animador(bases[i], 1.2, ['hp_muro', bases[i].get('hp_muro') - 5], 'resta hp_muro')
anim_mura2 = Animador(bases[i], 1.2, ['hp_muro', bases[i].get('hp_muro') + 5], 'suma hp_muro')
base.loadObject(anim_base1)
base.loadObject(anim_base2)
base.loadObject(anim_mura1)
base.loadObject(anim_mura2)
# Genera los recursos al principio
def generaRecursos():
grupo_recursos1.empty()
recurso1 = Recurso('espadas', 5, 3)
carta_recurso1 = CartaRecurso((100, 100), (150, 150), NEGRO, REC_ESPADA1, recurso1)
carta_recurso1.loadObject(texto_espadas)
grupo_recursos1.add(carta_recurso1)
# Grupos de sprites para las torres de las dos bases
grupo_base1 = pygame.sprite.Group()
grupo_base2 = pygame.sprite.Group()
# Grupo para las dos bases
bases = []
# Grupo de sprites para las cartas
grupo_cartas = pygame.sprite.Group()
# Grupo de sprites para los recursos
grupo_recursos1 = pygame.sprite.Group()
# Texto para las cartas
texto_daño = TextoColgado('Daño', TEST_FONT_DESCR, ROJO)
texto_reparar = TextoColgado('Reparar', TEST_FONT_DESCR, AZUL)
texto_espadas = TextoColgado('Algunas cosas', TEST_FONT_DESCR, VERDE, 'espadas')
# Barajamos las cartas una primera vez, y creamos los castillos
shuffle()
generaCastillos()
generaRecursos()
# Widget para testear
boton_damage = pygame_widgets.Button(WIN, 250, 300, 125, 40, text='Dañar castillo', onClick=botonHandler,
onClickParams=[1])
boton_damage_muro = pygame_widgets.Button(WIN, 250, 350, 125, 40, text='Dañar muras', onClick=botonHandler,
onClickParams=[3])
boton_shuffle = pygame_widgets.Button(WIN, 450, 325, 125, 40, text='Cartas nuevas', onClick=shuffle)
textbox_posX = pygame_widgets.TextBox(WIN, 150, 100, 200, 25)
textbox_posY = pygame_widgets.TextBox(WIN, 150, 125, 200, 25)
sliderx = pygame_widgets.Slider(WIN, 250, 50, 200, 25, min=0, max=1, step=0.01)
slidery = pygame_widgets.Slider(WIN, 250, 150, 200, 25, min=0, max=1, step=0.01)
lWidgets = [boton_damage, boton_damage_muro, boton_shuffle, textbox_posX, textbox_posY, sliderx, slidery]
def main():
run = True
clock = pygame.time.Clock()
while run:
clock.tick(30)
# Comprobamos que eventos han ocurrido y actuamos respecto a ellos
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mouseHandler(pygame.mouse.get_pos())
keyHandler(pygame.key.get_pressed())
# Testeo
for boton in lWidgets:
boton.listen(events)
for recurso in grupo_recursos1:
recurso.offset[0] = sliderx.getValue()
recurso.offset[1] = slidery.getValue()
renderWindow()
pygame.quit()
if __name__ == '__main__':
main()
|
class Twitter(object, ):
def __init__(self):
self.tweets = {}
self.followDB = {}
self.count = 0
def postTweet(self, userId, tweetId):
self.count += 1
if (userId not in self.tweets):
self.tweets[userId] = []
self.tweets[userId].append({'count': self.count, 'tweet': tweetId})
def getNewsFeed(self, userId):
a = []
if (userId in self.tweets):
for tweet in self.tweets[userId]:
if (tweet not in a):
a.append(tweet)
if (userId in self.followDB):
for t in self.followDB[userId]:
if (t in self.tweets):
for tweet in self.tweets[t]:
if (tweet not in a):
a.append(tweet)
recentNums = []
for val in a:
recentNums.append(int(val['count']))
toReturn = []
toFind = sorted(recentNums, reverse=True)[:10]
print toFind
for v in toFind:
for val in a:
if (int(val['count']) == v):
toReturn.append(val['tweet'])
return toReturn
def follow(self, followerId, followeeId):
if (followerId not in self.followDB):
self.followDB[followerId] = []
self.followDB[followerId].append(followeeId)
def unfollow(self, followerId, followeeId):
if (followerId in self.followDB):
if (followeeId in self.followDB[followerId]):
self.followDB[followerId].remove(followeeId) |
import random
class Solution(object):
def __init__(self, nums):
self.db = {}
for (i, val) in enumerate(nums):
if (val not in self.db):
self.db[val] = []
self.db[val].append(i)
def pick(self, target):
return random.choice(self.db[target])
|
class Solution(object):
def insert(self, intervals, newInterval):
def merge_interval(intervals):
a = []
prevVal = (-1)
while (len(intervals) > 0):
startInterval = intervals[0][0]
endInterval = intervals[0][1]
intervals.pop(0)
while ((len(intervals) > 0) and (endInterval >= intervals[0][0])):
endInterval = max(intervals[0][1], endInterval)
intervals.pop(0)
a.append([startInterval, endInterval])
return a
intervals.append(newInterval)
intervals.sort(key=(lambda k: k[0]))
print intervals
return merge_interval(intervals) |
import string
class Solution(object):
def mostCommonWord(self, paragraph, banned):
listOfWords = banned
allWords = []
for word in paragraph.split(' '):
for letter in string.punctuation:
word = word.replace(letter, '')
word = word.lower()
if (word not in listOfWords):
allWords.append(word)
highWordCount = 0
highWord = None
for word in list(set(allWords)):
wordCount = allWords.count(word)
if (wordCount > highWordCount):
highWordCount = wordCount
highWord = word
return highWord
|
class Solution(object):
def treeToDoublyList(self, root):
a = []
def check(root):
if (root == None):
return
a.append(root.val)
check(root.left)
check(root.right)
check(root)
a.sort()
g = []
def linkedList(start=False, prev=None):
if (len(a) == 0):
g.append(prev)
return g[0]
e = Node(a.pop(0))
if (start == True):
g.append(e)
e.left = prev
e.right = linkedList(prev=e)
return e
print a
r = linkedList(True, prev=None)
if (len(g) == 0):
return
if (r == None):
return
r.left = g[(-1)]
return r |
import string
diction = {}
MAIN = list(string.printable)
for (i, letter) in enumerate(MAIN):
diction[str(i)] = letter
class Codec:
def encode(self, longUrl):
new = ''
for letter in longUrl:
new = ((new + '-') + str(MAIN.index(letter)))
print new
return new
def decode(self, shortUrl):
decoded = ''
for num in shortUrl.split('-'):
try:
decoded = (decoded + str(diction[str(num)]))
except:
pass
return decoded
|
import string
class Solution(object):
def generateTheString(self, n):
if ((n % 2) == 0):
stringVal = ''.join(['a' for i in range((n - 1))])
return (stringVal + 'z')
else:
return ''.join(['a' for i in range(n)])
|
class NestedIterator(object, ):
def __init__(self, nestedList):
def getR(a):
final = []
if (type(a) == list):
for val in a:
if (val.isInteger() == False):
final += getR(val)
else:
final.append(val.getInteger())
else:
x = a.getInteger()
if (x == None):
for val in a.getList():
final += getR(val)
else:
final.append(x)
return final
print nestedList
self.listVal = getR(nestedList)
print self.listVal
def next(self):
return self.listVal.pop(0)
def hasNext(self):
return (len(self.listVal) > 0) |
class Solution(object):
def average(self, salary):
minVal = float('inf')
maxVal = float('-inf')
total = 0
for v in salary:
if (v < minVal):
minVal = v
if (v > maxVal):
maxVal = v
total += v
print minVal
print maxVal
return (float(((total - minVal) - maxVal)) / (len(salary) - 2)) |
class Solution(object):
def isPowerOfTwo(self, n):
def is_power(n):
if ((n == 1) or (n == 2)):
return True
if (n < 2):
return False
if (n != int(n)):
return False
return is_power((float(n) / 2.0))
return is_power(n) |
class Solution(object):
def isPowerOfThree(self, n):
def is_power(n):
if (n != int(n)):
return False
if (n == 3):
return True
if (n == 1):
return True
if (n < 3):
return False
return is_power((float(n) / 3.0))
return is_power(n) |
from tkinter import *
import random
w=Tk()
w.title("가위 바위 보 게임")
def selection(var):
img = [PhotoImage(file='image/scissor.png'), PhotoImage(file='image/rock.png'), PhotoImage(file='image/paper.png')]
user_lb = Label(w, text='사용자', compound='top', image=img[var])
user_lb.image = img[var]
user_lb.grid(row=0,column=0)
com_img = random.randrange(0,3)
com_lb = Label(w, text='컴퓨터', compound='top', image=img[com_img])
com_lb.image = img[com_img]
com_lb.grid(row=0,column=2)
if var==com_img:
arrow_lb = Label(w, text='=====', font='Helvetica 30')
result_lb = Label(w, text='비김!', font='Helvetica 15', fg='black', width=15)
elif (var==0 and com_img==1) or (var==1 and com_img==2) or (var==2 and com_img==0):
arrow_lb = Label(w, text='<<<<<', font='Helvetica 30')
result_lb = Label(w, text='컴퓨터 승!', font='Helvetica 15', fg='red', width=15)
else:
arrow_lb = Label(w, text='>>>>>', font='Helvetica 30')
result_lb = Label(w, text='사용자 승!', font='Helvetica 15', fg='blue', width=15)
arrow_lb.grid(row=0, column=1)
result_lb.grid(row=1,column=1)
btn_scissor = Button(w, text="가위", bg='yellow', width=15, command=lambda:selection(0))
btn_rock = Button(w, text="바위", bg='yellow', width=15, command=lambda:selection(1))
btn_paper = Button(w, text="보", bg='yellow', width=15, command=lambda:selection(2))
btn_scissor.grid(row=2, column=0)
btn_rock.grid(row=2, column=1, padx=80)
btn_paper.grid(row=2, column=2)
w.mainloop()
|
def binary_search(arr, n, k):
start_index = 0
end_index = n-1
# while start index is less or equal to end index
while start_index <= end_index:
# mid index is the start index + end index - start index
# if start index is 40 and end index is 45 then mid index is 40 + 1.5 ie 43/42 ~ whatever 😂
mid_index = start_index + (end_index - start_index)//2
# k is the current mid index
if arr[mid_index] == k:
return 1
# k is on the right
elif arr[mid_index] < k:
start_index = mid_index + 1
# k is on the left,
else:
end_index = mid_index - 1
return -1
num_inputs = int(input())
for i in range(0, num_inputs):
n_and_k = [int(x) for x in input().split()]
n = n_and_k[0]
k = n_and_k[1]
arr = [int(x) for x in input().split()]
result = binary_search(arr, n, k)
print(result) |
rojo = [255,0,0]
verde = [0,255,0]
azul = [0,0,255]
# Los vectores en Python se representan con la estructura de datos lista
tupla = (1,1,1)
# Las tuplas son otra estructura de datos pero son imutables
print(type(rojo))
print(type(tupla))
print('El color rojo se representa con el vector ', rojo)
print('El color verde se representa con el vector', verde)
print('El color azul se representa con el vector', azul)
# Para conocer la dimensión de un vector, podemos utilizar el método len
print('La dimensión del vector rojo es ', len(rojo))
# Se pueden sumar vectores y así mismo crear stacks de vectores
rojo_verde = rojo + verde
print('La suma del vector rojo y verde es ', rojo_verde)
# Se puede hacer sub vectores en python indicando del subindice que parte el vector hasta el ultimo subindice
print('Se partira el vector rojo ', rojo[0:2])
|
import numpy as np # Importamos numpy
vector = np.array([1,-1,1]) # Declaramos el vector como numpy array
escalar = 3.1 # Declaramos el escalar
print('El resultado del producto vector y escalar es ', vector*escalar)
### EJERCICIO ###
v = np.array([1,1])
a = -1
b = 2
c = 0.1
|
T=input('#TestCases')
cases=[]
for i in range(int(T)):
N=0
B=0
test_case_line=input('#OfHouses Budget')
test_case_line_list=test_case_line.split(' ')
N=int(test_case_line_list[0])
B=int(test_case_line_list[1])
test_case_line2=input('NPricesOfEachHouse')
A=test_case_line2.split(' ')
A=[int(i) for i in A]
A.sort()
over_price=0
number_of_Houses=0
if A[0]<=B:
for price in A:
over_price+=price
if over_price<=B:
number_of_Houses+=1
cases.append(number_of_Houses)
TestCase=1
for n in cases:
print(f'Case #{TestCase}: {n}')
TestCase+=1 |
# -*- coding:utf-8 -*-
'''
python文件操作
创建,打开,添加,读取文件和写入文件等操作.
'''
"""
# 1. 如何创建一个txt文件
def main():
# 声明变量f来打开一个名为first.txt的文件, open需要一个文件名和一个对文件的模式, w+: 表示写入并且如果文件中不存在则会创建文件
f = open('./demo/first.txt','w+') # 如果文件不存在,w会自动创建该文件.
# 写入文件内容:
for i in range(10):
f.write('this is firstoneyuan {}\r\n'.format(i+1))
# for循环,运行范围为10个数字.使用write函数将数据写入到文件中.
# 关闭first.txt文件的实例
f.close()
# 2. 如何添加数据到一个文件中
# a+ 表示以追加模式将数据写入文件, + 号表示,该文件不存在就会创建文件.
f = open('./demo/first.txt','a+')
for i in range(2):
f.write('appending two line firstoney {}\r\n'.format(i+1))
f.close()
# 3. 读取一个文件
# 以读取模式打开一个文件
f = open('./demo/first.txt','r')
# 使用mode函数检查文件是否处于打开模式.如果是打开模式,就读取并打印文件.
if f.mode == 'r':
contents = f.read()
print(contents) # 输出到屏幕.
"""
def main():
# 4. 如何逐行读取文件
f = open('./demo/first.txt','r')
f1 = f.readlines()
for x in f1:
print(x)
# 逐行读取文件时,它将分隔每一行并以可读格式显示文件
if __name__=="__main__":
main()
f = open('./demo/one.txt','w')
f.write('this is two')
f.close()
"""
python3的文件读取模式:
'r' : 默认模式为只读模式.
'w' : 打开文件再进行写入,如果文件不存在,会创建新文件,如果文件存在,会覆盖文件内容.
'x' : 创建一个新文件.如果文件已存在,则操作失败.
'a' : 以追加模式打开文件,如果文件不存在,则会创建新文件.
't' : 这是默认模式,以文本模式打开
'b' : 以二进制模式打开.
'+' : 打开一个文件进行读写(更新).
""" |
def write_to_file(file, postcode, city, country):
try:
with open(file, 'w') as opened_file:
opened_file.write(f'My postcode is {postcode} \nI am based in {city}, which is in {country}.')
except FileNotFoundError:
print('File not found.') |
"""Dans ce fichier vous trouvez des exemples d'utilisations des boucles
N'hesitez pas a vous exercer pour mieux comprendre comment on utilise cela"""
def Bonjour(nombre):
"""Cette fonction va servir à afficher la valeur absolu de nombre fois le mot bonjour
elle va prendre en paramètre un nombre qui indiquer le nombre d'affichage (int)"""
if nombre<0: #on va dist
while nombre < 0:
nombre = nombre + 1
print("Bonjour !")
else:
while nombre > 0:
nombre = nombre - 1
print("Bonjour !!")
#Pour l'utilisation de la boucle for, vous aurez un exemple dans le fichier Liste
#Pour l'utilisation des mots-cles break et continue, je vous laisse vous amusez avec ^^
if __name__ == '__main__':
Bonjour(12)
Bonjour(-3)
|
from functools import reduce
class Group():
def __init__(self, raw):
self.persons = [set(x) for x in raw.split("\n")]
def get_answers_count(self, aggregation):
return len(reduce(aggregation, self.persons))
with open('input', 'r') as f:
groups = [Group(x) for x in f.read().split("\n\n")]
print("Part 1:", sum([g.get_answers_count(lambda a, b: a|b) for g in groups]))
print("Part 2:", sum([g.get_answers_count(lambda a, b: a&b) for g in groups])) |
def solve1(board):
return descend(board, 3, 1)
def solve2(board):
a = descend(board, 1, 1)
b = descend(board, 3, 1)
c = descend(board, 5, 1)
d = descend(board, 7, 1)
e = descend(board, 1, 2)
return a * b * c * d * e
def descend(board, slope_x, slope_y):
trees_count = 0
x, y = 0, 0
while y < len(board):
tree = access(board, x, y)
if tree == '#':
trees_count += 1
x += slope_x
y += slope_y
return trees_count
def access(board, x, y):
width = len(board[0])
x = x % width
return board[y][x]
def main():
with open('input', 'r') as f:
lines = f.readlines()
board = [x.strip() for x in lines]
print(solve1(board))
print(solve2(board))
main() |
def partOne(val):
# The bottom right value of each square is an odd power of 2 (9, 25, 49, 81, ...)
# Find which square the number is in by getting the next upper odd power of 2
i = 1
while i*i < val:
i += 2
square = i/2
# The number "square" is at distance "square * 2" from the center
# All numbers in this square are at distance D such as: square >= D >= 2 * square
# (i * i) is the value of the bottom right corner
# We can decrement from (i * i) to get to val
# The distance D of each step number will go down and up in its bounds
# A modulo on (i * i) - v will give us the distance difference between d(square * 2) and d(value)
return (square * 2) - ((i * i - val) % square)
def partTwo(val):
# Build the spiral
values = [(0, 0, 1)]
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] # Right, Up, Left, Down
steps = 0
directionIndex = 0
while True:
# Increase the step (segment length) every two segment
if directionIndex % 2 == 0:
steps += 1
# Compute one segment
for step in range(0, steps):
currentX, currentY, _ = values[-1]
dX, dY = directions[directionIndex % 4]
nextX = currentX + dX
nextY = currentY + dY
value = sum([v[2] for v in values if abs(nextX - v[0]) <= 1 and abs(nextY - v[1]) <= 1])
if value > val:
return value
next = (nextX, nextY, value)
values.append(next)
# Then change direction
directionIndex += 1
val = 347991 # answer: 480
print(partOne(val))
print(partTwo(val)) |
#!/usr/bin/env python
# coding=utf-8
import sys
def left_child(node):
return node * 2 + 1
def right_child(node):
return node * 2 + 2
def parent(node):
if (node % 2):
return (i - 1) / 2
else:
return (i - 2) / 2
def max_heapify(array, i, heap_size):
l = left_child(i)
r = right_child(i)
largest = i
if l < heap_size and array[l] > array[i]:
largest = l
if r < heap_size and array[r] > array[largest]:
largest = r
if largest != i:
array[i], array[largest] = array[largest], array[i]
max_heapify(array, largest, heap_size)
def build_max_heap(array):
for i in range(len(array) / 2, -1, -1):
max_heapify(array, i, len(array))
def heap_sort(array):
build_max_heap(array)
for i in range(len(array) - 1, 0, -1):
array[0], array[i] = array[i], array[0]
max_heapify(array, 0, i)
if __name__ == "__main__":
array = [0, 2, 6, 98, 34, -5, 23, 11, 89, 100, 7]
heap_sort(array)
for a in array:
sys.stdout.write("%d " % a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.