blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e5ee7a96bf4a82a2da1c5b73fd44323915423908 | namnv4/python | /recommendation-system/utils/manhattan.py | 6,632 | 4.125 | 4 | from collections import Counter
import matplotlib.pyplot as plt
import csv
def manhattan(rating1, rating2):
"""Computes the Manhattan distance. Both rating1 and rating2 are
dictionaries of the form
{'The Strokes': 3.0, 'Blue Streak': 2.5 ...}"""
distance = 0
for key in rating1:
if key in rating2:
distance += abs(rating1[key] - rating2[key])
return distance
def calculate_mean(list_of_numbers):
"""
Calculates the mean from a list of numbers
:rtype : object
"""
sum_of_numbers = sum(list_of_numbers)
count_of_numbers = len(list_of_numbers)
mean = sum_of_numbers/count_of_numbers
return mean
def calculate_median(numbers):
"""
Calculates the median from a list of numbers
"""
N = len(numbers)
numbers.sort()
# Find the median
if N % 2 == 0:
# if N is even
m1 = N/2
m2 = (N/2) + 1
# Convert to integer, match position, list index starts from 0 while len starts from 1 ..n
m1 = int(m1) - 1
m2 = int(m2) - 1
median = (numbers[m1] + numbers[m2])/2
else:
m = (N+1)/2
# Convert to integer, match position
m = int(m) - 1
median = numbers[m]
return median
if __name__ == '__main__':
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
print calculate_mean(donations)
def calculate_mode(numbers):
'''
Calculating the mode
'''
c = Counter(numbers)
mode = c.most_common(1)
return mode[0][0]
if __name__=='__main__':
scores = [7, 8, 9, 2, 10, 9, 9, 9, 9, 4, 5, 6, 1, 5, 6, 7, 8, 6, 1, 10]
mode = calculate_mode(scores)
print('The mode of the list of numbers is: {0}'.format(mode))
'''
Frequencies
Calculating the mode when the list of numbers may
have multiple modes
'''
def calculate_mode(numbers):
c = Counter(numbers)
numbers_freq = c.most_common()
max_count = numbers_freq[0][1]
modes = []
for num in numbers_freq:
if num[1] == max_count:
modes.append(num[0])
return modes
if __name__ == '__main__':
scores = [5, 5, 5, 4, 4, 4, 9, 1, 3]
modes = calculate_mode(scores)
print('The mode(s) of the list of numbers are:')
for mode in modes:
print(mode)
"""Frequency table"""
def frequency_table(numbers):
table = Counter(numbers)
print('Number\tFrequency')
for number in table.most_common():
print('{0}\t{1}'.format(number[0], number[1]))
if __name__=='__main__':
scores = [7, 8, 9, 2, 10, 9, 9, 9, 9, 4, 5, 6, 1, 5, 6, 7, 8, 6, 1, 10]
frequency_table(scores)
'''
Find the range
'''
def find_range(numbers):
lowest = min(numbers)
highest = max(numbers)
# Find the range
r = highest-lowest
return lowest, highest, r
if __name__ == '__main__':
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
lowest, highest, r = find_range(donations)
print('Lowest: {0} Highest: {1} Range: {2}'.format(lowest, highest, r))
def find_differences(numbers):
# Find the mean
mean = calculate_mean(numbers)
# Find the differences from the mean
diff = []
for num in numbers:
diff.append(num-mean)
return diff
def calculate_variance(numbers):
# Find the list of differences
diff = find_differences(numbers)
# Find the squared differences
squared_diff = []
for d in diff:
squared_diff.append(d**2)
# Find the variance
sum_squared_diff = sum(squared_diff)
variance = sum_squared_diff/len(numbers)
return variance
if __name__ == '__main__':
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
variance = calculate_variance(donations)
print('The variance of the list of numbers is {0}'.format(variance))
std = variance**0.5
print('The standard deviation of the list of numbers is {0}'.format(std))
def find_corr_x_y(x,y):
n = len(x)
# Find the sum of the products
prod = []
for xi, yi in zip(x,y):
prod.append(xi*yi)
sum_prod_x_y = sum(prod)
sum_x = sum(x)
sum_y = sum(y)
squared_sum_x = sum_x**2
squared_sum_y = sum_y**2
x_square = []
for xi in x:
x_square.append(xi**2)
# Find the sum
x_square_sum = sum(x_square)
y_square=[]
for yi in y:
y_square.append(yi**2)
# Find the sum
y_square_sum = sum(y_square)
# Use formula to calculate correlation
numerator = n*sum_prod_x_y - sum_x*sum_y
denominator_term1 = n*x_square_sum - squared_sum_x
denominator_term2 = n*y_square_sum - squared_sum_y
denominator = (denominator_term1*denominator_term2)**0.5
correlation = numerator/denominator
return correlation
if __name__ == '__main__':
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
print "Correlation ||||==>", find_corr_x_y(x,y)
# Find the sum of numbers stored in a file
def sum_data(filename):
s = 0
with open(filename) as f:
for line in f:
s = s + float(line)
print('Sum of the numbers =====>: {0}'.format(s))
if __name__ == '__main__':
sum_data('../res/test_data.txt')
'''
Calculating the mean of numbers stored in a file
'''
def read_data(filename):
numbers = []
with open(filename) as f:
for line in f:
numbers.append(float(line))
return numbers
if __name__ == '__main__':
data = read_data('../res/test_data.txt')
mean = calculate_mean(data)
print('Mean: {0}'.format(mean))
def scatter_plot(x, y):
plt.scatter(x, y)
plt.xlabel('X-Axis')
plt.ylabel('Correlation')
plt.show()
# def read_csv(filename):
# numbers = []
# squared = []
# with open(filename) as f:
# reader = csv.reader(f)
# next(reader)
# for row in reader:
# numbers.append(int(row[0]))
# squared.append(int(row[1]))
# return numbers, squared
# if __name__ == '__main__':
# numbers, squared = read_csv('../res/numbers.csv')
# scatter_plot(numbers, squared)
def read_csv(filename):
with open(filename) as f:
reader = csv.reader(f)
next(reader)
summer = []
highest_correlated = []
for row in reader:
summer.append(float(row[1]))
highest_correlated.append(float(row[2]))
return summer, highest_correlated
if __name__ == '__main__':
summer, highest_correlated = read_csv('../res/correlate-summer.csv')
corr = find_corr_x_y(summer, highest_correlated)
print('Highest correlation********: {0}'.format(corr))
scatter_plot(summer, highest_correlated) |
30cb2152ba61fdc70e20fde9f9b71daa05ffafa1 | divyachandramouli/Data_structures_and_algorithms | /4_Searching_and_sorting/Bubble_sort/bubble_sort_v1.py | 555 | 4.21875 | 4 | # Implementation of bubble sort
def bubble_sorter(arr):
n=len(arr)
i=0
for j in range(0,n):
for i in range(0,n-j-1):
#In the jth iteration, last j elements have bubbled up so leave them
if (arr[i]>arr[i+1]):
arr[i],arr[i+1]=arr[i+1],arr[i]
return arr
array1=[21,4,1,3,9,20,25,6,21,14]
print(bubble_sorter(array1))
" Average and worst case time complexity: O(n*n)"
" The above algorithm always runs O(n^2) time even if the array is sorted."
"It can be optimized by stopping the algorithm if inner loop didn't cause any swap" |
3f3205aea8dd64a69b9ed91f6aab600d63da9475 | divyachandramouli/Data_structures_and_algorithms | /3_Queue/Queue_builtin.py | 384 | 4.21875 | 4 | # Queue using Python's built in functions
# Append adds an element to the tail (newest element) :Enqueue
# Popleft removes and returns the head (oldest element) : Dequeue
from collections import deque
queue=deque(["muffin","cake","pastry"])
print(queue.popleft())
# No operation called popright - you dequeue the head which is the oldest element
queue.append("cookie")
print(queue)
|
da3083ae44778e0fbe6177756a4c4736d62d11f8 | divyachandramouli/Data_structures_and_algorithms | /4_Searching_and_sorting/Recursion/fib_val_iterative.py | 274 | 3.53125 | 4 | #Return the value of fib seq given the pos - iterative
def get_fib_val(pos):
if (pos==0):
return 0
if (pos==1):
return 1
first=0
second=1
next=first+second
for i in range(2,pos):
first=second
second=next
next=first+second
return next
print(get_fib_val(6)) |
c9c45ba67a057a5ff79e95737ff7e2e8799d622e | johan-wendelind/on-learning | /basics.py | 169 | 3.859375 | 4 | numbers = {"Johan": 10.0, "Hojt": 2.1, "Peter": 5.0}
mysum = sum(numbers.values())
length = len(numbers)
avg = mysum / length
print(avg)
hej = "Hej"
print(hej.lower())
|
6111c6ba0af45cb83eb7254b7a01c9aabba24421 | Egor93/Climate_dynamics_and_statistics | /ex1/ex1_part_2.py | 3,668 | 3.5 | 4 |
import numpy.linalg as LA
import numpy as np
import matplotlib.pyplot as plt
class PDF:
# DESCRIPTION
# Class containing all methods necessary to generate
# two arrays of samples which have user-defined standart deviation,mean;
# correlate/do not correlate with each other according to user input.
# INPUT
# means
# variances
# correlation - correlation coefficient (of two sample arrays)
# a_size - size of arrays of independent random samples
# OUTPUT
# plot_PDF_hist method, plots the 2D histogram of generated samples
def __init__(self,means,variances,correlation,a_size):
self.means = means
self.variances = variances
self.correlation = correlation
self.a_size = a_size
def get_covmat(self):
# DESCRIPTION
# Get covariance matrix using informaion
# about variances and correlation
variance1=self.variances[0]
variance2=self.variances[1]
covariance12=self.correlation*np.sqrt(variance1)*np.sqrt(variance2)
covmat=np.array([[variance1,covariance12],[covariance12,variance2]])
return covmat
def get_eigen(self):
# DESCRIPTION
# Get eigenvalues,eigentvectors of covariance matrix
covmat=self.get_covmat()
eigvals,eigvects=LA.eig(covmat)
return eigvals,eigvects
def get_A(self):
# DESCRIPTION
# Generate matrix A, containing two
# arrays of samples.
eigvals,eigvects=self.get_eigen()
variances=eigvals
# these standart deviations coincide with input stdiv
# if correlation=0, otherwise there is some deviation from input stdiv.
stdeviations=np.sqrt(variances)
# Draw m random samples from a normal (Gaussian) distribution.
a1=np.random.normal(0,stdeviations[0],self.a_size)
a2=np.random.normal(0,stdeviations[1],self.a_size)
A=np.array([a1,a2])
return A
def get_E(self):
# DESCRIPTION
# Generate matrix E,using
# eigenvectors of covariance matrix.
return self.get_eigen()[1]
def get_Mu(self):
# DESCRIPTION
# Generate matrix Mu, containing two
# arrays of mean values of shape corresponding to
# size of arrays of independent random samples - a_size
mu1=np.full((1,self.a_size),means[0])
mu2=np.full((1,self.a_size),means[1])
Mu=np.array([mu1[0],mu2[0]])
return Mu
def calc_X(self):
E = self.get_E()
A = self.get_A()
Mu = self.get_Mu()
X=np.dot(E,A)+Mu
return X
def plot_PDF_hist(self):
X=self.calc_X()
fig=plt.figure(figsize=(12,10))
plt.hist2d(X[0],X[1],bins=int(self.a_size/10))
plt.title('Joint PDF/2 random variables/{} samples, correlation={}'.format(self.a_size,self.correlation),fontsize=20)
plt.xlabel('X1')
plt.ylabel('X2')
plt.colorbar()
plt.show()
# INPUT VARAIABLES
# mean array
mu1=50
mu2=40
means=np.array([mu1,mu2])
# variances array
var1=400
var2=500
variances=np.array([var1,var2])
# correlation [-1;1]
corr1=0.5
# size of vector a (m elements)
a_size=1000
PDF_obj1=PDF(means,variances,corr1,a_size)
PDF_obj1.plot_PDF_hist()
# change correlation to -0.5
corr2=-0.5
PDF_obj2=PDF(means,variances,corr2,a_size)
PDF_obj2.plot_PDF_hist()
# change correlation to 0
corr3=0.0
PDF_obj3=PDF(means,variances,corr3,a_size)
PDF_obj3.plot_PDF_hist()
# CONCLUSION
# the maps looks exactly how I would expect them to see, considering mean and correlation values
|
90fdca302f36aabd3a9e68b74401cc81b4b37339 | jamesilloyd/robot_lab_inspection | /classification.py | 6,753 | 3.59375 | 4 | import numpy as np
from cv2 import cv2
from matplotlib import pyplot as plt
import thresholding
import part
from mpl_toolkits.mplot3d import Axes3D
'''
partClassification is used to classify all the parts within a cropped image.
It's inputs are:
-img_bgr = the cropped image to be classified
-show = whether to show results using matplotlib (for debugging)
-isCurves = to create the correct part type object that will inherit the correct classification metric ranges
-isMoving = same as above (can have different part objects: static straight, static curve, moving straight, moving curve)
'''
def partClassification(img_bgr, show = False, isCurves = True,isMoving = False):
# Prepare the position results to be used to save in csv
resultsVision = {"0":{'QCPassed': False, 'reason' : 'No part found'},
"1":{'QCPassed': False, 'reason' : 'No part found'},
"2":{'QCPassed': False, 'reason' : 'No part found'},
"3":{'QCPassed': False, 'reason' : 'No part found'},
"4":{'QCPassed': False, 'reason' : 'No part found'},
"5":{'QCPassed': False, 'reason' : 'No part found'},
"6":{'QCPassed': False, 'reason' : 'No part found'},
"7":{'QCPassed': False, 'reason' : 'No part found'},
"8":{'QCPassed': False, 'reason' : 'No part found'},
"9":{'QCPassed': False, 'reason' : 'No part found'},
"10":{'QCPassed': False, 'reason' : 'No part found'},
"11":{'QCPassed': False, 'reason' : 'No part found'}}
# Prepare the position results to be sent to plc
resultsPLC = {"0":False,
"1":False,
"2":False,
"3":False,
"4":False,
"5":False,
"6":False,
"7":False,
"8":False,
"9":False,
"10":False,
"11":False}
# prepare variables for graph title
passedCount = 0
failedCount = 0
# Change to rgb for plotting purposes
img_rgb = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2RGB)
# Get the image height and width to help map part positions to results grid
imageHeight , imageWidth = img_bgr.shape[:2]
# Convert the image to gray prepare for thresholding
img_gray = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2GRAY)
# Carry out otsu thrsholding on the cropped gray image
parts = thresholding.otsuThresholding(img_gray, isCurved = isCurves,isMoving = isMoving)
# Sort parts by position in the grid (Top left to right)
parts.sort(key=lambda x: x.centreXY[0], reverse=False)
parts.sort(key=lambda x: x.centreXY[1], reverse=False)
# Iterate through the list of parts
for j, piece in enumerate(parts):
# This code finds the part index within the results grid dictionary to be marked as good
resultIndex = 0
PLCIndex = 0
# This variable is used to capture any contours we may have accidentally captured on the edge of the image
validPart = True
# Find the correct index the piece corresponds to (PLC indexes columns then rows)
if(piece.centreXY[0]/imageWidth < 0.05):
validPart = False
elif(piece.centreXY[0]/imageWidth < 0.33):
# print('x1')
resultIndex += 0
PLCIndex += 0
elif(piece.centreXY[0]/imageWidth < 0.66):
# print('x2')
resultIndex += 1
PLCIndex += 4
elif(piece.centreXY[0]/imageWidth < 0.95):
# print('x3')
resultIndex += 2
PLCIndex += 8
else:
validPart = False
if(piece.centreXY[1]/imageHeight < 0.05):
validPart = False
elif(piece.centreXY[1]/imageHeight < 0.25):
# print('y1')
resultIndex += 0
PLCIndex += 0
elif(piece.centreXY[1]/imageHeight < 0.5):
# print('y2')
resultIndex += 3
PLCIndex += 1
elif(piece.centreXY[1]/imageHeight < 0.75):
# print('y3')
resultIndex += 6
PLCIndex += 2
elif(piece.centreXY[1]/imageHeight < 0.95):
# print('y4')
resultIndex += 9
PLCIndex += 3
else:
validPart = False
if(validPart):
# The object is automatically QC checked on initialisation
# Mark the QC result on the output dictionary
resultsVision[str(resultIndex)]["QCPassed"] = piece.isQCPassed
resultsVision[str(resultIndex)]["reason"] = piece.reasonForFailure
resultsPLC[str(PLCIndex)] = piece.isQCPassed
else:
resultIndex = 'N/A'
# Plot the contours, part number, and centre point
cv2.drawContours(img_rgb, [piece.contour], -1, (0,0,255), 2)
cv2.drawContours(img_rgb,piece.childContours,-1,(0,0,255), 1)
# TODO: edit this to just show the part number after debugging
cv2.putText(img_rgb ,"{0} - {1}".format(resultIndex,piece.reasonForFailure),piece.centreXYText,cv2.FONT_HERSHEY_SIMPLEX ,0.3,(0,255,0),1,cv2.LINE_AA)
cv2.circle(img_rgb,piece.centreXY, 3, (255,0,0), -1)
# Get the bounding rectangle to be plotted after we have identified the part as good or bad
rect = cv2.minAreaRect(piece.contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
if piece.isQCPassed:
cv2.drawContours(img_rgb,[box],0,(0,255,0),1)
passedCount += 1
# This is for debugging
print('Part {3}, Aspect Ratio {0}, Solidity {1}, Area/Perimeter {2}, Reason {4}'.format(piece.aspectRatio,piece.solidity,piece.areaPerimeterSqr,resultIndex,piece.reasonForFailure))
elif(validPart):
cv2.drawContours(img_rgb,[box],0,(255,0,0),1)
failedCount += 1
# This is for debugging
print('Part {3}, Aspect Ratio {0}, Solidity {1}, Area/Perimeter {2}, Reason {4}'.format(piece.aspectRatio,piece.solidity,piece.areaPerimeterSqr,resultIndex,piece.reasonForFailure))
# Only use this line for debugging
#if(piece.reasonForFailure == "Unknown Failure Reason"): show = True
# Show resuts
if(show):
plt.figure(figsize = (7,7))
plt.title('Count: {0} - {1} Passed - {2} Failed'.format(len(parts),passedCount,failedCount))
plt.imshow(img_rgb)
plt.axis('off')
plt.show()
# Send back the classified image to also save for assessment
img_classified = cv2.cvtColor(img_rgb,cv2.COLOR_RGB2BGR)
return resultsVision, resultsPLC, img_classified |
351c73d47838d5e027952f2bcfad6e5f3b439fcc | safa-6/DSCGaziOdevSenligi | /problemset4safaözer.py | 211 | 3.796875 | 4 | #Safa Özer
x= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x)
for i in x:
if(i % 2) == 0:
i= False # print(i, "Cift Sayidir.")
elif(i % 2) == 1:
i= False
else:
print(max(x))
|
1f265b5316c3cd5fd6f103c8cac60a75584e01b3 | Lee8150951/Python-Learning | /day05/01-OperateDictionary.py | 575 | 4.375 | 4 | # P88练习
# 练习6-1
man = {
'first_name': 'Jacob',
'last_name': 'Lee',
'age': 22,
'city': 'Shanghai'
}
print(man)
# 练习6-2 略
# 练习6-3
python = {
'dictionary': 'it can store many Key/value pairs',
'list': 'it can store many data, but they can be changed',
'tuple': 'it can store many data, and they can\'t be changed'
}
dictionary = python.get('dictionary', 'can\' find')
list = python.get('list', 'can\' find')
tuple = python.get('tuple', 'can\' find')
print(f"dictionary=>{dictionary}")
print(f"list=>{list}")
print(f"tuple=>{tuple}") |
9ad344b78580699941bee4bf63239492d1b69d85 | Lee8150951/Python-Learning | /day07/03-Return.py | 835 | 4.15625 | 4 | # P127练习
# 练习8-6
def city_country(city, country):
conclusion = f"{city.title()}, {country.title()}"
return conclusion
info = city_country("Santiago", "Chie")
print(info)
info = city_country("Shanghai", "China")
print(info)
info = city_country("Tokyo", "Japan")
print(info)
# 练习8-7
def make_album(singer_name, album_name, count):
album = {
"singer_name": singer_name,
"album_name": album_name,
"count": count
}
return album
album = make_album("Jay Chou", "Mdm Yeh Huimei", 20)
print(album)
# 练习8-8
while True:
singer_name = input("Singer\'s Name: ")
album_name = input("Album\'s Name: ")
count = input("Album\'s count: ")
album = make_album(singer_name, album_name, count)
quit = input("Do you want to quit(y/n): ")
print(album)
if quit == "y":
break |
09c6efc1ed4e0d774b72dd47d4df3f95a72d2287 | s444427/Algorithms---Tasks-from-sites | /DONE/Dywan.py | 299 | 3.546875 | 4 | # https://adjule.pl/groups/ogolny/problems/mwpz2014y
# solution by Paweł Lewicki
if __name__ == '__main__':
count = input();
for i in range(0,int(count)):
mylist = input()
newlist = mylist.split(' ')
mytuple = tuple(newlist)
print(int(mytuple[0]) * int(mytuple[1])) |
301f738c7aa181ac3535e21f24f2609dd69bc152 | s444427/Algorithms---Tasks-from-sites | /DONE/Liczby pierwsze.py | 509 | 3.75 | 4 | # https://pl.spoj.com/problems/PRIME_T/
# solution by Paweł Lewicki
import math
if __name__ == '__main__':
x = int(input())
for j in range(0, x):
n = int(input())
isPrime = 0
if n == 1:
isPrime = 1
elif n == 2:
isPrime = 0
else:
for i in range(2, math.ceil(math.sqrt(n)+1)):
if n % i == 0:
isPrime = 1
if isPrime == 0:
print("TAK")
else:
print("NIE")
|
40f3e8dd0591c6fd6209b9ce1e52a8407f009047 | will-jac/sl_arrhythmia | /neuron.py | 2,600 | 3.546875 | 4 | import numpy as np
# Ideas for development / different options:
#
# Type of NN:
# - Recurrent
# - Feedforward
#
# Type of activation
# - ReLU
#
# Loss function
# - MSE
#
# Type of backpropogation
# - ?
#
# Meta-parameters
# - Input / output layer sizes
#
# basic code
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def initialize_with_zeros(dim):
w = np.zeros(shape=(1, dim))
b = 0
assert(w.shape == (1, dim))
assert(isinstance(b, float) or isinstance(b, int))
return w, b
def propogate(w, b, X, Y):
m = X.shape[0]
# print(m)
print(X.shape, w.shape)
# forward prop
A = sigmoid(np.dot(X, w.T) + b)
# print(A)
# print(Y.shape)
# print(A.shape)
# print((Y * np.log(A)).shape)
cost = (-1/m) * np.sum(Y * np.log(A) + (1-Y) * (np.log(1-A)))
# backward prop
dw = (1/m) * np.dot((A-Y).T, X)
db = (1/m) * np.sum(A-Y)
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
return dw, db, cost
def optimize(w, b, X, Y, num_iterations, learning_rate):
costs = []
for i in range(num_iterations):
# cost and gradient calculation
dw, db, cost = propogate(w, b, X, Y)
# update rule
w -= learning_rate * dw
b -= learning_rate * db
# record costs
if i % 100 == 0:
costs.append(cost)
print('Cost after iteration %i: %f' % (i,cost))
return w, b, dw, db, costs
def predict(w, b, X):
m = X.shape[0]
Y_prediction = np.zeros((m,1))
w = w.reshape(1, X.shape[1])
# probability vector
A = sigmoid(np.dot(w.T, X) + b)
for i in range(A.shape[0]):
Y_prediction[0,i] = 1 if A[0,i] > 0.5 else 0
assert(Y_prediction.shape == (m, 1))
return Y_prediction
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5):
print(X_train.shape)
w, b = initialize_with_zeros(X_train.shape[1])
# gradient descent
w, b, dw, db, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate)
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
print('train: {} %'.format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print('train: {} %'.format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
if __name__ == "__main__":
import preprocess
data = preprocess.process_data()
[test, train] = preprocess.partition_data(data, [0.2,0.8])
model(train[:,0:-1],train[:,-1],test[:,0:-1],test[:,-1], 2000, 0.005)
|
584f92c81ac9f745e10411691a455dbc3a1e2aef | rpytel1/clickbait-challenge | /feature_extraction/services/slang_service.py | 1,489 | 3.671875 | 4 | import nltk
from nltk import word_tokenize
with open("../feature_extraction/resources/slang_words.txt", encoding="utf-8") as f:
content = f.readlines()
slang_list = [x.strip() for x in content]
# function checking for presence of slang words in a text
def calculate_num_slang_words(text):
if text == "":
return 0
words = word_tokenize(text)
is_slang_list = [word in slang_list for word in words]
return is_slang_list.count(True)
# function calculating all slang words in an entry
def calculate_all_num_slang_words(entry):
slang_words_post_title = calculate_num_slang_words(entry["postText"][0])
slang_words_article_title = calculate_num_slang_words(entry["targetTitle"])
slang_words_post_desc = calculate_num_slang_words(entry["targetDescription"])
slang_words_post_keywords = calculate_num_slang_words(entry["targetKeywords"])
slang_words_post_captions = calculate_num_slang_words(" ".join(entry["targetCaptions"]))
slang_words_post_paragraphs = calculate_num_slang_words(" ".join(entry["targetParagraphs"]))
return [slang_words_post_title, slang_words_article_title, \
slang_words_post_desc, slang_words_post_keywords, slang_words_post_captions, slang_words_post_paragraphs]
def get_feat_names():
return "post_text_slang_words", "article_title_slang_words", "article_desc_slang_words", \
"article_keywords_slang_words", "article_captions_slang_words", \
"article_paragraphs_slang_words"
|
a18409893d7bf522e91091be92bbc46dbe4af198 | zhanghui0228/study | /python_Basics/basics/day09--tuple.py | 2,782 | 4.09375 | 4 | #元组(tuple)
'''
元组是"不可变"的列表(list)
元组使用小括号来进行表示
元组书写格式:
格式一: tup1 = ('abc', 'bcd', 123, 456)
格式二: tup2 = 'abc', 'bcd', 1, 2, 3
'''
#元组的读写
'''
元组的读取方式与列表读取的方式是相同的
元组创建完元素后,元素不允许修改,如果元组内持有列表,则元组内的列表可以被修改
元组允许使用"元组运算符"来进行创建新的元组 元组运算符同样适用于列表
'''
t1 = (['张三', 20, 2000], ['李四', 22, 2200])
#print(t1[0])
item = t1[0]
item[1] = 25
print(t1)
#使用“元组运算符”创建新的元组
new_tup1 = (1, 2, 3) + (4, 5, 6)
new_tup2 = ("i", 'love') * 2
new_tup3 = ('me',) * 2 #如果元组中只有一个元素时,必须在元素后面添加一个逗号,说明这是一个元组,否则python会将其看作一个字串串来进行运行
print(new_tup1)
print(new_tup2)
print(new_tup3)
#序列
'''
序列(sequence)是指”有序“的队列, 是一种数据结构的统称
符合以下两种即可称之为序列:
序列中的元素顺序按添加顺序排列;
序列中的数据是通过”索引“来进行获取的
序列包含的数据结构:
字符串(str)、列表(list)、元组(tuple)、数字序列(range)
数字序列(range):
用于表示数字序列,内容不可变
使用range()函数来进行创建
语法:
range(起始值,结束值) --左闭右开
'''
#range
r = range(1,10)
print(type(r), r)
r1 = r[8] #range取值
print(r1)
#设置range的步长(间隔)
r2 = range(1,10, 2)
print(r2[4])
#使用成员运算符进行判断
print(5 in r2)
print(6 in r2)
#打印斐波那契数列
result = []
for i in range(0,50):
if i == 0 or i == 1:
result.append(1)
else:
result.append(result[i - 2] + result[i - 1])
print(result)
#编程练习
'''
有四个数字1、2、3、4,能组成多少个互不相同且数字不重复的两位数
任务
1、 定义变量count,用于存放统计出所组成的两个数的个数
2、定义变量lst,用于存放组成后的两位数
'''
count = 0
for i in range(1,5):
for n in range(1,5):
if i != n:
count += 1
print(count)
#序列类型的互相转换
'''
list() 转换为列表
tuple() 转换为元组
join()、str() 转换为字符串
str()函数用于将单个数据转为字符串
join()函数用于对列表进行连接 --要求:必须所有元素都是字符串
'''
L1 = ['a', 'b', 'c']
#使用join函数将列表进行连接
print("".join(L1)) #""表示多个元素的分割符
print(",".join(L1)) |
3bed81d65c30f440ee3abd6106801608f9f7e72c | zhanghui0228/study | /python_Basics/memory/mem.py | 1,145 | 4.21875 | 4 | #内存管理机制 ----赋值语句内存分析
'''
使用id()方法访问内存地址
'''
def extend_list(val, l=[]):
print('----------------')
print(l, id(l))
l.append(val)
print(l, id(l))
return l
list1 = extend_list(10)
list2 = extend_list(12, [])
list3 = extend_list('a')
print(list1)
print(list2)
print(list3)
"""
垃圾回收机制:
以引用计数为主,分代收集为辅
如果一个对象的引用数为0,python虚拟机就会回收这个对象的内存
引用计数的缺陷是循环引用的问题
"""
class Test(object):
def __init__(self):
print("对象生成了:{}".format(id(self)))
def __del__(self):
print("对象删除了:{}".format(id(self)))
def f0():
'''自动回收内存'''
while True:
''' 不断产生对象,但不使用它 '''
c = Test()
def f1():
'''内存一直在被引用,不会被回收'''
l = []
while True:
c = Test()
l.append(c)
print(len(l))
if __name__ == '__main__':
#f0()
f1() #电脑内存不大的,不要一直运行此函数 |
9f90663477c36ddaff0bf19c432e0445a739f77d | zhanghui0228/study | /python_Basics/Association协程/asyncio_queue.py | 1,558 | 3.84375 | 4 | # 协程之间的数据通信
'''
嵌套调用 拿到另一个协程函数中的结果
'''
import asyncio
# async def compute(x, y):
# ''' 定义一个计算协程函数 '''
# print(' start compute {0} + {1} '.format(x, y))
# await asyncio.sleep(5)
# return x + y
#
#
# async def get_sum(x, y):
# ''' 获取compute协程函数中返回的结果 '''
# result = await compute(x, y)
# print('{0} + {1} = {2}'.format(x, y, result))
#
#
# def main():
# loop = asyncio.get_event_loop()
# loop.run_until_complete(get_sum(1, 5))
# loop.close()
#
#
# if __name__ == '__main__':
# main()
# print('*' * 60)
#---------------------------------------------------------------------------------------------------
'''
队列
'''
async def add(store, name):
''' 写入数据到队列 '''
for i in range(6):
#往队列中添加数字
await asyncio.sleep(3)
await store.put(i)
print('{2}-->add num ...{0}, size:{1}'.format(i, store.qsize(), name))
async def reduct(store):
''' 删除队列中的数据 '''
for i in range(12):
result = await store.get()
print('reduct num ...{0}, size:{1}'.format(result, store.qsize()))
def main():
store = asyncio.Queue(maxsize=6)
info_1 = add(store, 'info1')
info_2 = add(store, 'info2')
redu = reduct(store)
#创建协程队列
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(info_1, info_2, redu))
loop.close()
if __name__ == '__main__':
main()
|
86374990275c081632ef916b8c338c50611141c6 | zhanghui0228/study | /python_Basics/process进程/process_pool.py | 1,187 | 3.5625 | 4 | #进程池
'''
#now_process = current_process() #当前进程
'''
import time
from multiprocessing import current_process, Pool
def run(file_name, i):
'''
多线程执行的代码 ---写入文件
:param file_name: str 文件名称
:param i: int 写入的数字
:return:
'''
now_process = current_process()
with open(file_name, 'a+', encoding='utf-8') as f:
context = 'RUN process name :{name:>10}, pid:{pid:>10}, num :{num:>10}\n'.format(name=now_process.name, pid=now_process.pid, num=i)
f.write(context)
time.sleep(4)
print(context)
return 'pass'
def ProcessPool():
file_name = 'pool.txt'
#定义开启的进程池个数
pool = Pool(2)
for i in range(20):
#同步添加任务
#result = pool.apply(run, args=(file_name, i))
#异步添加任务
result = pool.apply_async(run, args=(file_name, i))
print('NUM:{0}-------INFO:{1}'.format(i, result)) #异步任务可以添加result.get(5) 设置超时时间,其效果与同步效果一样
#关闭进程池
pool.close()
pool.join()
if __name__ == '__main__':
ProcessPool() |
31918b42c7390832e1cfa859445bcb16c3a56d80 | sdbaronc/LaboratorioFuncionesRemoto | /a_power_b.py | 331 | 4.03125 | 4 |
while True:
a = int(input("ingrese la base del numero:"))
if a==0:
print("final del programa")
break
b = int(input("ingrese el exponente del numero: "))
def a_power_b(a, b):
prod = 1
for x in range(1, b + 1):
prod = prod * a
print(prod)
a_power_b(a , b ) |
50903c1ea22fd9f91f8afd8d5b804b9ddc457e69 | brianna219c/cssi-labs | /python/labs/functions-cardio/functionsCalculator.py | 274 | 3.828125 | 4 | print("Welcome to bri's calculator!")
num1 =int(raw_input("Give me a numnber:"))
num2 =int(raw_input("Give me another numnber:"))
def myAddFunction(add1, add2):
sum = add1 + add2
return sum
print(myAddFunction("Here is the sum:" + str(myAddFunction(num1, num2)))
|
137defbc2fbc8cd308d1fb892bfcce9f2f99498a | ola-lola/Python-Projects | /Hangman.py | 2,070 | 4.125 | 4 | import random
import time
from termcolor import colored
print("Hello there!")
time.sleep(1)
print("If you know some cities from Europe... ")
time.sleep(1)
print(colored("Let's play HANGMAN!", "green"))
time.sleep(1)
namey = input("What's your name?: ")
time.sleep(1)
print( "Hello " + namey + "!\n")
time.sleep(1)
print("Let's start a game!")
time.sleep(1)
print(colored("Please guess a one name of capital cities in Europe!", "green"))
cities = ("TIRANE","ANDORRA" , "VIENNA", "BAKU", "MINSK", "BRUSSELS", "SARAJEVO", "SOFIA", "ZAGREB", "PRAGUE",
"COPENHAGEN", "TALLINN", "HELSINKI", "PARIS", "TIBILISI", "BELGIA", "ATHENS", "BUDAPEST", "ROME",
"RIGA", "REYKJAVIK", "LUXEMBURG", "OSLO", "AMSTERDAM", "BELFAST", "WARSAW", "LISBON", "MOSCOW",
"EDINBURG", "BRATISLAVA", "MADRID", "STOCKHOLM", "KIEV", "LONDON", "BELGRADE")
letters_guessed_by_user = ''
attemps_left = 10
city = random.choice(cities)
print(city)
for char in city:
print("_ ", end = '' )
has_user_won = False
while attemps_left > 0 and not has_user_won :
print("\nPlease enter a letter or word: ")
letter = input("").upper() # .upper() - print only big letters
if len(letter) == 1 :
if letter in city:
letters_guessed_by_user += letter
everything_is_ok = True
for char in city:
if char in letters_guessed_by_user:
print(char, end = '')
else:
everything_is_ok = False
print("_ ", end= '')
if everything_is_ok == False:
has_user_won = False
else:
has_user_won = True
else:
attemps_left -= 1
print("Only", attemps_left , "attemps left!")
else:
if letter == city:
has_user_won = True
else:
attemps_left -= 1
print("Only", attemps_left , "attemps left!")
if has_user_won:
print(colored( "You won!", "red"))
else:
print(colored("You lost!", "red"))
|
425e31750033cc79b0f2dbb38457f9b41b1b5cf8 | jkohans/adventofcode2020 | /day15/day15.py | 1,339 | 3.640625 | 4 | def get_number(starting_numbers, turn):
num_starting_numbers = len(starting_numbers)
last_seen_idx = dict()
for i, num in enumerate(starting_numbers[: len(starting_numbers) - 1]):
last_seen_idx[num] = i
last_spoken = starting_numbers[-1]
for i in range(turn - len(starting_numbers)):
actual_turn_no = i + num_starting_numbers + 1
idx = find_last_mention(last_seen_idx, last_spoken)
# print("at turn", actual_turn_no)
# print("looking for", last_spoken)
# print("found at idx", idx)
if idx is None:
next_ = 0
else:
last_turn_spoken = idx + 1
# print("last spoken at turn", last_turn_spoken)
next_ = (actual_turn_no - 1) - last_turn_spoken
# print("number at this turn will be", next_)
# print("-----")
last_seen_idx[last_spoken] = actual_turn_no - 2
last_spoken = next_
return last_spoken
def find_last_mention(last_seen_idx, number):
# idx = None
#
# for i in range(len(numbers)-1, -1, -1):
# if numbers[i] == number:
# idx = i
# break
#
# return idx
return last_seen_idx.get(number, None)
if __name__ == "__main__":
# print(get_number([0,3,6], 10))
print(get_number([2, 0, 6, 12, 1, 3], 30000000))
|
71d63fd0763f47c13a70464065f6f9a29382e7aa | jkohans/adventofcode2020 | /day23/day23.py | 3,038 | 3.53125 | 4 | def pick3_ll(right_pointers, current_cup):
pick3 = []
next_ = right_pointers[current_cup]
for _ in range(3):
pick3.append(next_)
next_ = right_pointers[next_]
# chop out the picked list
right_pointers[current_cup] = next_
for label in pick3:
del right_pointers[label]
return pick3, right_pointers
def get_destination_ll(right_pointers, current_cup, min_, max_):
# need an efficient way to find min and max here
target = current_cup - 1
while target not in right_pointers:
if target < min_:
target = max_
break
target = target - 1
return target
def get_clockwise_order_after1_ll(right_pointers):
labels = []
ptr = right_pointers[1]
while ptr != 1:
labels.append(ptr)
ptr = right_pointers[ptr]
return labels
def initialize_right_pointers(cups):
right_pointers = {}
prev_cup = None
for cup in cups:
if not prev_cup: # first element
prev_cup = cup
else:
right_pointers[prev_cup] = cup
prev_cup = cup
right_pointers[prev_cup] = cups[0] # complete the circle
return right_pointers
def find_min_max(sorted_cups, pick3):
idx_min = 0
idx_max = len(sorted_cups) - 1
min_, max_ = sorted_cups[idx_min], sorted_cups[idx_max]
while min_ in pick3:
idx_min = idx_min + 1
min_ = sorted_cups[idx_min]
while max_ in pick3:
idx_max = idx_max - 1
max_ = sorted_cups[idx_max]
return min_, max_
if __name__ == "__main__":
# cups = [3, 8, 9, 1, 2, 5, 4, 6, 7]
cups = [3, 9, 8, 2, 5, 4, 7, 1, 6]
fill_size = 1000000
biggest = max(cups)
cups += list(map(lambda x: biggest + x, range(1, fill_size - len(cups) + 1))) # fill up to 1M
sorted_cups = sorted(cups)
right_pointers = initialize_right_pointers(cups)
# part 2:
# - one million cups! remaining cups are max+1, max+2, ... max+n
# - 10 million moves!
# - find two cups immediately clockwise of cup 1
i = 0
current_cup = cups[0]
while i < 10000000:
# print("*** move", i+1)
# print(right_pointers)
pick3, right_pointers = pick3_ll(right_pointers, current_cup)
# print("pick3", pick3)
min_, max_ = find_min_max(sorted_cups, pick3)
# find destination and insert, no need to shift
destination = get_destination_ll(right_pointers, current_cup, min_, max_)
# print("destination", destination)
old_dest_right_ptr = right_pointers[destination]
for label in pick3:
right_pointers[destination] = label
destination = label
right_pointers[pick3[2]] = old_dest_right_ptr
current_cup = right_pointers[current_cup]
i = i + 1
# print("finally", "".join(map(str, get_clockwise_order_after1_ll(right_pointers))))
after_one = right_pointers[1]
after_after_one = right_pointers[after_one]
print(after_one * after_after_one)
|
0e739fad9a189252d99c5614e30e545b7b06f3d0 | jkohans/adventofcode2020 | /day9/day9.py | 1,736 | 3.578125 | 4 | def find_first_invalid_number(numbers):
preamble_size = 25
for idx, number in enumerate(numbers[preamble_size:]):
offset_number = preamble_size + idx
prev_slice = numbers[offset_number - 25 : offset_number]
if not find_pairs(prev_slice, number):
return offset_number, number
def get_input(input_filename):
with open(input_filename) as f:
return [int(line.rstrip("\n")) for line in f]
def find_pairs(nums, target_sum):
nums.sort()
front_idx = 0
back_idx = len(nums) - 1
while front_idx < back_idx:
front_num = nums[front_idx]
back_num = nums[back_idx]
sum = front_num + back_num
if sum == target_sum:
return front_num, back_num
elif sum < target_sum: # go higher, from front
front_idx = front_idx + 1
else: # sum > target_sum, go lower from back
back_idx = back_idx - 1
return None
def find_contiguous_sum(target_sum, numbers):
current_start = 0
current_end = 1
current_sum = sum(numbers[current_start : current_end + 1])
while current_sum != target_sum:
if current_sum < target_sum: # less, so need to try adding a number
current_end = current_end + 1
else: # over, so need to remove the top
current_start = current_start + 1
current_sum = sum(numbers[current_start : current_end + 1])
return numbers[current_start : current_end + 1]
if __name__ == "__main__":
numbers = get_input("day9_input.txt")
offset_number, number = find_first_invalid_number(numbers)
contiguous_numbers = find_contiguous_sum(number, numbers)
print(min(contiguous_numbers) + max(contiguous_numbers))
|
d7b9399b86cde9cc79864ef7bdd42902adb98cb1 | alex00321/Python | /Self_learning/twolistmerge_algorithm.py | 1,706 | 3.671875 | 4 | from typing import Optional
class ListNode:
def __init__(self, val = None):
if isinstance(val, int):
self.val = val
self.next = None
elif isinstance(val, list):
self.val = val[0]
self.next = None
cur = self
for i in val[1:]:
cur.next = ListNode(i)
cur = cur.next
def gatherAttrs(self):
return ",".join("{}:{}".format(k,getattr(self,k)) for k in self.__dict__.keys())
def __str__(self):
return self.__class__.__name__+"{"+"{}".format(self.gatherAttrs())+"}"
"""
recursion
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode], carry =0)->Optional[ListNode]:
if l1 is None and l2 is None:
return ListNode(carry) if carry else None
if l1 is None:
l1, l2 = l2, l1
carry += l1.val + (l2.val if l2 else 0)
l1.val = carry%10
l1.next = self.addTwoNumbers(l1.next, l2.next if l2 else None, carry//10)
return l1
"""
class Solution:
def addTwoNumbers(self, l1:Optional[ListNode], l2:Optional[ListNode]) ->Optional[ListNode]:
cur = dummy = ListNode()
carry = 0
while l1 or l2 or carry:
carry += (l1.val if l1 else 0) + (l2.val if l2 else 0)
cur.next = ListNode(carry%10)
carry //=10
cur = cur.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy.next
if __name__ == "__main__":
l1 =ListNode([1,6,3])
l2 =ListNode([4,5,6])
sol = Solution()
temp = sol.addTwoNumbers(l1,l2)
print(temp)
|
6707c007958b3b6f89f507fb9e317983833b4598 | seanremenyi/Game-of-21 | /extras.py | 2,952 | 3.953125 | 4 | ###rules and instructions to be printed with the --help tag
def help():
print("""
Help
Objective
* The objective of the game is to reach 21 points or as close as possible without going over.
Rules
* The player is dealt 2 cards giving a certain total.
* The computer opponent known as the dealer is dealt 2 cards as well however only 1 is shown.
* The player can choose to Hit which will give him 1 more card and increase his total. The User can do this as many times as he wants until his hand is over 21 in which case he Busts and loses.
* The player has a further advantage that if he gets 21 in this phase will automatically win.
* If the player is happy with their hand and total they will choose to hold.
* Now it's the dealers turn and will also try to get as close to 21 without going over (can still go bust as well).
* If neither player busts or reaches 21 the two totals will be evaluated with the number closest to 21 winning, if the totals are equal, the winner will be whoever got there with the least amount of cards.
Instructions
* The game is commenced by going to the src folder and entering,
./main.py
* You will be asked if you want to play, input "yes" to continue or "no" to receive a goodbye message.
* A prompt will come to start the game, here the user may input anything and return to start.
* The game will deal the cards and the user can choose to hit by inputing "Hit" or "Hold" to hold. Any other input will ask the user to try again either of those 2 options.
* Again any key prompts are used for the user to continue the game and control the pacing.
* These prompts will be used to continue until the end of the game to reach the final count and winner declared.
* The running total of how many ames won each player has is displayed and the game will ask if a rematch is wanted.
* "yes" to play again or "no" for the goodbye message)
""")
return ""
### My secret message that will be displayed with the right flag
def secret():
print("""
Wow You Won 15 Games, You Must Like This Game, Well I Must Say
____ ____ ____ ____ ____ ____ ____ ____
| | | | | | | | | | | | | | | |
| C | | O | | N | | G | | R | | A | | T | | S |
|____| |____| |____| |____| |____| |____| |____| |____|
____
| |
| & |
|____|
____ ____ ____ ____ ____
| | | | | | | | | |
| T | | H | | A | | N | | K |
|____| |____| |____| |____| |____|
____ ____ ____
| | | | | |
| Y | | O | | U |
|____| |____| |____|
For Playing!
""")
return ""
|
9d997fb7a3c1963eaf32697e75007e0831cb6ce6 | tiaraprtw/basic-phyton | /string formating.py | 329 | 3.921875 | 4 | #untuk memasukan argumen, ditempatkan untuk mengisi string yg berisi {}
#sallary = 8
#txt = "my name is ara, and i want my sallary is {}".format(sallary)
#print(txt)
nama=str(input ("write your name here: "))
age= int(input("how old are you: "))
teks= "im {} and {} years old".format(nama,age)
#print(txt)
print(teks)
|
49f1d420b08fe1e6f67f2cf4f0de8a59ed0492c0 | surenderreddychitteddy/python_practice | /Netmiko_to_ssh.py | 1,290 | 3.53125 | 4 | import Netmiko
def ssh(device_type, ipaddress):
"""
This function is used for performing ssh to linux devices
:param device_type: The device for which you want to perform ssh login.
:param ipaddress: IP address of the device.
:return: connection | None
"""
try:
connection = netmiko.ConnectHandler(device_type='cisco_ios', host=ipaddress, username=DEVICE_LOGIN_USERNAME,
password=DEVICE_LOGIN_PASSWORD)
logging.info(f'Now we have logging into {device_type} {ipaddress}')
except netmiko.ssh_exception.SSHException as ssh_err:
logging.error("Issue observed with ssh to IP: %s - %s" % (ipaddress, str(ssh_err)))
return None
except netmiko.NetMikoAuthenticationException as auth_err:
logging.error("%s is not authorized to access device with IP: %s"
" - %s" % (os.environ["USER"], ipaddress, str(auth_err)))
return None
except netmiko.NetMikoTimeoutException as timeout_err:
logging.error("Device connection timeout - %s" % str(timeout_err))
return None
else:
return connection
connection = ssh('xyz device', '10.11.12.13')
if not connection:
pass
else:
'''Perform required action after logging into the device'''
|
8d1eb0a46803b18af195483c71ee52b14aa932c9 | xpqz/aoc-18 | /day9.py | 2,399 | 3.5625 | 4 | """
day 9 of Advent of Code 2018
by Stefan Kruger
Solution using actual linked list to avoid O(n) insertion behaviour that
cripples part 2.
An alternative approach could have used a deque:
https://stackoverflow.com/questions/39522787/time-complexity-of-random-access-in-deque-in-python
"""
from collections import Counter
from dataclasses import dataclass
from typing import Any
@dataclass
class Node:
item: int
left: Any = None
right: Any = None
start: bool = False
class CircularList:
def __init__(self):
self.cursor = None
self.scores = Counter()
def moveleft(self, steps):
for _ in range(steps):
self.cursor = self.cursor.left
def moveright(self, steps):
for _ in range(steps):
self.cursor = self.cursor.right
def insert_at_cursor(self, item):
node = Node(item)
if self.cursor is None:
node.left = node
node.right = node
node.start = True
self.cursor = node
return
node.right = self.cursor
node.left = self.cursor.left
# Single node
if self.cursor.start and self.cursor.right.start:
self.cursor.right = node
self.cursor.left.right = node
self.cursor.left = node
self.cursor = node
def remove_at_cursor(self):
item = self.cursor.item
is_start = self.cursor.start
self.cursor.left.right = self.cursor.right
self.cursor.right.left = self.cursor.left
self.cursor = self.cursor.right
self.cursor.start = is_start
return item
def place(self, player, marble):
if marble % 23 == 0:
self.moveleft(7)
removed = self.remove_at_cursor()
self.scores[player] += marble + removed
else:
self.moveright(2)
self.insert_at_cursor(marble)
def winner(self):
return self.scores.most_common(1)
if __name__ == "__main__":
circle = CircularList()
# Set the zero marble; does not belong to a player
circle.insert_at_cursor(0)
marble = 1
max_marble = 71588 # * 100 # Part2: times 100
while marble < max_marble:
for player in range(430):
circle.place(player, marble)
marble += 1
if marble > max_marble:
break
print(circle.winner())
|
1c69dac16dd39b6e774dcc2b0574b40ebf08d76b | hwpvanholsteijn/SmartPug | /Servo/servo.py | 905 | 3.65625 | 4 | #!/usr/bin/python
import wiringpi
import time
# ====== VARIABLES ====== #
delay_period = 0.01
# ====== FUNCTIONS ====== #
# Set pins to PWM mode and set frequency
# - https://learn.adafruit.com/adafruits-raspberry-pi-lesson-8-using-a-servo-motor/software
def init():
# use 'GPIO naming'
wiringpi.wiringPiSetupGpio()
# set #18 to be a PWM output
wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT)
# set the PWM mode to milliseconds stype
wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
# divide down clock
wiringpi.pwmSetClock(192)
wiringpi.pwmSetRange(2000)
print "Initialized servo at 18 in PWM mode"
def sweep():
print "Bark bark!"
# Rotate cw
for pulse in range(50, 250, 1):
wiringpi.pwmWrite(18, pulse)
time.sleep(delay_period)
# Rotate ccw
for pulse in range(250, 50, -1):
wiringpi.pwmWrite(18, pulse)
time.sleep(delay_period)
|
d49c03a009a1bffc88273c17230453a1ee7ecd01 | AtulSinghTR/AtulSinghTR | /exercism-py/python/raindrops/raindrops.py | 261 | 3.734375 | 4 | def convert(number):
sound=''
if number%3==0:
sound='Pling'
if number%5==0:
sound=sound+'Plang'
if number%7==0:
sound=sound+'Plong'
if len(sound)==0:
sound=str(number)
return sound
|
82fbd2329d3cb784b37943f7845808dbd8eee886 | AtulSinghTR/AtulSinghTR | /exercism-py/python/scrabble-score/scrabble_score.py | 319 | 3.890625 | 4 | def score(word):
marks = {'1':['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'], '2':['D', 'G' ], '3': ['B', 'C', 'M', 'P'], '4': ['F', 'H', 'V', 'W', 'Y'], '5': ['K'], '8': ['J', 'K'], '10': ['Q','Z']}
print(marks.values())
if 'A' in marks.values():
print('exists')
print(score('ABCD')) |
9c88249c564273d910853815b5465518be5be476 | AtulSinghTR/AtulSinghTR | /python/tuple-dicts.py | 2,122 | 3.671875 | 4 | import sys
x=(1)
print(type(x))
x=(1,)
print(type(x))
# Common array func work with tuple also
tup_1=(1,2,3,4,5)
print('length:', len(tup_1))
print('Slicing:', tup_1[:2])
# tuples are immutables
try:
tup_1[0] = 9
# except:
# print(sys.exc_info()[0], sys.exc_info()[1])
except Exception as e:
print(e)
# tuples are iterables
for i in tup_1:
print(i, end=' ')
# Packing and Unpacking of tuples
tup_2 = 6, 9, 8
print(tup_2)
print(type(tup_2))
a,b,c = tup_2
print(a,b,c)
print(type(a))
# Exer
cardinal_numbers= "first", "second" , "third"
print(cardinal_numbers[1])
pos1, pos2, pos3 = cardinal_numbers
'2nd' in cardinal_numbers
print(cardinal_numbers[1:])
###
### List
###
universities = [
['California Institute of Technology', 2175, 37704],
['Harvard', 19627, 39849],
['Massachusetts Institute of Technology', 10566, 40732],
['Princeton', 7802, 37000],
['Rice', 5879, 35551],
['Stanford', 19535, 40569],
['Yale', 11701, 40500]
]
def enrollment_stats(university):
student_enrolled=[]
tuition_fees=[]
for un in university:
student_enrolled.append(un[1])
tuition_fees.append(un[2])
return student_enrolled,tuition_fees
def mean(lst):
return sum(lst) / len(lst)
#def median(lst):
enroll,fee = enrollment_stats(universities)
print(f"Total Students: {sum(enroll):,}")
print(f"Total Tuition: $ {sum(fee):,}")
print(f"Students Mean: {mean(enroll):,.2f}")
#========
Nouns=["fossil", "horse", "aardvark", "judge", "chef", "mango", "extrovert", "gorilla"]
Verbs= ["kicks", "jingles", "bounces", "slurps", "meows", "explodes", "curdles"]
Adjectives= ["furry", "balding", "incredulous", "fragrant","exuberant", "glistening"]
Prepositions= ["against", "after", "into", "beneath", "upon", "for", "in", "like", "over", "within"]
Adverbs= ["curiously", "extravagantly", "tantalizingly", "furiously", "sensuously"]
import random
def random_char(choice):
return random.choice(choice)
print(f"A {adj1} {noun1}")
print(f"{A/An} {adj1} {noun1} {verb1} {prep1} the {adj2} {noun2}")
print(f"{adverb1}, the {noun1} {verb2}")
print(f"the {noun2} {verb3} {prep2} a {adj3} {noun3}")
|
f8da1e91278146bc58125352cbbeacd0a11827b5 | stephenjkaplan/mta-data-analysis | /data_visualization_utilities.py | 2,663 | 3.734375 | 4 | """
This file contains all utility functions used in the "Data Analysis & Visualization" Notebook
Stephen Kaplan, 2020-07-05
"""
import matplotlib.pyplot as plt
import seaborn as sns
def get_top_stations_by_total_traffic(df, num_stations=10):
"""
Returns a DataFrame containing the busiest stations by total traffic.
:param pandas.DataFrame df: MTA turnstile data. Must contain columns STATION and TOTAL_TRAFFIC.
:param int num_stations: Number of busiest stations to return. Defaults to 10.
:return: DataFrame containing the top n busiest stations.
:rtype: pandas.DataFrame
"""
# aggregate total traffic for each station and sort in descending order
df_grouped_by_stations = df.groupby('STATION', as_index=False).sum()
df_stations_ranked = df_grouped_by_stations.sort_values('TOTAL_TRAFFIC', ascending=False)
return df_stations_ranked[0:num_stations]
def prepare_mta_data_for_heatmap(df):
"""
Prepares MTA turnstile data to plot a heatmap of traffic at different stations during different times of day.
:param pandas.DataFrame df: Contains columns STATION, DATE, TIME_BIN, TOTAL_TRAFFIC, TIME
:return: DataFrame with average traffic by 3-hour time increments.
:rtype: pandas.DataFrame
"""
# total entries at each station on each date for each 3-hr timespan
hour_bin_sum = df.groupby(['STATION', 'DATE', 'TIME_BIN']).agg({'TOTAL_TRAFFIC': 'sum'})
hour_bin_sum.reset_index(inplace=True)
# Use amounts above to calculate the average entries in each 3-hr timespan at each station
hourly_avg_df = hour_bin_sum.groupby(['TIME_BIN', 'STATION']).agg({'TOTAL_TRAFFIC': 'mean'})
hourly_avg_df.reset_index(inplace=True)
# Put data in hourly_avg_df in format conducive for line plots
df_heatmap = hourly_avg_df.pivot_table(index='STATION', columns='TIME_BIN', values='TOTAL_TRAFFIC')
return df_heatmap
def plot_busy_times_heatmap(df, title):
"""
Plots a heatmap of the average busiest time spans at a given set of stations.
:param df: DataFrame that has been prepared by the function prepare_mta_data_for_heatmap
:param str title: Plot title.
"""
plt.figure(figsize=(16, 12))
sns.heatmap(df, vmin=2500, vmax=40000, cbar_kws={'label': 'Avg Total Traffic'})
plt.xlabel('3-Hour Windows', fontsize=14)
plt.ylabel('Stations', fontsize=14)
plt.title(title, fontsize=20)
plt.xticks([0, 1, 2, 3, 4, 5, 6, 7, 8],
['12:00am - 3:00am', '3:00am - 6:00am', '6:00am - 9:00am', '9:00am - 12:00pm',
'12:00pm - 3:00pm', '3:00pm - 6:00pm', '6:00pm - 9:00pm', '9:00pm - 12:00am'],
rotation=45)
|
508f8733c7a928faa06ef664b232f5d81aaf3460 | yaroslavtsepkov/chord-alg | /main.py | 1,005 | 3.609375 | 4 | from typing import *
from chord_node import ChordNode
def stabilize_and_print(nodes: List[ChordNode]):
print('**************************')
for i in range(10):
for node in nodes:
node.stabilize()
node.fix_fingers()
for node in nodes:
print(node)
print('**************************')
if __name__ == "__main__":
m: int = 3
nodes: List[ChordNode] = []
head: ChordNode = ChordNode(3, 0)
head.join(None)
nodes.append(head)
for n in [1, 3]:
node: ChordNode = ChordNode(m, n)
node.join2(head)
nodes.append(node)
stabilize_and_print(nodes)
print("stabilize... until append\n")
six_node: ChordNode = ChordNode(m, 6)
six_node.join2(head)
nodes.append(six_node)
print("stabilize... before append\n")
stabilize_and_print(nodes)
six_node._delete()
nodes.remove(six_node)
print("stabilize... before remove\n")
stabilize_and_print(nodes)
print("done") |
275c0320c0858b5ffd852e69191fe0dcc50f5ebf | arneger/english-anagram-translator | /anagram_program.py | 4,266 | 3.640625 | 4 | from nltk.corpus import words
from tkinter import *
import random
# Function that takes the user-input and checks if there's english words from
# the nltk words list that got the exact same characters as the input.
def anagram_matcher():
output_word2.config(state=NORMAL)
output_word2.delete(0.0, END)
output_word2.config(state=DISABLED)
the_anagram = input_word2.get("1.0", "end-1c")
characters = the_anagram.lower()
if len(characters.split()) > 1:
output_word2.config(state=NORMAL)
output_word2.insert(END, " Type only a single word.")
output_word2.config(state=DISABLED)
else:
try: #A try except. If the code doesn't run it's probably because nltk words is not installed (Check README)
english_words = words.words()
for word in english_words:
if sorted(word) == sorted(characters):
output_word2.config(state=NORMAL)
output_word2.insert(END, "\n " + word)
output_word2.config(state=DISABLED)
else:
pass
except:
output_word2.config(state=NORMAL)
output_word2.insert(END, "Error: Check the README")
output_word2.config(state=DISABLED)
# Function that generates an anagram from the given user input.
def anagram_generator():
output_word1.config(state=NORMAL)
output_word1.delete(0.0, END)
output_word1.config(state=DISABLED)
the_word = input_word1.get("1.0", "end-1c")
if len(the_word.split()) > 1:
output_word1.config(state=NORMAL)
output_word1.insert(END, " Type only a single word.")
output_word1.config(state=DISABLED)
else:
anagram_list = list(the_word.lower())
random.shuffle(anagram_list)
new_anagram = "".join(anagram_list)
output_word1.config(state=NORMAL)
output_word1.insert(END, " " + new_anagram)
output_word1.config(state=DISABLED)
# The GUI
window = Tk()
canvas = Canvas(height=650, width=800, bg="#0d0d0d")
canvas.pack()
window.title("Anagramify")
window.resizable(False,False)
#Mid-frame 1
mid_frame1 = Frame(window, bg="#1a1a1a", bd=10)
mid_frame1.place(relx=0.5, rely=0.08, relwidth=0.7, relheight=0.3, anchor="n")
input_label = Label (mid_frame1, text="Word", bg="#1a1a1a", fg="white", font="arial 15 bold")
input_label.place(relx=0.12, rely=0.15, relwidth=0.2, relheight=0.2)
input_word1 = Text(mid_frame1, font="none 15 bold", bg="#0d0d0d", fg="white", state=None)
input_word1.place(relx=0.02, rely=0.35, relwidth=0.4, relheight=0.3)
translate_button1 = Button(mid_frame1, text=u"\u2b9e", bg="#1a1a1a", fg="white", font="none 15 bold", command=anagram_generator)
translate_button1.place(relx=0.451, rely=0.35, relwidth=0.1, relheight=0.31)
output_label1 = Label (mid_frame1, text="Anagram", bg="#1a1a1a", fg="white", font="arial 15 bold")
output_label1.place(relx=0.68, rely=0.15, relwidth=0.2, relheight=0.2)
output_word1 = Text(mid_frame1, font="none 12 bold", bg="#0d0d0d", fg="white", state=DISABLED)
output_word1.place(relx=0.58, rely=0.35, relwidth=0.4, relheight=0.3)
#mid-frame 2
mid_frame2 = Frame(window, bg="#1a1a1a", bd=10)
mid_frame2.place(relx=0.5, rely=0.4, relwidth=0.7, relheight=0.52, anchor="n")
input_label2 = Label (mid_frame2, text="Anagram", bg="#1a1a1a", fg="white", font="arial 15 bold")
input_label2.place(relx=0.12, rely=0.23, relwidth=0.2, relheight=0.2)
input_word2 = Text(mid_frame2, font="none 15 bold", bg="#0d0d0d", fg="white")
input_word2.place(relx=0.02, rely=0.4 , relwidth=0.4, relheight=0.17)
translate_button2 = Button(mid_frame2, text=u"\u2b9e", bg="#1a1a1a", fg="white", font="none 15 bold", command=anagram_matcher)
translate_button2.place(relx=0.451, rely=0.4, relwidth=0.1, relheight=0.175)
output_label2 = Label (mid_frame2, text="Anagram Matches", bg="#1a1a1a", fg="white", font="arial 15 bold")
output_label2.place(relx=0.585, rely=0.03, relwidth=0.4, relheight=0.1)
output_word2 = Text(mid_frame2, font="none 12 bold", bg="#0d0d0d", fg="white", state=DISABLED)
output_word2.place(relx=0.58, rely=0.15 , relwidth=0.4, relheight=0.7)
window.mainloop() |
029f12d5b321a2a7bec86797ea11acd06b8d7bf2 | rf2046/python-course | /fizzbuzz/fizzbuzz.py | 197 | 3.75 | 4 | count = 0
while (count < 100):
if count%15==0:
print ("fizzbuzz")
elif count%3==0:
print ("fizz")
elif count%5==0:
print ("buzz")
else: print ("%d" % (count))
count += 1 |
e06f6aac1d590e16acf26a36f19112d250580300 | gareia/DataStructures | /Hackerrank/PreorderTraversal.py | 529 | 3.84375 | 4 | """
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def preOrder(root):
print(preOrderHelper(root))
def preOrderHelper(root):
if(root):
result = str(root.info) + " "
#print(result)
result += preOrderHelper(root.left)
result += preOrderHelper(root.right)
return result
return ""
#MAIN
#input
#n[1-500] nodes in the tree
#output
#inline space-separated string tree's preorder traversal |
ebf4fae9e217276076c8cdcee0f074e2fe827c6e | gareia/DataStructures | /Hackerrank/ReverseArray.py | 335 | 3.546875 | 4 |
def reverseArray(a):
pos0 = 0
posF = len(a)-1
while(pos0 < posF): #O(n/2) => O(n)
aux = a[pos0]
a[pos0] = a[posF]
a[posF] = aux
pos0 += 1
posF -= 1
return a
#MAIN
# INPUT a: array n: len(a)
# n [1-10^3]
# a[i] [1-10^4]
# reverseArray(a) call
# OUTPUT reversed array |
d688bf04940a7684ac77cff9666bb67d402d1f5d | sheilazpy/ML-AndrewNg | /ex1-python/gradientDescent.py | 1,047 | 3.9375 | 4 | ##############################################
# Author: Jivitesh Singh Dhaliwal
# Date: 07-11-2013
# Description:Gradient Descent Algorithm
# without regularization
##############################################
from computeCost import *
def gradientDescent(X, y, theta, alpha, numIter):
''' Perform Linear Regression using Gradient Descent'''
costHistory = [0]
m = len(X) # Number of training examples
for i in range(numIter):
temp = theta[:] # Copy theta vector to a temporary vector for update
temp = (X.T.dot((X.dot(theta) - y))) # Performing the entire operation of grad des using
# matrix multiplication
theta = theta - ((alpha/ m) * temp)
costHistory.append(computeCost(X, y, theta, m))
if costHistory[-1] > costHistory[-2]:
print 'Cost is not converging. Please check alpha. Exiting'
break
return theta
|
2dbb417f34777ae77b8b5ca45e652f8c71df5806 | sheilazpy/ML-AndrewNg | /ex2-python/gradientFunction.py | 544 | 3.546875 | 4 | ################################################
# Author: Jivitesh Singh Dhaliwal
# Date: 09-11-2013
# Program: Compute Cost for Logistic Regression
################################################
from computeCost import *
def gradientFunction(X, y, theta, alpha, numIter):
'''Return the gradient for given hypothesis function
@Params: X, y, theta'''
costHistory = [0]
m = len(X) # Number of training examples
for i in range(numIter):
return (1/m) * sum((X.T.dot(X.dot(theta) - y)))
|
f1922a5f7e6139b3909e0c804c6277d66e44f314 | AliAldobyan/queues-data-structure | /queues.py | 2,407 | 4.15625 | 4 | class Node:
def __init__(self, num_of_people, next = None):
self.num_of_people = num_of_people
self.next = next
def get_num_of_people(self):
return self.num_of_people
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class Queue:
def __init__(self, limit=20, front=None, back=None):
self.front = front
self.back = back
self.limit = limit
self.length = 0
self.waiting_time = 0
def is_empty(self):
return self.length == 0
def is_full(self):
return self.length == self.limit
def peek(self):
return self.front
def insert_node(self, number_of_people):
new_node = Node(number_of_people)
if self.is_empty():
self.front = new_node
else:
self.back.set_next(new_node)
self.back = new_node
self.length += 1
self.waiting_time += (30 * number_of_people)
def enqueue(self, num_of_people):
max_num = 12
num_of_people = int(num_of_people)
if self.is_full():
print("Sorry, can you wait? the queue to see the amusement park is full!")
else:
if num_of_people > 12:
while num_of_people > max_num:
num_of_people = num_of_people - max_num
self.insert_node(max_num)
self.insert_node(num_of_people)
def dequeue(self):
if self.is_empty():
print("Queue is Empty!")
else:
node_to_remove = self.front
self.front = node_to_remove.get_next()
self.length -= 1
self.waiting_time -= 30 * node_to_remove.get_num_of_people()
return f"The size of the group that went into the ride: {node_to_remove.get_num_of_people()}"
def get_waiting_time(self):
if self.waiting_time > 59:
return f"The waiting time for the queue is: {int(self.waiting_time / 60)} minutes"
else:
return f"The waiting time for the queue is: {int(self.waiting_time)} seconds"
visitors = Queue()
print("-"*45)
print(visitors.get_waiting_time())
print("-"*45)
visitors.enqueue(4)
visitors.enqueue(12)
visitors.enqueue(18)
print("-"*45)
print(visitors.get_waiting_time())
print(visitors.dequeue())
print(visitors.get_waiting_time())
print("-"*45)
|
7ff6d894cb5fd11ebc5e67f8e8b54113cd5865cc | MdNaina/python_random_projects | /bank.py | 1,364 | 3.59375 | 4 | import time
customer_name = ""
acc_no = ""
bal = 500
while True:
time.sleep(2.5)
print('+------------------------------------+')
print('| 1 - get the values |')
print('| 2 - deposit to account |')
print('| 3 - withdraw in account |')
print('| 4 - show your profile |')
print('| 5 - to exit |')
print('+------------------------------------+\n')
choice = input('Enter you choice : ')
if choice == '1':
customer_name = input('\ntype a customer name?\n : ')
acc_no = input('type a account number?\n : ')
print("profile update\n")
elif choice == '2':
deposit = int(input('\nEnter the amount to deposit\n : '))
bal += deposit
print("updated")
elif choice == '3':
withdraw = int(input('\nEnter the withdrawal amount\n :'))
bal -= withdraw
print("updated")
elif choice == '4':
print('\nyou profile'.title())
print(f"Costomor_Name : {customer_name}")
print(f"Account_Number : {acc_no}")
print(f"Balance : {bal}")
print("This your account details\n")
elif choice == '5':
print("\nprogram is terminated")
break
else:
print("I dont understand your command")
|
0277a293d7e820b11b9cb1bf05c12440b39e476b | 321HG/NeuralPy | /neuralpy/layers/sparse/embedding.py | 5,237 | 3.515625 | 4 | """Embedding layer for NeuralPy"""
from torch.nn import Embedding as _Embedding
from neuralpy.utils import CustomLayer
class Embedding(CustomLayer):
"""
A simple lookup table that stores embeddings of a fixed dictionary and size
To learn more about RNN, please check pytorch
documentation at https://pytorch.org/docs/stable/nn.html#embedding
Supported Arguments:
num_embeddings: (Integer) size of the dictionary of embeddings
embedding_dim: (Integer) the size of each embedding vector
padding_idx: (Integer) If given, pads the output with the
embedding vector at padding_idx (initialized to zeros)
whenever it encounters the index
max_norm: (Float) If given, each embedding vector with
norm larger than max_norm is renormalized to have norm max_norm
norm_type: (Float) The p of the p-norm to compute for the max_norm option.
Default 2
scale_grad_by_freq: (Boolean) If given, this will scale gradients by the
inverse of frequency of the words in the mini-batch. Default False
sparse: (Boolean) If True, gradient w.r.t. weight matrix will be a sparse
tensor.
"""
def __init__(
self,
num_embeddings,
embedding_dim,
padding_idx=None,
max_norm=None,
norm_type=2.0,
scale_grad_by_freq=False,
sparse=False,
name=None,
):
"""
__init__ method for Embedding
Supported Arguments:
num_embeddings: (Integer) size of the dictionary of embeddings
embedding_dim: (Integer) the size of each embedding vector
padding_idx: (Integer) If given, pads the output with the
embedding vector at padding_idx (initialized to zeros)
whenever it encounters the index
max_norm: (Float) If given, each embedding vector with
norm larger than max_norm is renormalized to have norm max_norm
norm_type: (Float) The p of the p-norm to compute for the max_norm
option.Default 2
scale_grad_by_freq: (Boolean) If given, this will scale gradients by the
inverse of frequency of the words in the mini-batch. Default False
sparse: (Boolean) If True, gradient w.r.t. weight matrix will be a
sparse tensor.
"""
# Checking num_embeddings
if not num_embeddings or not isinstance(num_embeddings, int):
raise ValueError("Please provide a valid num_embeddings")
# Checking embedding_dim
if not embedding_dim or not isinstance(embedding_dim, int):
raise ValueError("Please provide a valid embedding_dim")
# Checking padding_idx, It is an optional field
if padding_idx is not None and not isinstance(padding_idx, int):
raise ValueError("Please provide a valid padding_idx")
# Checking max_norm, It is an optional field
if max_norm is not None and not isinstance(max_norm, float):
raise ValueError("Please provide a valid max_norm")
# Checking norm_type, It is an optional field
if not norm_type or not isinstance(norm_type, float):
raise ValueError("please provide a valid norm_type")
# Checking scale_grad_by_freq, It is an optional field
if not isinstance(scale_grad_by_freq, bool):
raise ValueError("Please provide a valid scale_grad_by_freq")
# Checking sparse, It is an optional field
if not isinstance(sparse, bool):
raise ValueError("Please provide a valid sparse")
super().__init__(_Embedding, "Embedding", layer_name=name)
# Storing values
self.__num_embeddings = num_embeddings
self.__embedding_dim = embedding_dim
self.__padding_idx = padding_idx
self.__max_norm = max_norm
self.__norm_type = norm_type
self.__scale_grad_by_freq = scale_grad_by_freq
self.__sparse = sparse
def set_input_dim(self, prev_input_dim, prev_layer_type):
"""
This method calculates the input shape for layer based on previous output
layer.
This method is used by the NeuralPy Models, for building the models.
No need to call this method for using NeuralPy.
"""
# Embedding does not need to n_input, so returning None
return None
def get_layer(self):
"""
This method returns the details as dict of the layer.
This method is used by the NeuralPy Models, for building the models.
No need to call this method for using NeuralPy.
"""
# Returning all the details of the layer
return self._get_layer_details(
(self.__embedding_dim,),
{
"num_embeddings": self.__num_embeddings,
"embedding_dim": self.__embedding_dim,
"padding_idx": self.__padding_idx,
"max_norm": self.__max_norm,
"norm_type": self.__norm_type,
"scale_grad_by_freq": self.__scale_grad_by_freq,
"sparse": self.__sparse,
},
)
|
2a2c833ee70c33f7aeb62c85dd400fab04c5ad8d | 321HG/NeuralPy | /neuralpy/layers/regularizers/dropout3d.py | 2,160 | 3.546875 | 4 | """Dropout3D Layer"""
from torch.nn import Dropout3d as _Dropout3D
from neuralpy.utils import CustomLayer
class Dropout3D(CustomLayer):
"""
Applies Dropout3D to the input.
The Dropout3D layer randomly sets input units to 0 with a frequency of `rate`
at each step during training time, which helps prevent overfitting.
Inputs not set to 0 are scaled up by 1/(1 - rate)
such that the sum over all inputs is unchanged.
Supported Arguments
p=0.5: (Float) Probability of an element to be zeroed.
The value should be between 0.0 and 1.0.
name=None: (String) Name of the layer, if not provided
then automatically calculates a unique name for the layer
"""
def __init__(self, p=0.5, name=None):
"""
__init__ method for Dropout3D class
Supported Arguments
p=0.5: (Float) Probability of an element to be zeroed.
The value should be between 0.0 and 1.0.
name=None: (String) Name of the layer, if not provided
then automatically calculates a unique name for the layer
"""
super().__init__(_Dropout3D, "Dropout3D", layer_name=name)
# Checking the field p, it should be a valid prob value
if not (isinstance(p, float) and p >= 0.0 and p <= 1.0):
raise ValueError("Please provide a valid p value")
self.__p = p
def set_input_dim(self, prev_input_dim, layer_type):
"""
This method calculates the input shape for layer based on previous
output layer.
This method is used by the NeuralPy Models, for building the models.
No need to call this method for using NeuralPy.
"""
# Dropout3D does not need to n_input, so returning None
return None
def get_layer(self):
"""
This method returns the details as dict of the layer.
This method is used by the NeuralPy Models, for building the models.
No need to call this method for using NeuralPy.
"""
return self._get_layer_details(None, {"p": self.__p, "inplace": False})
|
414243ac380ab55d740804838030ba11ba39c7cb | 321HG/NeuralPy | /neuralpy/layers/activation_functions/gelu.py | 1,624 | 3.796875 | 4 | """GELU Activation Function"""
from torch.nn import GELU as _GELU
from neuralpy.utils import CustomLayer
class GELU(CustomLayer):
"""
Applies the Gaussian Error Linear Units function to the input tensors.
For more information, check https://pytorch.org/docs/stable/nn.html#gelu
Supported Arguments
name=None: (String) Name of the activation function layer,
if not provided then automatically calculates a unique name for the layer
"""
def __init__(self, name=None):
"""
__init__ method for the GELU Activation Function class
Supported Arguments
name=None: (String) Name of the activation function layer,
if not provided then automatically calculates a unique name for the
layer
"""
super().__init__(_GELU, "GELU", layer_name=name)
def set_input_dim(self, prev_input_dim, layer_type):
"""
This method calculates the input shape for layer based on previous output
layer. Here for this activation function, we dont need it
This method is used by the NeuralPy Models, for building the models.
No need to call this method for using NeuralPy.
"""
# GELU does not need to n_input, so returning None
return None
def get_layer(self):
"""
Provides details of the layer
This method is used by the NeuralPy Models, for building the models.
No need to call this method for using NeuralPy.
"""
# Returning all the details of the activation function
return self._get_layer_details()
|
2a992878eb7049a4e63b04317e7a0c0d44972927 | 321HG/NeuralPy | /neuralpy/layers/other/flatten.py | 2,090 | 3.953125 | 4 | """Flatten layer for NeuralPy"""
from torch.nn import Flatten as _Flatten
from neuralpy.utils import CustomLayer
class Flatten(CustomLayer):
"""
Flattens a contiguous range of dims into a tensor
To learn more about Dense layers, please check PyTorch
documentation
https://pytorch.org/docs/stable/nn.html?highlight=flatten#torch.nn.Flatten
Supported Arguments:
start_dim: (Integer) first dim to flatten (default = 1)
end_dim: (Integer) last dim to flatten (default = -1)
"""
def __init__(self, start_dim=1, end_dim=-1, name=None):
"""
__init__ method for Flatten
Supported Arguments:
start_dim: (Integer) first dim to flatten (default = 1)
end_dim: (Integer) last dim to flatten (default = -1)
"""
# Checking start_dim
if start_dim and not isinstance(start_dim, int):
raise ValueError("Please provide a valid start_dim")
# Checking end_dim
if end_dim and not isinstance(end_dim, int):
raise ValueError("Please provide a valid end_dim")
super().__init__(_Flatten, "Flatten", layer_name=name)
# Storing the data
self.__start_dim = start_dim
self.__end_dim = end_dim
def set_input_dim(self, prev_input_dim, prev_layer_type):
"""
This method calculates the input shape for layer based on previous output
layer.
This method is used by the NeuralPy Models, for building the models.
No need to call this method for using NeuralPy.
"""
# Flatten does not need to n_input, so returning None
return None
def get_layer(self):
"""
This method returns the details as dict of the layer.
This method is used by the NeuralPy Models, for building the models.
No need to call this method for using NeuralPy.
"""
# Returning all the details of the layer
return self._get_layer_details(
None, {"start_dim": self.__start_dim, "end_dim": self.__end_dim}
)
|
85399a1213b77968a68592055d28e02075440f27 | dairycode/Python-language | /03_循环/hm_04_累加求和.py | 383 | 3.703125 | 4 | # 计算0-100之间所有数字的累计求和结果
# 0.定义最终结果的变量
result = 0
# 1.定义一个整数的变量记录循环的次数
i = 0
# 2.开始循环
while i <= 100:
print(i)
# 每一次循环,都让result这个变量和i这个计数器相加
result += i
# 处理计数器
i += 1
print("0-100之间的数字求和结果 = %d" % result) |
a2854e2dc98c50748506f8efb41affe3254f2264 | dairycode/Python-language | /02_分支/hm_02_判断年龄改进版.py | 412 | 3.8125 | 4 | # 输入用户年龄
age = int(input("请输入年龄:"))
# 判断是否满18岁(>=)
if age >= 18:
# 如果满18岁,允许进入网吧嗨皮
print("你已经成年,欢迎来网吧嗨皮")
else:
# 如果未满18岁,提示回家写作业
print("你还没有成年,请回家写作业吧")
# 这句代码无论条件是否成立都会执行
print("这句代码什么时候执行?") |
a928884a6c5200c8a4ebff292ef60f612fd66c02 | dairycode/Python-language | /03_循环/hm_03_程序计数.py | 335 | 4.0625 | 4 | # 打印5遍Hello Python
# 1.定义一个整数变量,记录循环次数
i = 0
# 2.开始循环
while i < 3:
# 1>希望在循环内执行的代码
print("Hello Python")
# 2>处理计数器
# i = i+1
i += 1
# 3.观察一下,循环结束后,计数器i的数值是多少
print("循环结束后,i = %d" % i) |
9182e71d91c1c32ef92fc2847c9326f98f54d4b6 | TomasHenriqueSantos/Python-Exercises | /ex004.py | 394 | 3.921875 | 4 | print('===Exercício 04===')
s = input('Digite algo:')
print('O tipo primitivo desse valor é', type(s))
print('Só tem espaços?', s.isspace())
print('É um numero?', s.isnumeric())
print('É alfabético?', s.isalpha())
print('É alfanumerico', s.isalnum())
print('Esta maiusculo?', s.isupper())
print('Esta minusculo?', s.islower())
print('Esta capitalizado?', s.istitle())
|
fc90cd9a54a819f1ecb6ca2488fc30f0f69fdfa0 | kimotot/pe | /py28.py | 1,350 | 3.734375 | 4 | # プロジェクトオイラー Problem28
# coding:UTF-8
MAX_LOOP = 500
def get_rightup(max = MAX_LOOP):
''' 中心からみて右斜め上方向に出現する数字列を求める関数
最大max個まで求める
先頭(0番目)は1である'''
list_rightup = [1]
n = 1
while n <= max:
list_rightup.append(list_rightup[n-1] + n*8)
n += 1
return list_rightup
def get_other(list_rightup,max = MAX_LOOP):
'''中心から見て左上・左下・右下方向に出現する数字列を求める関数
右上方向に出現する数字列を引数とし、それをもとに他列を求める
あとで総計を求める作業を簡単にするため先頭(0番目)は0とする'''
list_leftup = [0]
list_leftdown = [0]
list_rightdown = [0]
n = 1
while n <= max:
list_leftup.append(list_rightup[n] - (2*n) * 1)
list_leftdown.append(list_rightup[n] - (2*n) * 2)
list_rightdown.append(list_rightup[n] - (2*n) * 3)
n += 1
return list_leftup,list_leftdown,list_rightdown
if __name__ == "__main__":
li_rightup = get_rightup()
li_leftup,li_leftdown,li_rightdown = get_other(li_rightup)
s = 0
for nlist in [li_rightup,li_leftup,li_leftdown,li_rightdown]:
s += sum(nlist)
print(s) |
f958dfe13580d6aee7338aa4b57a658e3a5772e1 | kimotot/pe | /py46.py | 1,832 | 4.03125 | 4 | '''pe46の解答'''
import basic
import Prime
def is_odd_composite_number(n):
'''引数nが奇数の合成数であるか判定する関数'''
i = 1
r = n - (i**2) * 2
while r > 0:
if Prime.is_prime(r):
return True
i += 1
r = n - (i**2) * 2
else:
return False
class Odd_composite_number_Iterator:
''' 奇数の合成数を発生させるイテレータクラス
9以上で素数でない奇数とする'''
def __init__(self,max_number = 0):
''' 生成する合成数の最大値を設定する
最大値以下の数字までとする'''
self._max = max_number
def __iter__(self):
'''イテレータを初期化する'''
self._count = 0 #生成した合成数の個数をカウントする変数を初期化する
self._head = 7
return self
def __next__(self):
''' 素数でない奇数を奇数合成数とし、
9から始めて奇数合成数を発生させる関数
最大max値まで生成するが、max=0の場合、無限に発生させる'''
while True:
self._head += 2
if self._head > self._max != 0:
raise StopIteration
if Prime.is_prime(self._head):
pass
else:
self._count += 1
return self._head
if __name__ == "__main__":
@basic.time_log
def test():
it = Odd_composite_number_Iterator()
for x in it:
print(x)
@basic.time_log
def main():
it = Odd_composite_number_Iterator(10)
for x in it:
if is_odd_composite_number(x):
pass
else:
print(x)
break
test()
|
b925015be06011d41139ef95aeb6a7c0876370f6 | kimotot/pe | /py35.py | 2,662 | 3.5 | 4 | # coding:UTF-8
'''
100万未満の循環素数の個数を求める
'''
import math
import time
import copy
def get_sosu(maximum):
'''
引数max以下の素数を求める
戻り値は求めた素数を含むリスト
なお、1は素数ではないので、リストに含めない
'''
sosu_list = [2, 3] # 自明の素数をセットしておく
for n in range(5, maximum, 2):
sq = int(math.sqrt(n))
isprime = True
for prime in sosu_list:
if prime > sq:
isprime = True
break
elif n % prime == 0:
isprime = False
break
if isprime:
sosu_list.append(n)
return sosu_list
def all_rotate(num):
'''
引数を桁数分回転した数字列のリストを返す関数
引数は、基本となる正の整数値
戻り値は、リスト
'''
# 引数を各桁ごとの数字のリストに変換する
split_list = []
n1 = num % 10
n10 = num // 10
while (n1 > 0) or (n10 > 0):
split_list.insert(0,n1)
n1 = n10 % 10
n10 = n10 // 10
# split_listを回転した結果、得られた数字をリストに順次追加してゆく
c = 0
n_split_list = [copy.copy(split_list)]
while c < len(split_list) - 1:
t = split_list[0]
split_list.pop(0)
split_list.append(t)
n_split_list.append(copy.copy(split_list))
c += 1
# 整数値に戻す
int_list = []
for one_split_list in n_split_list:
s = 0
for n in one_split_list:
s = s*10 + n
int_list.append(s)
return int_list
def all_kisu(num):
"""全ての数字が奇数であるか判定する関数
"""
iskisu = True
while num > 0:
if num % 2 == 0:
iskisu = False
break
num = num // 10
return iskisu
if __name__ == "__main__":
MAX = 1000000
start_time = time.time()
slist = get_sosu(MAX)
elapsed_time = time.time() - start_time
print("経過時間={0:.3}".format(elapsed_time))
coun = 0
for n in slist:
if all_kisu(n):
rs = all_rotate(n)
isprime = True
for nrs in rs:
if nrs in slist:
pass
else:
isprime = False
break
if isprime:
coun += 1
print(n)
print(coun)
elapsed_time = time.time() - start_time
print("経過時間={0:.3}".format(elapsed_time))
|
cc856863bf356c569efce883609d6dc2bd369b55 | sanjay1711/100-days-of-code | /2.5. Numbers:sum of digits.py | 110 | 3.734375 | 4 | # Read an integer:
num = int(input())
a=(num%10)
b=(num//10)%10
c=(num//10)//10
# Print a value:
print(a+b+c)
|
e70c5700828ed6b9aca63aa8f7fcab81d4b8903f | flutesa/pythondevclub | /2 lesson (if-elif-else)/burkova/ZadachaB.py | 212 | 3.96875 | 4 | number = int(input())
if number % 5 == 0:
print('zero')
if number % 5 == 1:
print('one')
if number % 5 == 2:
print('two')
if number % 5 == 3:
print('three')
if number % 5 == 4:
print('four')
|
bad46d4862133163dca0723f79cdd661ce9ebbcc | flutesa/pythondevclub | /4 lesson (functions, classes)/burkova/111158.py | 281 | 3.828125 | 4 | # Desc sorting
def BubbleSort(a):
for i in range(len(a)):
for j in range(len(a) - 1):
if a[j + 1] > a[j]:
a[j], a[j + 1] = a[j + 1], a[j]
return a
a = list(map(int, input().split()))
a = BubbleSort(a)
print(' '.join(list(map(str, a))))
|
765e8508a91bf87bdfba292e97c009f1dfcef684 | mtu2/stargazing | /stargazing/utils/print_funcs.py | 1,663 | 3.609375 | 4 | from typing import List
from blessed import Terminal
import math
def print_xy(term: Terminal, x: int, y: int, value: str, flush=True, max_width: int = None,
center=False, trim=False):
"""trim and center both require max_width to be given"""
if max_width is not None:
empty_len = max(max_width - term.length(value), 0)
if trim and term.length(value) > max_width:
length = term.length(value)
eles = term.split_seqs(value)[::-1]
dot_count = 0
for i, ele in enumerate(eles):
# Skip if element is a sequence
if len(term.strip_seqs(ele)) == 0:
continue
if length > max_width:
eles[i] = ""
length -= 1
else:
eles[i] = "."
dot_count += 1
if dot_count == 2:
break
value = "".join(eles[::-1])
if center:
empty = " " * (empty_len // 2)
print(term.move_xy(x - max_width // 2, y) +
f" {empty}{value}{empty} ", end="", flush=flush)
else:
empty = " " * empty_len
print(term.move_xy(x, y) +
f" {value}{empty} ", end="", flush=flush)
else:
print(term.move_xy(x, y) + value, end="", flush=flush)
def print_lines_xy(term: Terminal, x: int, y: int, lines: List[str], flush=True, max_width: int = None,
center=False, trim=False):
for i, line in enumerate(lines):
print_xy(term, x, y + i, line, flush, max_width, center, trim)
|
37d025ee7f23ecd7270f4e7702a42124f51c2c39 | yunblack/Movie-Data-Viewer | /moviedatareader.py | 1,742 | 3.734375 | 4 | # name: Juyoung Daniel Yun
# email: juyoung.yun@stonybrook.edu
# id: 112368205
from datetime import datetime
import csv
#----------------------------------------------------------------------
movieItems = []
def csv_dict_reader(file_obj):
"""
Read a CSV file using csv.DictReader
The line is basically a dictionary object.
"""
reader = csv.DictReader(file_obj, delimiter=',')
for line in reader:
if line["id"] != '':
mDate = datetime.strptime(line["release_date"], "%m/%d/%Y").date()
movieItem = {}
movieItem['date'] = mDate
movieItem['record'] = line
movieItem['genres'] = line["genres"]
movieItem['id'] = line["id"]
movieItem['imdb_id'] = line["imdb_id"]
movieItem['original_language'] = line["original_language"]
movieItem['original_title'] = line["original_title"]
movieItem['popularity'] = line["popularity"]
movieItem['production_companies'] = line["production_companies"]
movieItem['production_countries'] = line["production_countries"]
movieItem['revenue'] = line["revenue"]
movieItem['runtime'] = line["runtime"]
movieItem['spoken_languages'] = line["spoken_languages"]
movieItem['status'] = line["status"]
movieItem['title'] = line["title"]
movieItem['adult'] = line["adult"]
movieItems.append(movieItem)
print("Total movie items = ", len(movieItems))
movieItems.sort(key=lambda item:item['date'])
return movieItems
if __name__ == "__main__":
with open("movies_metadata_edited.csv", encoding="utf8") as f_obj:
csv_dict_reader(f_obj) |
cb884c3a3a6e612b8e1d69b44a24362af4a826cc | chris-mega/ObstacleSlam | /events/src/obstacle_run_slam/obstacles.py | 609 | 3.59375 | 4 | class Obstacle(object):
def __init__(self):
self.area = -1
self.x = -1
self.y = -1
self.angle = -100
self.width = -1
self.height = -1
self.position = 'None'
def update(self, x, y, width, height, area, angle, pos):
self.area = area
self.x = x
self.y = y
self.width = width
self.height = height
self.angle = angle
self.position = pos
class Obstacles(object):
def __init__(self):
self.cup = Obstacle()
self.yellow = Obstacle()
self.blue = Obstacle()
|
cc349db0742aaebc7650af633e66bc10cb3f14b2 | matheusjunqueiradasilva/Jogo-adivinhacao | /jogo da adivinhacao.py | 561 | 4.15625 | 4 | import random
rand = random.randint(1, 200)
tentiva = 10
print(" Bem vindo ao jogo da advinhacao!")
print(" Tente advinhar o numero sorteado, e ele deve ser menor que 200!")
while True:
numero1 = int(input("digite o numero: "))
if numero1 == rand:
print(" parabens voce acertou! ")
break
elif numero1 > rand:
print("o numero que chutou foi maior! ")
elif tentiva == 0:
break
else:
print("o numero chutado foi menor ")
tentiva -= 1
print(f" numero restante de tentativas", +tentiva)
|
dc37784ec5ecc60523139480f96242bcc91695bf | appanchhibber/CHEERS | /Solution.py | 1,425 | 3.984375 | 4 | from MathOperations import MathOperation
"""
Python file for implementing the solution of the project
"""
class Solution:
"""
This class is responsible for the calculation of the value of alpha and the length between the two coasters of same
radius
"""
alpha_value = float(10)
@staticmethod
def alpha():
"""
This static method calculates the value of alpha
:return:nothing
"""
alpha = 2
precision = 6
pi = MathOperation.pi()
calculated_decimal_places = 1
for itr in range(0, precision):
original = alpha - MathOperation.sin(alpha) - pi / 2
prime = 1.0 - MathOperation.cos(alpha)
alpha = alpha - (original / prime)
if itr >= 1:
calculated_decimal_places += 3 * (2 ** (itr - 1))
if calculated_decimal_places > precision:
break
return alpha
@staticmethod
def set_alpha():
Solution.alpha_value = Solution.alpha()
@staticmethod
def get_alpha():
return Solution.alpha_value
@staticmethod
def get_length(radius):
"""
This static method calculates the length based on the value of alpha
:param radius:
:return:float length
"""
Solution.set_alpha()
return 2.0 * radius * (1.0 - MathOperation.cos(Solution.get_alpha() / 2))
|
f69eb91c047160eaa5583235cfc700261df952f8 | dldydrhkd/Problem-Solving | /leetcode/1137.py | 353 | 3.59375 | 4 | class Solution:
def tribonacci(self, n: int) -> int:
if(n==0):
return 0
if(n==1):
return 1
if(n==2):
return 1
n1 = 0
n2 = 1
n3 = 1
for i in range(3,n+1):
n4 = n1+n2+n3
n1 = n2
n2 = n3
n3 = n4
return n3 |
69fde7d67b3b07b88dcf9e844d12c59d08739064 | dldydrhkd/Problem-Solving | /프로그래머스/전화번호 목록.py | 219 | 3.6875 | 4 | def solution(phone_book):
answer = True
phone_book.sort()
for i in range(1,len(phone_book)):
if(phone_book[i-1] == phone_book[i][:len(phone_book[i-1])]):
answer = False
return answer
|
13394b73571a3f164a9c7a1461fa2b6e6ba4f63f | alicebalayan/Algorithms | /General Problems/General/5/solution.py | 790 | 4.09375 | 4 | # General Problem 5:
# Find the only element in an array that only occurs once.
# Solution:
# Store the array into a dictionary while counting the occurences
# Then print out values that occur once, if there is exactly one
# function printOneCount
# Takes an array of integers as the input
# Outputs the element that is repeated exactly once
def printOneCount(arr):
myDict = dict()
for i in arr:
myDict[i] = myDict.get(i,0) + 1
arrMax = min(myDict, key=myDict.get)
lengthOne = list()
for key, value in myDict.items():
if (value == 1):
lengthOne.insert(len(lengthOne),key)
if (len(lengthOne) == 1):
print(arrMax)
else:
print("There is not exactly one element that occurs once.")
if __name__ == '__main__':
arr = [2, 5, 8, 5, 2, 2, 2, 5, 5]
printOneCount(arr) |
2a99a9e07ad02b5d5ae3c785ef43f1b57f560ac9 | alicebalayan/Algorithms | /General Problems/General/8/solution.py | 1,566 | 4.03125 | 4 | # General Problem 8:
# Implement binary search in a rotated array (ex. {5,6,7,8,1,2,3})
# Solution:
# Similar to general 7
# We assume that the rotated array is sorted
# First we find the real starting index of the rotated array
# Then we perform binary search, except we consider the real starting index
# Therefore, we will need to use modulus to get the index correct
# Note: need to keep track of when start passes end to terminate loop
def binarySearchRot(arr, value, startRealIndex):
end = ((startRealIndex - 1) + len(arr)) % len(arr)
start = startRealIndex
startPassedEnd = False
while (startPassedEnd != True):
mp = ((( ((start - startRealIndex) % len(arr)) + ( (end - startRealIndex + len(arr)) % len(arr))) // 2) + startRealIndex) % len(arr)
if (arr[mp] == value):
return mp
elif (arr[mp] < value):
if ((((start - startRealIndex) % len(arr)) - ( (end - startRealIndex + len(arr)) % len(arr))) == 0 ):
startPassedEnd = True
else:
start = (mp + 1) % len(arr)
else:
if ((((start - startRealIndex) % len(arr)) - ( (end - startRealIndex + len(arr)) % len(arr))) == 0 ):
startPassedEnd = True
else:
end = ((mp - 1) + len(arr)) % len(arr)
return -1
def findStart(arr):
lastValue = arr[0]
for i in range(1, len(arr)):
if (arr[i] < lastValue):
return i
lastValue = arr[i]
return 0
if __name__ == '__main__':
arr = [8, 9, 10, 0, 1, 3, 4, 5, 6, 7]
val = 9
startRealIndex = findStart(arr)
index = binarySearchRot(arr, val, startRealIndex)
if (index != -1):
print(index)
else:
print("Not found.") |
f50ec07ceb69c0e52b26ebcb3e2e6b0672d6de99 | GaoFan98/algorithms_and_ds | /DS and Algorithms in Python/random_tests.py | 7,020 | 3.984375 | 4 | # list = [1, 4, 3, 4, 5]
#
# i = 0
# while i < len(list):
# print(list[i])
# i += 1
# modulus comparison keyword parameter
# print(max(-2, -65, 32, 11, key=abs))
# Integer related point and character on the integer point
# print(ord('~'))
# print(chr(65))
# return the whole value of division and it's reminder 5//3 = (1,2)
# print(divmod(5, 3))
# returns hashed version
# print(hash('secret'))
# returns unique id version
# print(id('secret'))
# age = int(input("Enter age: "))
# heart_rate = 206.9 - (0.67 * age)
# target = 0.65 * heart_rate
# print('Fat-burning heart rate is', target)
# import math
#
#
# def sqrt(x):
# if not isinstance(x, (int, float)):
# raise TypeError('x must be numeric')
# elif x < 0:
# raise ValueError('x cannot be negative')
#
# return math.sqrt(x)
# or without math
# return x ** 0.5
#
#
# out = sqrt(4)
# print(out)
# def zero_div(x, y):
# try:
# ratio = x / y
# except ZeroDivisionError:
# return "You cannot divide by 0"
#
# return ratio
#
#
# out = zero_div(2, 123)
# print(out)
# age = -1
# while age <= 0:
# try:
# age = int(input('Enter your age: '))
# if age <= 0:
# print('Age must be positive number')
#
# except ValueError:
# print('Invalid age specification')
#
# except EOFError:
# print('Unexpected error reading input')
# usage of next()
# data = [1,2,3,4,5,6]
# # it is wrong to do
# # print(next(data))
# # instead create list_iterator object first and then use next()
# i = iter(data)
# print(next(i))
#
# def factors(n):
# for k in range(1, n + 1):
# if n % k == 0:
# yield k
#
#
# out = factors(10)
# print(out)
# def fibo():
# a = 0
# b = 1
# while True:
# yield a
# future = a + b
# a = b
# b = future
#
#
# print(fibo())
# Iterator
# class SequenceIterator:
# def __init__(self, sequence):
# self._seq = sequence
# self._number = -1
#
# def __next__(self):
# self._number += 1
#
# if self._number < len(self._seq):
# return self._seq[self._number]
# else:
# return StopIteration()
#
# def __iter__(self):
# return self
#
#
# class ReverseSequenceIterator:
# def __init__(self, sequence):
# self._seq = sequence
# self._number = len(sequence)
#
# def __next__(self):
# self._number -= 1
#
# if self._number >= 0:
# return self._seq[self._number]
# else:
# return StopIteration()
#
# def __iter__(self):
# return self
# Range
# class Range:
# def __init__(self, start, stop=None, step=1):
# if step == 0:
# raise ValueError('step cannot be 0')
#
# if stop is None:
# start, stop = 0, start
#
# self._length = max(0, (stop - start + step - 1) // step)
# self._start = start
# self._step = step
#
# def __len__(self):
# return self._length
#
# def __getitem__(self, item):
# if item < 0:
# item += len(self)
#
# if not 0 <= item < self._length:
# raise IndexError('index out of range')
#
# return self._start + item * self._step
#
#
# test = Range(start=2, stop=10, step=2)
# print(test[2])
# Inheritance example
# class CreditCard:
# def __init__(self, customer, bank, account_id, credit_limit):
# self._customer = customer
# self._bank = bank
# self._account = account_id
# self._limit = credit_limit
# self._balance = 0
#
# def get_customer(self):
# return self._customer
#
# def get_bank(self):
# return self._bank
#
# def get_account(self):
# return self._account
#
# def get_limit(self):
# return self._limit
#
# def get_balance(self):
# return self._balance
#
# def charge(self, price):
# if price + self._balance > self._limit:
# return False
# else:
# self._balance += price
# return True
#
# def make_payment(self, amount):
# self._balance -= amount
#
#
# class PredatoryCreditCard(CreditCard):
# OVERLIMIT_FEE = 5
#
# def __init__(self, customer, bank, account_id, credit_limit, annual_percent):
# """
# super().__init__ inherit params from parent class
# """
# super().__init__(customer, bank, account_id, credit_limit)
# self._year_per = annual_percent
#
# def charge(self, price):
# success = super().charge(price)
#
# if not success:
# self._balance += PredatoryCreditCard.OVERLIMIT_FEE
#
# return success
#
# def process_month(self):
# if self._balance > 0:
# monthly_fee = pow(1 + self._year_per, 1 / 12)
# self._balance *= monthly_fee
# more example on inheritance
# class Progression:
# def __init__(self, start):
# self._current = start
#
# def _advance(self):
# self._current += 1
#
# def __next__(self):
# if self._current is None:
# raise StopIteration
# else:
# answer = self._current
# self._advance()
# return answer
#
# def __iter__(self):
# return self
#
# def print_progression(self, n):
# print(" ".join(str(next(self)) for _ in range(n)))
#
#
# class AbsoluteDiffProgression(Progression):
# def __init__(self, first=2):
# self._current = first
# self._prev = 202
#
# def __next__(self):
# answer = self._current
# self._current, self._prev = abs(self._current - self._prev), self._current
# return answer
#
# def print_progression(self, n):
# print(" ".join(str(next(self)) for _ in range(n)))
#
#
# print(AbsoluteDiffProgression().print_progression(9))
# class ArithmeticProgression(Progression):
# def __init__(self, increment=1, start=0):
# super().__init__(start)
# self._increment = increment
#
# def _advance(self):
# self._current += self._increment
#
#
# class GeometricProgression(Progression):
# def __init__(self, base=1, start=1):
# super().__init__(start)
# self._base = base
#
# def _advance(self):
# self._current *= self._base
#
#
# class FibonacciProgression(Progression):
# def __init__(self, first=1, second=1):
# super().__init__(first)
# self._prev = second - first
#
# def _advance(self):
# self._prev, self._current = self._current, self._prev + self._current
#
#
# print("Default progression")
# Progression(1).print_progression(10)
#
# print("Arithmetic progression")
# ArithmeticProgression(5).print_progression(10)
#
# print("Arithmetic progression")
# GeometricProgression(5).print_progression(10)
#
# print("Fibonacci progression with first number 41 and second number 123")
# FibonacciProgression(41, 123).print_progression(10)
|
d3fa518047f00633b3e21037013f6c0bc6b1c648 | GaoFan98/algorithms_and_ds | /Grokking/3_quick_sort.py | 343 | 3.796875 | 4 | def quick_sort(arr):
if len(arr) < 2:
return arr
else:
pivot = arr[0]
less = [num for num in arr[1:] if num <= pivot]
greater = [num for num in arr[1:] if num > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
q = quick_sort([7, -9, 12, 8, 89])
print(q)
"""
Big O: nlog(n)
"""
|
b50f2c2dfa19a96d431b030b5a0551fc932e9141 | GaoFan98/algorithms_and_ds | /Algo/Arrays/find_miss_el.py | 649 | 3.640625 | 4 | # def finder(l1, l2):
# num_dict = {}
#
# for num in l1:
# if num not in num_dict:
# num_dict[num] = 1
# else:
# num_dict[num] += 1
#
# for num in l2:
# if num not in num_dict:
# num_dict[num] = 1
# else:
# num_dict[num] -= 1
#
# for num in num_dict:
# if num_dict[num] > 0:
# return num
#
#
# out = finder([5, 5, 7, 7], [5, 7, 7])
# print(out)
# faster solution
def finder_bitwise(l1, l2):
result = 0
for num in l1 + l2:
result ^= num
return result
out = finder_bitwise([5, 5, 7, 7], [5, 7, 7])
print(out)
|
3c35cae20db00a8798be0a18ce87d93bb628d673 | GaoFan98/algorithms_and_ds | /Coursera/7_fibonacci_partial_sum.py | 308 | 3.546875 | 4 | def calc_fib(frm,till):
arr_nums = [0,1]
if (till <= 1): return till
for i in range(2,till+1):
arr_nums.append((arr_nums[-1]+arr_nums[-2])%10)
a = sum(arr_nums[frm:till+1]) %10
return a
if __name__ == '__main__':
frm, till = map(int, input().split())
print(calc_fib(frm, till)) |
5f25a0a9ad7ae81345007761fb6641542edcdd3b | GaoFan98/algorithms_and_ds | /Coursera/1_fibonacci_number.py | 697 | 4.15625 | 4 | # Recursive way
# def calc_fib(n):
# if n <= 1:
# return n
# return calc_fib(n-1)+calc_fib(n-2)
# n = int(input())
# print(calc_fib(n))
# Faster way of fibonacci
# def calc_fib(n):
# arr_nums = [0, 1]
#
# if (n <= 1):
# return n
#
# for i in range(2, n + 1):
# arr_nums.append(arr_nums[-1] + arr_nums[-2])
#
# return arr_nums[-1]
#
#
# print(calc_fib(9))
#
# Another way of Fibonacci with O(n)
# def good_fibonacci(n):
# if (n <= 1):
# return (n, 0)
#
# else:
# # here good_fibonacci works as counter-=1 step
# (a, b) = good_fibonacci(n - 1)
# # print(a,b)
# return (a + b, a)
#
#
# print(good_fibonacci(4))
|
dff4d3df76fef571af82586fa6b1436ac38231d7 | EmilieTrouillard/ComputationalTools | /preprocessing/parser.py | 2,254 | 3.5 | 4 | # coding=utf8
import json
import re
import mmh3
'''
GOAL: Get all links to other wikipedia pages from the json file of a single page.
'''
# DEPRECATED USED FOR PARSING JSON FROM API
# WIKILINK_REGEX = r"/<a\s+(?:[^>]*?\s+)?href=\\([\"'])\/wiki\/(.*?)\\\1/"
WIKILINK_REGEX = r'\[\[([\| \w+]*)\]\]'
rgx = re.compile(WIKILINK_REGEX)
def getPageIndex(pageName):
'''
Creates an Index from page name, thanks to a hash function
We need to hash on a big enough space, to avoid collisions.
32 bits: 2••32 = 4 294 967 296 = 429 * 10 000 000 the nbr of articles,
64 bits: 2••64 >> 10 000 000, seems safer
'''
return abs(mmh3.hash64(pageName)[0])
def getLinksFromPage(page):
'''
For a page returns the links (Best to handle the format from here)
'''
return page['links']
def getTitleFromPage(page):
'''
For a page returns the title (Best to handle the format from here)
'''
return page['title']
def parseJSON_FROMXML(fileName):
'''
Parses a json file generated from the xml wikipedia dump
'''
# REGEX
global WIKILINK_REGEX
rgx = re.compile(WIKILINK_REGEX)
try :
with open(fileName) as f:
jsonPage = json.load(f)
except FileNotFoundError:
return 'Please enter the name of an existing file'
# Pages List
pageLinks = dict()
pageRedirect = dict()
pageTitles = dict()
for page in jsonPage:
# Pages that are deprecated and don't contain any content.
if 'redirect' in page.keys():
pageRedirect[getPageIndex(page['title'])] = getPageIndex(page['redirect']['title'])
else:
page_revision = page['revision']
matches = rgx.findall(page_revision['text'])
matches = [match for match in matches if match[:5] != 'File:']
links = [getPageIndex(onematch) for match in matches for onematch in match.split('|')]
pageLinks[getPageIndex(page['title'])] = list(set(links))
pageTitles[getPageIndex(page['title'])] = page['title']
return pageLinks, pageRedirect, pageTitles
# TESTABLE
if __name__ == '__main__':
print('Enter the input file:')
jsonFile = input()
print(parseJSON_FROMXML(jsonFile))
|
91a3b5ba76ba9b77775c981e048aec2cae7e8d9d | Fabulinux/Project-Cognizant | /Challenges/Brian-08302017.py | 1,007 | 4.25 | 4 | import sys
def main():
# While loop to check if input is valid
while(1):
# Try/Except statement for raw_input return
try:
# Prompt to tell user to input value then break out of while
val = int(raw_input("Please input a positive integer: ").strip())
break
except:
# Except invalid input error and prompts again
print "Invalid input, try again."
continue
# Construction of the staircase
for step in xrange(val):
# Variable to reduce redundancy
breakpoint = val-step-1
# Creates the spaces for the step
for space in range(0, breakpoint):
sys.stdout.write(' ')
# Creates the actual steps using "#"
for pound in range(breakpoint, val):
sys.stdout.write('#')
#Print new line for next step
print ""
# Basic main method call in python if running as a stand alone program
if __name__ == "__main__": main()
|
78f333af2427a13909aa28b67c4be1675d3e81f7 | AlexOKeeffe123/mastermind | /game/board.py | 2,682 | 4.15625 | 4 | import random
from typing import Text
#Chase
class Board:
def __init__(self, length):
"""The class constructor
Args:
self (Display): an instance of Display
"""
self._items = {} # this is an empty dictionary
self._solutionLength = length
def to_string(self):
"""Converts the board data to its string representation.
Args:
self (Board): an instance of Board.
Returns:
string: A representation of the current board.
"""
lines = "\n--------------\n"
for name, values in self._items.items():
# "Player {name}: ----, ****"
lines += f"Player {name}: {values[1]}, {values[2]}\n"
lines += "--------------"
return lines
def apply(self, turn):
""" Applies the given turn to the playing surface. Gets player's turn, name, and values
Args:
self (Board): an instance of Board.
turn (Turn): The turn to apply.
"""
guesserName = turn.get_guesser_name()
values = self._items[guesserName]
values[1] = turn.get_guess()
values[2] = self._create_hint(values[0], values[1])
def prepare(self, player):
"""Sets up the board with an entry for each player.
Args:
self (Board): an instance of Board.
player (string): gets player's values
"""
name = player.get_name()
code = str(random.randint(10 ** (self._solutionLength - 1), 10 ** self._solutionLength))
guess = hint = ""
for char in range(self._solutionLength):
guess += "-"
hint += "*"
self._items[name] = [code, guess, hint]
def _create_hint(self, code, guess):
"""Generates a hint based on the given code and guess.
Args:
self (Board): An instance of Board.
code (string): The code to compare with.
guess (string): The guess that was made.
Returns:
string: A hint in the form [xxxx]"""
hint = ""
for index, letter in enumerate(guess):
if code[index] == letter:
hint += "x"
elif letter in code:
hint += "o"
else:
hint += "*"
return hint
def get_solution(self, name):
"""Gets solution
Args:
self (Board): An instance of Board.
Return:
name (String): gets player's name
integer (Int): gets code"""
return self._items[name][0] |
f27dd793820c4035d0e89ddc6dc1d590c744270d | nzsakib/leetcode | /palindrome_number.py | 617 | 3.71875 | 4 |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# Negative number is not palindrome
if x < 0:
return False
z = x
rev = 0
prev = rev
while ( z != 0 ):
current = z % 10
rev = rev * 10 + current
if (rev - current) / 10 != prev: # 32 bit integer overflow check
return False
prev = rev
z = int(z / 10)
if x == rev:
return True
else:
return False
l = Solution()
print(l.isPalindrome(-1))
|
cc77887815ab66a9dc2d20459de45c864fb9c5ff | shahara21-meet/meet2019y1lab6 | /lab_6.py | 186 | 4 | 4 | def add(start,end,n):
total = 0
for number in range(start, end + n):
num=num+
print(num)
total = total + number
return total
x=add(1,10,2)
print(x)
|
99d06c8c3a682c0b07c39bdcd0c6d2943625f8ee | cubanmakers/OttoDIYPython | /Otto_allmoves_V9.py | 1,120 | 3.71875 | 4 | """
Otto All moves python test
OttDIY Python Project, 2020 | sfranzyshen
"""
import otto9, time
Otto = otto9.Otto9()
Otto.init(5, 12, 13, 14, True, 0, 1, 2, 3)
Otto.home()
Otto.walk(2, 1000, 1) #-- 2 steps, "TIME". IF HIGHER THE VALUE THEN SLOWER (from 600 to 1400), 1 FORWARD
Otto.walk(2, 1000, -1) #-- 2 steps, T, -1 BACKWARD
Otto.turn(2, 1000, 1) #-- 3 steps turning LEFT
Otto.home()
time.sleep_ms(100)
Otto.turn(2, 1000, -1) #-- 3 steps turning RIGHT
Otto.bend(1, 500, 1) #-- usually steps =1, T=2000
Otto.bend(1, 2000, -1)
Otto.shakeLeg(1, 1500, 1)
Otto.home()
time.sleep_ms(100)
Otto.shakeLeg(1, 2000, -1)
Otto.moonwalker(3, 1000, 25, 1) #-- LEFT
Otto.moonwalker(3, 1000, 25,-1) #-- RIGHT
Otto.crusaito(2, 1000, 20, 1)
Otto.crusaito(2, 1000, 20, -1)
time.sleep_ms(100)
Otto.flapping(2, 1000, 20, 1)
Otto.flapping(2, 1000, 20, -1)
time.sleep_ms(100)
Otto.swing(2, 1000, 20)
Otto.tiptoeSwing(2, 1000, 20)
Otto.jitter(2, 1000, 20) #-- (small T)
Otto.updown(2, 1500, 20) #-- 20 = H "HEIGHT of movement"T
Otto.ascendingTurn(2, 1000, 50)
Otto.jump(1, 2000)
Otto.home()
|
8f8253d0ebd6f6d823958e1af0720e5455d2713f | josht047/Ising-Model-Project | /Plotting Ising Model.py | 1,681 | 3.90625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
beta = 1.0
#defining function to randomly generate initial spin configuration
def initialise(n):
state = np.random.randint(2,size=(n,n))
return 2*state -1 #as spin can be -1 or 1, but the previous line gives a random matrix of 0 and 1
#function to use metropolis algorithm on lattice
def metropolis(state,beta,n):
a = np.random.randint(0,n)
b = np.random.randint(0,n)
spin_ij = state[a,b] #considering the spin of a random point in the lattice
spin_neighbours = state[(a+1)%n,b] + state[(a-1)%n,b] + state[a,(b+1)%n] + state[a,(b+1)%n] #considering spin of the neighbours #by using modulo n, periodic boundary conditions can be established
hamil = -spin_ij*spin_neighbours# - spin_ij
dE = 2*hamil #as dE = flipped Hamiltonian - Hamiltonian = -2*Hamiltonian
if dE < 0:
spin_ij *= -1.0
#here we compare the probability to a random number between 0 and 1 to determine whether or not the spin will flip
elif np.exp(-dE*beta) > rand():
spin_ij *= -1.0
state[a,b] = spin_ij
return state
#function that plots the current spin state of the lattice when called
def plot(result,i):
plt.figure(figsize=(5,5))
plt.imshow(result)
plt.title("Updated Spin Configuration")
def find_mag(state):
mag = np.sum(state)
return mag
#main function
n = 100
nsteps = 200000
mag = []
x = np.arange(200000)
state = initialise(n)
print (state)
#loop to repeatedly apply the algorithm to the lattice
for i in range(nsteps):
result = metropolis(state,beta,n)
plot(result,nsteps)
plt.show() |
cc1760c2ecbd3b7501e46b86eb9f3ae214975d84 | ValerieGM/Learn-Python-The-Hard-Way | /exercises/ex05.py | 599 | 3.921875 | 4 | my_name = 'Valkyrie'
my_age = 23 # sorta
my_height = 130 # cm I think
my_weight = 66 # kg
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Black'
print(f"Let's talk about {my_name}.")
print(f"She's {my_height} centimeters tall.")
print(f"She's {my_weight} kilograms heavy.")
print(f"Actually that's not too heavy.")
print(f"She's got {my_eyes} and {my_hair}.")
print(f"Her teeth arr usually {my_teeth} depending on the coffee.")
## complications ret=lating to scripting
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height} and {my_weight} I get {total}.")
## f for format
|
28846684ac2b1aa260b3e6eff527664f9d1fad32 | ValerieGM/Learn-Python-The-Hard-Way | /exercises/ex24.py | 1,047 | 4.0625 | 4 | print("From The Top!!!")
print('You\'d need to know \'bout escapes with \\ that do:')
print("\n newlines and \t tabs.")
poem = """
\tMove him into the sun—
Gently its touch awoke him once,
At home, whispering of fields half-sown.\nAlways it woke him, even in France,
Until this morning and this snow.
If anything might rouse him now
\n\tThe kind old sun will know.
"""
print("********************")
print(poem)
print("********************")
five = 10 - 2 + 3 - 6
print(f"This should be five: {five}")
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 100
crates = jars / 100
return jelly_beans, jars, crates
start_point = 1000
beans, jars, crates = secret_formula(start_point)
## Another way to format strings
print("With a starting point of: {}".format(start_point))
start_point = start_point / 10
print("We can also do that this way:")
formula = secret_formula(start_point)
## Easier way to apply a list to a format string
print("We's have {} beans, {} jars and {} crates".format(*formula))
|
b4cdffb10f427f0b26c319f973b6d57d0959ee5e | frasanz/LTS | /chapter6/onehotword.py | 1,050 | 3.828125 | 4 | # This is an example of one hot encoding using words
import numpy as np
samples = ('The cat sat on the mat.', 'The dog ate my homework.')
#First, build an index of all tokens in the data
token_index = {}
for sample in samples:
# We simply tokenize the samples via the `split`method.
# In real life, we would also strip puctuation and special characters
# from the samples.
for word in sample.split():
if word not in token_index:
# Assign a unique index to each unique word
token_index[word] = len(token_index) + 1
# Note the we don't attribute index 0 to anything
# Next, we vectorize our samples.
# We will only consider the first `max_length` words in each sample.
max_length = 10
# This is where we store our results:
results = np.zeros((len(samples), max_length, max(token_index.values()) + 1))
for i, sampe in enumerate(samples):
for j, word in list(enumerate(sample.split()))[:max_length]:
index = token_index.get(word)
results[i,j,index] = 1.
print(results)
|
c3c33db359afa186f81827a9898d27885310ccb1 | olifantix/python_tools | /tic-tac-to_sim.py | 1,203 | 4.0625 | 4 | def check_win(d):
"""Input is a dictionary with keys 1-9 according to a numerical
keypad: 789
456
123
function checks win condition for tic tac toe and returns the dicts value"""
w = ( (7, 8, 9), (4, 5, 6), (1, 2, 3,),
(1, 4, 7), (2, 5, 8), (3, 6, 7),
(7, 5, 3), (9, 5, 1))
for fields in w:
# if not all fields present, can not be a win
if all(f in d for f in fields):
# if all fields the same, return 1st field as result
if len(set(d[num] for num in fields)) == 1:
return d[fields[0]]
return None
# generate random tic tac toe placement order
from random import shuffle
nums = list(range(1, 10))
shuffle(nums)
# place X and O interleafed onto shuffled numbers
who = True
ttt = {}
for n in nums:
ttt[n] = "X" if who else "O"
who = not who
winner = check_win(ttt)
if winner:
print("Winner:", winner)
break
else:
print("Draw!")
# output board
print(ttt.get(7, " "), ttt.get(8, " "), ttt.get(9, " "),
"\n"+ttt.get(4, " "), ttt.get(5, " "), ttt.get(6, " "),
"\n"+ttt.get(1, " "), ttt.get(2, " "), ttt.get(3, " ")+"\n")
|
1f15da7c30ac1cc5651b23777bda357d6edb6b53 | gaogao0504/gaogaoTest1 | /homework/pytestagmnt/calculator1.py | 818 | 4.28125 | 4 | """
1、补全计算器(加法,除法)的测试用例
2、使用数据驱动完成测试用例的自动生成
3、在调用测试方法之前打印【开始计算】,在调用测试方法之后打印【计算结束】
坑1:除数为0的情况
坑2: 自己发现
"""
# 被测试代码 实现计算器功能
class Calculator:
# 相加功能
def add(self, a, b):
return a + b
# 相减功能
def sub(self, a, b):
return a - b
# 相乘功能
def multi(self, a, b):
return a * b
# 相除功能
def div(self, a, b):
return a / b
# if b == 0:
# print("0")
# else:
# return a / b
#
# try:
# return a / b
# except Exception as e:
# return "这里有个异常"
|
f1b93a968eeeefd9605cc9976cec3f09a48eb610 | poldrack/pybraincompare | /example/make_connectogram.py | 960 | 3.609375 | 4 | # Make a connectogram d3 visualization from a square connectivity matrix
from pybraincompare.compare.network import connectogram
from pybraincompare.template.visual import view
import pandas
# A square matrix, tab separated file, with row and column names corresponding to node names
connectivity_matrix = "data/parcel_matrix.tsv"
parcel_info = pandas.read_csv("data/parcels.csv")
networks = list(parcel_info["Community"])
# should be in format "L-1" for hemisphere (L or R) and group number (1..N)
groups = ["%s-%s" %(parcel_info["Hem"][x],parcel_info["ID"][x]) for x in range(0,parcel_info.shape[0])]
# A threshold value for the connectivity matrix to determine neighbors, eg, a value of .95 means we only keep top 5% of positive and negative connections, and the user can explore this top percent
threshold = 0.99
html_snippet = connectogram(matrix_file=connectivity_matrix,groups=groups,threshold=threshold,network_names=networks)
view(html_snippet)
|
8a11a21c2675c2b6f5859e8224a3d1dbb77cd6f8 | ncouturier/Exercism | /python/twelve-days/twelve_days.py | 929 | 3.84375 | 4 |
NUMBERS = ["a ","two ","three ","four ", "five ", "six ","seven ","eight ","nine ","ten ","eleven ","twelve ", "thirteen ", "fourteen ", "fifteen ","sixteen ","seventeen ", "eighteen ","nineteen "]
NUMERALS = ["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"]
OBJECTS = ["Partridge in a Pear Tree","Turtle Doves","French Hens","Calling Birds","Gold Rings","Geese-a-Laying","Swans-a-Swimming","Maids-a-Milking","Ladies Dancing","Lords-a-Leaping","Pipers Piping"]
def firstn(n):
num = n
yield f"On the {NUMERALS[num-1]} day of Christmas my true love gave to me: "
while num > 0:
sep = "," if num >0 else "."
prefix = "and " if (num ==0 and not n==1) else ""
yield f"{prefix}{NUMBERS[num-1]} {OBJECTS[num-1]}{sep}"
num -= 1
def recite(start_verse, end_verse):
return [item for item in firstn(end_verse)][start_verse-1:]
|
b614122fb0117d4dd5afb5f148f5f803013a3397 | LeedsCodeDojo/Rosalind | /AndyB_Python/fibonacci.py | 1,355 | 4.25 | 4 |
def fibonacci(n, multiplier=1):
"""
Generate Fibonacci Sequence
fib(n) = fib(n-1) + fib(n-2)*multiplier
NB Uses recursion rather than Dynamic programming
"""
if n <= 2:
return 1
return fibonacci(n-1, multiplier) + fibonacci(n-2, multiplier) * multiplier
def fibonacciDynamic(n, multiplier=1):
"""
Generate Fibonacci Sequence
NB Uses Dynamic programming
"""
def processGeneration(populationHistory,generationCount):
generationSize = populationHistory[-1] + populationHistory[-2] * multiplier
populationHistory.append(generationSize)
return populationHistory[1:]
initialPopulation = [0,1]
return reduce(processGeneration, xrange(n-1), initialPopulation)[-1]
def mortalFibonacci(n, lifespan):
"""
Generate Fibonacci Sequence with Lifespan
NB Uses Dynamic programming so that sufficent generations are held in list
Last element of returned list contains the final generation
"""
def processGeneration(populationHistory,generationCount):
generationSize = populationHistory[-1] + populationHistory[-2] - populationHistory[0]
populationHistory.append(generationSize)
return populationHistory[1:]
initialPopulation = ([0] * (lifespan-1)) + [1]
return reduce(processGeneration, xrange(n), initialPopulation)[-1]
|
b86bf2023c5ca61cb86198a7b469aabeb837036e | pokhachevskiy/administrationUtility | /DataBaseWrapper.py | 1,068 | 3.5625 | 4 | import json
class DictWrapper:
def __init__(self, data):
self.data = data
# Обертка над базой данных для отладочного режима (не требует домена в окружении)
class DataBaseWrapper:
def __init__(self):
try:
db = open('db.json', 'r')
# Reading from json file
dict_db = json.load(db)
db.close()
except:
db = open('db.json', 'w')
dict_db = {'users': [{'sAMAccountName': ["test1"], 'amdzUserName': ["2134134"], 'amdzGroup': ["group"]},
{'sAMAccountName': ["test2"], 'amdzUserName': ["213adfadsf4134"],
'amdzGroup': ["group"]}]}
json_object = json.dumps(dict_db)
db.write(json_object)
db.close()
self.data = dict_db
def modify(self):
db = open('db.json', 'w')
json_object = json.dumps(self.data)
db.write(json_object)
db.close()
print(self.data)
|
8619254a232ae1d3acdb21f911a689b22b836bde | mbutkevicius/Sequences | /tuples_intro.py | 1,292 | 3.65625 | 4 | albums = [("Welcome to my Nightmare", "Alive Cooper", 1975),
("Bad Company", "Bad Company", 1974),
("Nightflight", "Budgie", 1981),
("More Mayhem", "Emilda May", 2011),
("Ride the Lightning", "Metallica", 1984),
]
print(len(albums))
# my solution (was right! yay me!)
for album in albums:
name, artist, year = album
print("Album: {}, Artist: {}. Year: {}"
.format(name, artist, year))
print()
# This is generally better though:
for name, artist, year in albums:
print("Album: {}, Artist: {}. Year: {}"
.format(name, artist, year))
# welcome = "Welcome to my Nightmare", "Alive Cooper", 1975
# bad = "Bad Company", "Bad Company", 1974
# budgie = "Nightflight", "Budgie", 1981
# imelda = "More Mayhem", "Emilda May", 2011
# metallica = "Ride the Lightning", "Metallica", 1984
#
# title, artist, year = metallica
# print(title)
# print(artist)
# print(year)
#
# table = ("Coffee table", 200, 100, 75, 34.50)
# print(table[1] * table[2])
#
# name, length, width, height, price = table
# print(length * width)
# print(metallica)
# print(metallica[0])
# print(metallica[1])
# print(metallica[2])
# Changes it into a list
# metallica2 = list(metallica)
# print(metallica2)
# metallica2[0] = "Master of Puppets"
# print(metallica2)
|
d656321a25f1158956cfa195418a4d8cc5ddaee5 | AlexDerr/Kattis | /Problems/Anagram Counting/AnagramCounting.py | 469 | 3.5 | 4 | import math
import string
import sys
occurences = {}
for line in sys.stdin:
str = line.splitlines()[0]
denominator = 1
for char in string.ascii_letters:
occurences[char] = 0
for char in str:
occurences[char] += 1
for item in occurences:
if occurences[item] != 0:
denominator *= math.factorial(occurences[item])
result = math.factorial(len(str))
result = result // denominator
print ( result )
|
9e5b696eb085411da4bcdfa2a74c8b6378d01fa0 | JadaShipp/ds-methodologies-exercises | /regression/split_scale.py | 6,025 | 3.609375 | 4 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, QuantileTransformer, PowerTransformer, RobustScaler, MinMaxScaler
def split_data(df, train_pct=0.75, seed=123):
train, test = train_test_split(df, train_size=train_pct, random_state=seed)
return train, test
def create_train_test_variables(df, X_col, target):
'''
Takes in a dataframe and splits the features into X and y
train and test variables
Returns each as a dataframe
'''
train, test = split_data(df)
X_train = train[[X_col]]
X_test = test[[X_col]]
y_train = [[target]]
y_test = [[target]]
return X_train, X_test, y_train, y_test
def standard_scaler(X_train, X_test):
"""
Takes in X_train and X_test dfs with numeric values only
Returns scaler, X_train_scaled, X_test_scaled dfs
"""
scaler = StandardScaler().fit(X_train)
X_train_scaled = (pd.DataFrame(scaler.transform(X_train),
columns=X_train.columns,
index=X_train.index))
X_test_scaled = (pd.DataFrame(scaler.transform(X_test),
columns=X_test.columns,
index=X_test.index))
return scaler, X_train_scaled, X_test_scaled
def merge_standard_scaled_to_original(train):
'''
Takes in a train dataframe and merges it with the original
unscaled dataframe then changes the scaled data column name
to reflect what it is
Returns the original dataframe with a new column
'''
X_train = train[['tenure']]
scaler = StandardScaler().fit(X_train)
X_train_scaled = (pd.DataFrame(scaler.transform(X_train),
columns=X_train.columns,
index=X_train.index))
df_plus_train = train.merge(X_train_scaled, how='inner', on=None, left_index=True, right_index=True)
df_plus_train.columns = ['customer_id', 'monthly_charges', 'tenure', 'total_charges', 'contract_type',
'tenure_scaled']
return df_plus_train
def scale_inverse(scaler, X_train_scaled, X_test_scaled):
"""Takes in the scaler and X_train_scaled and X_test_scaled dfs
and returns the X_train and X_test dfs
in their original forms before scaling
"""
X_train_unscaled = (pd.DataFrame(scaler.inverse_transform(X_train_scaled),
columns=X_train_scaled.columns,
index=X_train_scaled.index))
X_test_unscaled = (pd.DataFrame(scaler.inverse_transform(X_test_scaled),
columns=X_test_scaled.columns,
index=X_test_scaled.index))
return X_train_unscaled, X_test_unscaled
def uniform_scaler(X_train, X_test):
"""Quantile transformer, non_linear transformation - uniform.
Reduces the impact of outliers, smooths out unusual distributions.
Takes in a X_train and X_test dfs
Returns the scaler, X_train_scaled, X_test_scaled
"""
scaler = (QuantileTransformer(n_quantiles=100,
output_distribution='uniform',
random_state=123, copy=True)
.fit(X_train))
X_train_scaled = (pd.DataFrame(scaler.transform(X_train),
columns=X_train.columns,
index=X_train.index))
X_test_scaled = (pd.DataFrame(scaler.transform(X_test),
columns=X_test.columns,
index=X_test.index))
return scaler, X_train_scaled, X_test_scaled
def gaussian_scaler(X_train, X_test):
"""Transforms and then normalizes data.
Takes in X_train and X_test dfs,
yeo_johnson allows for negative data,
box_cox allows positive data only.
Returns Zero_mean, unit variance normalized X_train_scaled and X_test_scaled and scaler.
"""
scaler = (PowerTransformer(method='yeo-johnson',
standardize=False,
copy=True)
.fit(X_train))
X_train_scaled = (pd.DataFrame(scaler.transform(X_train),
columns=X_train.columns,
index=X_train.index))
X_test_scaled = (pd.DataFrame(scaler.transform(X_test),
columns=X_test.columns,
index=X_test.index))
return scaler, X_train_scaled, X_test_scaled
def min_max_scaler(X_train, X_test):
"""Transforms features by scaling each feature to a given range.
Takes in X_train and X_test,
Returns the scaler and X_train_scaled and X_test_scaled within range.
Sensitive to outliers.
"""
scaler = (MinMaxScaler(copy=True,
feature_range=(0,1))
.fit(X_train))
X_train_scaled = (pd.DataFrame(scaler.transform(X_train),
columns=X_train.columns,
index=X_train.index))
X_test_scaled = (pd.DataFrame(scaler.transform(X_test),
columns=X_test.columns,
index=X_test.index))
return scaler, X_train_scaled, X_test_scaled
def iqr_robust_scaler(X_train, X_test):
"""Scales features using stats that are robust to outliers
by removing the median and scaling data to the IQR.
Takes in a X_train and X_test,
Returns the scaler and X_train_scaled and X_test_scaled.
"""
scaler = (RobustScaler(quantile_range=(25.0,75.0),
copy=True,
with_centering=True,
with_scaling=True)
.fit(X_train))
X_train_scaled = (pd.DataFrame(scaler.transform(X_train),
columns=X_train.columns,
index=X_train.index))
X_test_scaled = (pd.DataFrame(scaler.transform(X_test),
columns=X_test.columns,
index=X_test.index))
return scaler, X_train_scaled, X_test_scaled
|
620b00694388d6590399efc4517b2cbcf7a3c6df | ly061/learn | /基础/嵌套函数.py | 418 | 4.0625 | 4 | # 外层函数的变量可以被内部函数调用,但是不能被修改。需要nonlocal 声明之后才能进行修改
def outer(num):
print('outing')
test_num = 10
def inner(num_inner):
nonlocal test_num
print(test_num)
test_num += 1
if type(num_inner) is int:
print('是整数')
else:
print('不是整数')
inner(num)
outer('1')
|
7c87545b7dbeeda6137fa964bdc18d1b47fb3cda | ly061/learn | /基础/士兵突击.py | 772 | 3.8125 | 4 | class Gun:
def __init__(self, model):
self.model = model
self.bullet_num = 0
def add_bullet(self, count):
self.bullet_num += count
def shoot(self):
if self.bullet_num <= 0:
print(f'{self.model}没有子弹了')
return
self.bullet_num -= 1
print(f'{self.model}tututu...{self.bullet_num}')
class Soldier:
def __init__(self, name):
self.name = name
self.gun = None
def fire(self):
if self.gun is None:
print(f'{self.name} did not have gun')
return
print(f'{self.name}gogogo')
self.gun.add_bullet(50)
self.gun.shoot()
ak47 = Gun("AK47")
xiaoming = Soldier("许三多")
xiaoming.gun = ak47
xiaoming.fire()
|
0f54ced3006c9c262d29354742a89688345a00f5 | ly061/learn | /基础/推导式.py | 592 | 3.75 | 4 | # 列表推导式
li1 = [x for x in range(5)]
li2 = [[x for x in range(3)] for x in range(3)]
li3 = [[x for x in range(3)] for x in range(3) if x > 0]
li4 = [(x, y) for x in range(3) for y in range(3)]
print(li1, li2, li3, li4, sep='\n')
# 字典推导式
text = 'i love you'
dic1 = {x: text.count(x) for x in text}
print(dic1)
# 生成器推导式(元祖推导式)
# 一个生成器只能运行一次,第一次迭代可以得到数据,第二次迭代就是空
gen = (x for x in range(10))
for i in gen:
print(i, end='')
for j in gen:
print(j)
print('--------------')
|
ea529fea345aaf3a88e6e0a9e02b1419c67c5603 | ly061/learn | /算法/冒泡排序.py | 1,097 | 3.90625 | 4 | # 两种解法都可以,第一种是把最大的往后排,第二种是把最小的往前排
def bubble_sort1(seq):
for i in range(len(seq)):
for j in range((len(seq)-i-1)):
if seq[j] > seq[j+1]:
seq[j], seq[j + 1] = seq[j + 1], seq[j]
return seq
def bubble_sort(seq):
for i in range(len(seq)):
exchange = False # 如果哪一次数组没有变化说明已经排好序了,这时就可以退出循环了
for j in range(i, len(seq)):
if seq[j] < seq[i]:
tmp = seq[j]
seq[j] = seq[i]
seq[i] = tmp
exchange = True
if not exchange:
break
return seq
def insertion_sort(seq):
if len(seq) > 1:
for i in range(1, len(seq)):
while i > 0 and seq[i] < seq[i - 1]:
tmp = seq[i]
seq[i] = seq[i - 1]
seq[i - 1] = tmp
i = i - 1
return seq
seq = [22, 1, 33, 4, 7, 6, 8, 9, 11]
print(bubble_sort(seq))
print(bubble_sort1(seq))
|
7258f76011bedbf7e28c7c9f9f0401e1a2b78f17 | ly061/learn | /基础/JSON序列化和反序列化.py | 543 | 4.21875 | 4 | # 序列化:把python转化为json
# 反序列化: 把json转为python数据类型
import json
# data = {"name": "ly", "language": ("python", "java"), "age": 20}
# data_json = json.dumps(data, sort_keys=True)
# print(data)
# print(data_json)
class Man(object):
def __init__(self, name, age):
self.name = name
self.age = age
def obj2json(obj):
return {
"name": obj.name,
"age": obj.age
}
man = Man("tom", 21)
jsonDataStr = json.dumps(man, default=lambda obj: obj.__dict__)
print(jsonDataStr) |
65a0a9921a54d50b0e262cccf64d980c2762f2f7 | edwinjosegeorge/pythonprogram | /longestPalindrome.py | 838 | 4.125 | 4 | def longestPalindrome(text):
'''Prints the longest Palendrome substring from text'''
palstring = set() #ensures that similar pattern is stored only once
longest = 0
for i in range(len(text)-1):
for j in range(i+2,len(text)+1):
pattern = text[i:j] #generates words of min lenght 2 (substring)
if pattern == pattern[::-1]: #checks for palendrome
palstring.add(pattern) #stores all palindrome
if len(pattern) > longest:
longest = len(pattern)
if len(palstring) == 0:
print("No palindrome substring found found")
else:
print("Longest palindrome string are ")
for pattern in palstring:
if len(pattern) == longest:
print(pattern)
longestPalindrome(input("Enter some text : "))
|
cc87e6aace0ee46f2d8b64170137d9e2a4cde7d8 | Omri49/Four-in-a-row | /four_in_a_row.py | 2,814 | 3.546875 | 4 | from ex12.game import Game
from ex12.ai import AI
from ex12.gui import GUI
from ex12.starting_menu import Menu
P_V_P = 1
AI_V_P = 2
P_V_AI = 3
AI_V_AI = 4
DRAW = -2
def player_decider(main_menu):
""" This will call game_loop with the proper player configurations"""
game_type = main_menu.get_player_type()
if game_type == P_V_P:
return 1, 2
elif game_type == AI_V_P:
ai_1 = AI(game, 1)
return ai_1, 2
elif game_type == P_V_AI:
ai_2 = AI(game, 2)
return 1, ai_2
else:
ai_1 = AI(game, 1)
ai_2 = AI(game, 2)
return ai_1, ai_2
def game_loop(player_1, player_2, gui, game):
""" The main loop function. Each iteration it defines the current player
and checks if there is a winner. IF the AIs turn is up, does the turn."""
if game.get_current_player() == 1: # PLAYER 1
player = player_1
current = 1
else:
player = player_2
current = 2
if game.get_is_winner():
if game.get_is_winner() == DRAW:
gui.framer()
return True # if game is winner, current gets sent. else, draw
if current == 2: # new - to fix the turns
current = 1
else:
current = 2
gui.framer(current)
return True
if isinstance(player, AI):
if gui.circle_done:
if current == player.get_player():
#gui.revert_circle_done()
player.find_legal_move()
move = player.get_last_found_move()
gui.game_binder(move)
gui.return_root().after(100, game_runner, player_1, player_2, gui, game)
def game_runner(player_1, player_2, gui, game):
""" Creating an outer function and an inner function makes it siginificantly easier """
if game_loop(player_1, player_2, gui, game):
play_again(player_1, player_2, gui, game)
def play_again(player_1, player_2, gui, game):
""" Checks if 'yes' has been pressed in the GUI, resets the game then
calls game_runner again. It will call itself again using AFTER aslong as the player hasn't pressed
a button. """
if gui.yes_pressed:
game.init_state() # resets the game
gui.reset_yes() # resets the yes. maybe change it to gui init state?
game_runner(player_1, player_2, gui, game)
else:
gui.return_root().after(100, play_again, player_1, player_2, gui, game)
# checks if yes has been pressed every once and a while
if __name__ == '__main__':
""" Defines the main."""
game = Game()
menu = Menu()
players = player_decider(menu)
gui = GUI(game)
game_runner(players[0], players[1], gui, game)
gui.mainloop()
|
d817775841ff14b2060a44cb2901713bce4a74f3 | maxigor/forcaAdivinhacao | /adivinhacao.py | 1,490 | 4.0625 | 4 |
def jogar():
import random
print("###############################")
print("Bem vindo ao jogo de Adivinhacao")
print("###############################")
numero_secreto = int(round(random.randrange(1 , 101)))
total_de_tentativas = 0
pontos = 1000
print("Escolha o nivel de dificuldade")
print("(1)-Facil (2)-Medio (3)-Dificil")
dificuldade = int(input("Insira o nivel de dificuldade: "))
if(dificuldade == 1):
total_de_tentativas = 20
elif(dificuldade == 2):
total_de_tentativas = 10
else:
total_de_tentativas = 5
print(" Voce possui {} tentativas".format(total_de_tentativas))
for rodada in range(1, total_de_tentativas + 1):
print("Tentativa {} de {}" .format(rodada ,total_de_tentativas ))
chute_str = input("digite o seu numero: ")
print("voce digitou ", chute_str)
chute = int(chute_str)
if(chute < 1 or chute > 100):
print("###############################")
print("O valor so deve ser entre 1 e 100")
print("###############################")
continue
maior = numero_secreto < chute
menor = numero_secreto > chute
if (numero_secreto == chute):
print("Voce acertou e ficou com {} pontos".format(pontos))
break
else:
if(menor):
print("O seu chute foi menor")
elif(maior):
print("O seu chute foi maior")
rodada = rodada + 1
pontos_perdidos = abs(numero_secreto - chute)
pontos = pontos - pontos_perdidos
print("Fim de jogo e ficou com {} pontos".format(pontos))
if(__name__ == "__main__"):
jogar()
|
d1a31cf00996eab089ce44d54e0ac15f562c82fa | jhylands/csteach | /prac4/extention pt2.py | 444 | 3.625 | 4 | def matrixSize(matrix):
print "Size:, " + str(len(matrix)) + "x" + str(len(matrix[0]))
def addMatrix(a,b):
c = []
for n in xrange(0,len(a)):
c.append([])
for i in xrange(0,len(b)):
c[n].append(a[n][i] + b[n][i])
return c
def T(a):
c = []
for i in xrange(0,len(a[0])):
c.append([])
for n in xrange(0,len(a)):
c[i].append(a[n][i])
return c
|
4d087b7671815aa117a2a03bdbc24b488b704553 | jhylands/csteach | /prac2/ex4.py | 420 | 3.9375 | 4 | def get_year():
year = int(raw_input("Please enter the year you wish to check."))
return year
#if a is devisible by b
def dvsbl(a,b):
return a%b ==0
def is_leap_year(year):
if dvsbl(year,4) and not dvsbl(year,100) or dvsbl(year,400):
return True
else:
return False
def main():
year = get_year()
if is_leap_year(year):
print year , " is a leap year!"
else:
print year , " is not a leap year!"
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.