blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9a18212013ab024142d825bd96b32d38b6a7b1ec | annasanchez27/bachelorthesis | /regrebackprop.py | 9,700 | 3.8125 | 4 | import numpy as np
import matplotlib.pyplot as plt
class NeuralNetwork():
"""
BASIC NEURAL NETWORK WORKING
"""
def __init__(self,hn):
self.Ni = 1 #Number of input nodes
self.Nh = hn #Number of hidden nodes
self.No = 1 #Number of output nodes
self.W_layer = [[],[]]
self.iterations = 1000
self.error_total_train = []
self.error_total_test = []
def initizalize_weights(self):
"""
Initialization of the weights. Random and Glorot initialization
:return:
"""
self.W_layer[0] = np.random.normal(0, 0.3, (self.Nh, self.Ni + 1))
self.W_layer[1] = np.random.normal(0, 0.3, (self.No, self.Nh + 1))
#self.W_layer[0] = np.random.normal(0,math.sqrt(2/(self.Ni+self.No)) , (self.Nh, self.Ni + 1))
#self.W_layer[1] = np.random.normal(0, math.sqrt(2/(self.Ni+self.No)), (self.No, self.Nh + 1))
def bias_vector(self, X):
"""
Creation of the bias vector
:param X: input data
:return:
"""
N = np.size(X,1)
Wo = np.ones([N, 1], dtype = int)
return Wo
def feed_forward(self, X, activation_function):
"""
Feedforward stage
:param X: input data
:param activation_function: type of activation function
:return:
"""
Y = []
Wo = self.bias_vector(X)
if activation_function == "tanh":
Y.append(np.tanh(np.dot(np.concatenate((X.T, Wo), axis=1), self.W_layer[0].T)))
if activation_function == "sigmoid":
Y.append(self.sigmoid(np.dot(np.concatenate((X.T, Wo), axis=1), self.W_layer[0].T)))
if activation_function == "relu":
Y.append(self.relu(np.dot(np.concatenate((X.T, Wo), axis=1), self.W_layer[0].T)))
Y.append(np.dot(np.concatenate((Y[0], Wo), axis=1), self.W_layer[1].T))
return Y
def backpropagation(self, input, target, learning_rate, activation_function):
"""
Backpropagation stage
:param input: input data
:param target: target data
:param learning_rate: learning rate
:param activation_function: activation function
:return: vector output (Y[0]: output of hiddden layer, Y[1]: output of the neural network)
"""
Wo = self.bias_vector(input)
for i in range(self.iterations):
Y = self.feed_forward(input, activation_function)
self.calculate_error(Y,target, 'train')
derv0 = -1*(target.T - Y[1])
derv1 = np.concatenate((Y[0],Wo), axis=1)
dwo = np.dot(derv0.T,derv1)
c = np.size(self.W_layer[1], 1)
dwi = np.dot(derv0,np.delete(self.W_layer[1], c-1, axis=1))
if activation_function == "tanh":
deriv2 = (1 - Y[0] ** 2)
if activation_function == "sigmoid":
deriv2 = Y[0]*(1-Y[0])
if activation_function == "relu":
deriv2 = self.reluDerivative(np.dot(np.concatenate((input.T, Wo), axis=1), self.W_layer[0].T))
delta_h = np.multiply(deriv2,dwi)
dwi = np.dot(delta_h.T, np.concatenate((input.T,Wo), axis=1))
self.W_layer[1] = self.W_layer[1] - learning_rate*dwo
self.W_layer[0] = self.W_layer[0] - learning_rate*dwi
return Y
def calculate_error(self, Y,target, t):
"""
Calculates the error
:param Y: predicted value
:param target: target value
:param t: type (test or train)
:return:
"""
error = sum(0.5 * (Y[1] - target.T) ** 2)
if t == "train":
self.error_total_train.append(error[0])
if t == "test":
self.error_total_test.append(error[0])
return error[0]
def plot_train(self, input, target, Y):
"""
Plot the prediction of the neural network
:param input: input data
:param target: target value
:param Y: predicted value
:return:
"""
x_axis = np.array([np.linspace(-1, 1, num=1000)])
y_axis = np.array(x_axis*x_axis)
plt.title('Figure representation after training data')
plt.scatter(input, target, color="m", marker="o", s=20, label="Data points")
#plt.plot(x_axis[0], y_axis[0], label="")
plt.scatter(input[0], Y[1], label="Train")
plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=0.)
plt.show()
def plot_test(self, input_train, target_train, input_test, target_test, Y, A):
"""
Plot test prediction
:param input_train: input data train
:param target_train: target data train
:param input_test: input data test
:param target_test: target data test
:param Y: prediction for training data
:param A: prediction
:return:
"""
x_axis = np.array([np.linspace(-1, 1, num=1000)])
y_axis = np.array(x_axis*x_axis)
plt.title('Prediction of the function')
plt.scatter(input_test, target_test, color="m", marker="o", s=20, label="Data points")
#plt.plot(x_axis[0], y_axis[0], label="Initial function")
plt.scatter(input_train[0], Y[1], label="Train", marker="o", s=20)
plt.scatter(input_test[0], A[1], color = 'green', label="Test", marker="+")
plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=0.)
plt.show()
def plot_error(self):
"""
Plot error in the training stage
:return:
"""
plt.ylim(0, 5)
plt.plot(self.error_total_train, label="Error in each iteration")
plt.title('Error in the training for normal distribution initialization')
plt.xlabel('Iteration')
plt.ylabel('Error')
plt.show()
def sigmoid(self,x):
"""
Sigmoid activation function
:param x: input
:return: output
"""
return 1 / (1 + np.exp(-x))
def relu(self, X):
"""
ReLu activation function
:param X: input
:return:
"""
return np.maximum(0, X)
def reluDerivative(self, x):
"""
ReLu derivative
:param x: input
:return:
"""
x[x <= 0] = 0
x[x > 0] = 1
return x
class CreationData():
def creation_data(self, numberofdata, type):
"""
Creation of the training data
:param numberofdata: number of data points
:param type: type of example
:return: input data, target data
"""
input = np.array([np.linspace(-1, 1, num=numberofdata)])
target = np.zeros(shape=(1,numberofdata))
if type == "sinus":
target = np.array(np.sin(np.pi * input * 2))
if type == "square":
target = np.array(input*input)
if type == "heaviside":
for i in range(len(input[0])):
if input[0][i]> 0:
target[0][i] = 1
else:
target[0][i] = 0
if type == "absolute":
for i in range(len(input[0])):
if input[0][i]> 0:
target[0][i] = input[0][i]
else:
target[0][i] = -input[0][i]
return input,target
def trainvstest(self, numberofdata, num_train):
"""
Division of train/test data
:param numberofdata: number of points
:param num_train: number of training points
:return:
"""
train = int(numberofdata*num_train/100)
test = numberofdata - train
return train,test
if __name__ == "__main__":
#Choose the percentages of training and test data
numberofdata = 100
num_train = 70
num_test = 30
learning_rates = [ 0.006,0.005, 0.007,0.008, 0.009]
learning_rates = sorted(learning_rates)
activation_functions = ['tanh', 'sigmoid', 'relu']
hidden_nodes = [2,3,4,5,6,7]
learning_plot = []
activation_plot = []
hidden_plot = []
error_plot = []
error = []
fig = "square"
CD = CreationData()
points_train, points_test = CD.trainvstest(numberofdata, num_train)
input_train, target_train = CD.creation_data(points_train, fig)
input_test, target_test = CD.creation_data(points_test, fig)
for act_funct in activation_functions:
er2 = []
for lr in learning_rates:
er = []
for hn in hidden_nodes:
NN = NeuralNetwork(hn)
NN.initizalize_weights()
Y = NN.backpropagation(input_train,target_train, lr, act_funct)
#NN.plot_train(input_train,target_train,Y)
#NN.plot_error()
A = NN.feed_forward(input_test, act_funct)
#NN.plot_test(input_train, target_train, input_test, target_test,Y,A)
er.append(NN.calculate_error(A, target_test, 'test'))
#learning_plot.append(lr)
#hidden_plot.append(hn)
#error_plot.append(NN.calculate_error(A, target_test, 'test'))
#error.append(NN.calculate_error(A, target_test, 'test'))
er2.append(er)
for error, lr in zip(er2,learning_rates):
plt.plot(hidden_nodes, error)
plt.scatter(hidden_nodes, error,label = 'Learning rate ' + str(lr), s=40)
plt.title('Error in the test set for the '+ str(act_funct) + " activation function")
plt.xlabel('Hidden nodes')
plt.ylabel('Error')
plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=0.)
plt.show()
#er2.append(er)
|
f75aae083dffe08049efe87a2faaab0c569a7ddc | poojavarshneya/algorithms | /merge_sort.py | 721 | 4.0625 | 4 | def merge(left, right):
result = []
if not left:
return right
if not right:
return left
l, r = 0, 0
while (l < len(left) and r < len(right)):
if (left[l] < right[r]):
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
if (l < len(left)):
result.extend(left[l:])
if (r < len(right)):
result.extend(right[r:])
return result
def merge_sort(array):
if len(array) < 2:
return array
middle = int(len(array) / 2)
a1 = merge_sort(array[:middle])
a2 = merge_sort(array[middle:])
return merge(a1, a2)
print(merge_sort([5,4,3,2,1]))
# 0,1,2,3,4,5,6 |
341277fc7834918e22442fce7fbea73b0ea954ac | saurabh-pandey/AlgoAndDS | /leetcode/arrays/third_max_a1.py | 1,381 | 4.15625 | 4 | #URL: https://leetcode.com/explore/learn/card/fun-with-arrays/523/conclusion/3231/
# Description
"""
Given integer array nums, return the third maximum number in this array. If the third maximum does
not exist, return the maximum number.
Example 1:
Input: nums = [3,2,1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: nums = [1,2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: nums = [2,2,3,1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
Constraints:
1 <= nums.length <= 104
-2^31 <= nums[i] <= 2^31 - 1
Follow up: Can you find an O(n) solution?
"""
def thirdMax(nums):
length = len(nums)
if length == 0:
return None
max_0 = nums[0]
for i in range(1, length):
max_0 = nums[i] if nums[i] > max_0 else max_0
if length < 3:
return max_0
minVal = -2**31 - 1
max_1 = minVal
for i in range(length):
if nums[i] == max_0:
continue
max_1 = nums[i] if nums[i] > max_1 else max_1
max_2 = minVal
for i in range(length):
if nums[i] == max_0:
continue
if nums[i] == max_1:
continue
max_2 = nums[i] if nums[i] > max_2 else max_2
if max_2 == minVal:
return max_0
else:
return max_2 |
c9da65feb5baaa463101fca0dd6ea3af172dc983 | lanxingjian/Learn-Python-the-Hard-Way | /ex8.py | 427 | 3.625 | 4 | formatter = "%s %s %s %s"
print formatter % (1,2,3,4)
print formatter % ("one", "two", "three" ,"four")
print formatter % (True,False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter %(
"I had this thing.",
"That you could type up right .",
"But it did not sing .",
"So I said goognight ."
)
# still don't understand the difference between %s and %r; |
2e05bc15339835e2b4970833f683819d26ccd3d3 | ppinko/python_exercises | /list/hard_has_identical.py | 486 | 3.71875 | 4 | """
https://edabit.com/challenge/q5FRS7dT2mrEQGG2J
"""
def has_identical(lst: list) -> bool:
return any(True for i in zip(*lst) for j in lst if list(i) == j)
""" Alternative solution """
def has_identical2(lst):
return any(tuple(i) in zip(*lst) for i in lst)
assert has_identical([
[4, 4, 4, 4],
[2, 4, 9, 8],
[5, 4, 7, 7],
[6, 4, 1, 0]
]) == True
assert has_identical([
[4, 4, 9, 4],
[2, 1, 9, 8],
[5, 4, 7, 7],
[6, 4, 1, 0]
]) == False
print('Success') |
9cea91ee50128081f18da42fcb1e9c8116dbb7f7 | Ruchitghadiya9558/python-program | /module/Date and Time module/datetime 1.py | 576 | 3.6875 | 4 | from datetime import datetime
from pytz import timezone
south_africa = ("Africa/Johannesburg")
currentedatetime = datetime.today()
print(currentedatetime)
print(type(currentedatetime))
print(currentedatetime.day)
print(currentedatetime.month)
print(currentedatetime.year)
print("----------------------------")
print(currentedatetime.hour)
print(currentedatetime.minute)
print(currentedatetime.second)
# current time
currentetime = currentedatetime.strftime("%H : %M : %S")
print(currentetime)
# south
currentetime1 = datetime.now(south_africa)
print(currentetime1) |
d6103756cec2ff8174dbf9a999bc2246409dc170 | bhnorris/PHYS200 | /PHYS200/chapter4Exercises.py | 2,211 | 4.5625 | 5 | """
Code from Chapter 4
Think Python: An Introduction to Software Design
Allen B. Downey
"""
from TurtleWorld import *
import math
def square(t, length):
"""Use the Turtle (t) to draw a square with sides of
the given length. Returns the Turtle to the starting
position and location.
"""
for i in range(4):
fd(t, length)
lt(t)
def polyline(t, n, length, angle):
"""Draw n line segments with the given length and
angle (in degrees) between them.
"""
for i in range(n):
fd(t, length)
lt(t, angle)
def polygon(t, n, length):
"""Draw regular polygon of sides specified by n
and length of sides by length
"""
angle = 360.0/n
polyline(t, n, length, angle)
def arc(t, r, angle):
"""Draw an arc segment, using a linear approximation,
of radius r and angle of the arc length by angle
"""
arc_length = 2 * math.pi * r * abs(angle) / 360
n = int(arc_length / 4) + 1
step_length = arc_length / n
step_angle = float(angle) / n
# making a slight left turn before the polyline reduces
# the error caused by the linear approximation of the arc
lt(t, step_angle/2)
polyline(t, n, step_length, step_angle)
rt(t, step_angle/2)
def circle(t, r):
"""Draw a circle using the arc function's linear approximation
to draw a full circle of 360 degrees
"""
arc(t, r, 360)
# _main_ ==> bob = Turtle()
# ==> r = radius
# _polyline_ ==> t = bob
# ==> n = int(2 * math.pi * radius / 4) + 1
# ==> length = 2 * math.pi * r / n
# ==> angle = float(360) / int(2 * math.pi * radius / 4) + 1
# _arc_ ==> t = bob
# ==>
def petal(t, r, angle):
for i in range(2):
arc(t, r, angle)
lt(t, 180-angle)
def flower(t, r, n, angle):
for i in range(n):
petal(t, r, angle)
lt(t, 360.0/n)
def isosceles(t, r, alpha):
y = r * math.sin(alpha * math.pi / 180)
rt(t, alpha)
fd(t, r)
lt(t, 90 + alpha)
fd(t, 2 * y)
lt(t, 90 + alpha)
fd(t, r)
lt(t, 180 - alpha)
def piePolygon(t, n, r):
beta = 360.0 / n
for i in range(n):
isosceles(t, r, beta / 2)
lt(t, beta)
|
690990951daf9fb9965b653da57a912a08ac1d6d | VigLinat/OpenWeather | /openweathermapapi.py | 2,002 | 3.53125 | 4 | import requests
messages = {200 : 'OK', 401 : 'invalid API key'}
def get_error_message(code_message):
return messages[code_message]
def get_current_weather(city, APIkey):
#api request for current weather
api_addres = 'https://api.openweathermap.org/data/2.5/weather'
APIparams = {'q' : city, 'APPID' : APIkey}
request_handler = requests.get(api_addres, params = APIparams)
return request_handler
def get_forecast(city, APIkey):
#api request for 5 day / 3 hour forecast
api_addres = 'https://api.openweathermap.org/data/2.5/forecast'
APIparams = {'q' : city, 'APPID' : APIkey}
request_handler = requests.get(api_addres, params = APIparams)
#forecast returns list of dictionaries
#weather['list'][1]['main']['temp'] example
return request_handler
def print_formatted_weather(weather):
#weather is dictionary about weather data
#prints formatted output for 5 day forecast or current weather
if 'list' in weather:
#if there is a "list" param, weather is a forecast,
#else, weather is a current weather
counter = weather['cnt']
weather = weather['list']
else:
counter = -1
if counter >= 0:
i = 0
prev_day = weather[0]['dt_txt'][8:10] #positions 8,9 contains month's day
while i < counter:
cur_day = weather[i]['dt_txt'][8:10]
if (cur_day != prev_day):
print('date: ', weather[i]['dt_txt'][0:11])
print('UTC time: ',weather[i]['dt_txt'][11:19], '\ntemperature: ', weather[i]['main']['temp'] - 273.15)
print('clouds: ', weather[i]['weather'][0]['main'],\
' ', weather[i]['clouds']['all'])
prev_day = cur_day
i = i + 1
print('\n')
else:
print('date & time: ', weather['dt_txt'])
print('temperature: ', weather['main']['temp'] - 273.15)
print('clouds: ', weather['weather']['main'],
' ', weather['clouds']['all'])
|
37d87239c556a46f1af2600489fee6aaabfce50f | awong05/epi | /test-for-palindromic-permutations.py | 563 | 3.875 | 4 | """
A palindrome is a string that reads the same forwards and backwards, e.g.,
"level", "rotator", and "foobaraboof".
Write a program to test whether the letters forming a string can be permuted to
form a palindrome. For example, "edified" can be permuted to form "deified".
Hint: Find a simple characterization of strings that can be permuted to form a
palindrome.
"""
from collections import Counter
def can_form_palindrome(s):
"""
Space complexity: O(c)
Time complexity: O(n)
"""
return sum(v % 2 for v in Counter(s).values()) <= 1
|
3a2939dc89db90d4ba3d1024da85bb9ad668119e | uyen-carolyn/CS-158B | /DNSclient.py | 3,736 | 3.625 | 4 | """BASE CODE PROVIDED BY BEN REED"""
import socket
import click
import struct
@click.command()
@click.argument('server')
@click.argument('query')
def resolve(server, query):
"""
This will resolve a query given a server IP address.
If the query looks like an IP address, it will return a domain name.
If the query looks like a domain name, it will return an IP address. (IPv4 and IPv6 if available)
Otherwise it will return an error message.
"""
# SETTING UP SOCKET CONNECTION.
sd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sd.connect((server, 53))
flags = 1 << 8
hdr = struct.pack('!HHHHHH', 17, flags, 1, 0, 0, 0)
parts = query.split('.')
# IDENTIFY QUERY AS IP ADDRESS OR DOMAIN NAME TO BE RESOLVED.
# IF CONDITION HANDLES IP ADDRESS.
if query.replace('.', '').isnumeric():
parts.reverse() # kudos to Miamia for explaining the reasoning behind reversing the query
parts.append("in-addr")
parts.append("arpa")
q = b''
for p in parts:
q += bytes([len(p)]) + p.encode()
q+= b'\0\0\x0c\0\1' # kudos to Tye for explaining how changing the question can reverse lookup
sd.send(hdr+q)
rsp = sd.recv(1024)
(id, flags, qcnt, acnt, ncnt, mcnt) = struct.unpack('!HHHHHH', rsp[0:12])
# VERIFY IF IP ADDRESS EXISTS
if acnt == 0: # kudos to Miamia for explaining the meaning of acnt's value at zero
print("No domain name exists under that address")
else:
resolved_domain = rsp[57:len(rsp) - 5].decode()
resolved_domain += "." + rsp[len(rsp) - 4: len(rsp)].decode()
r = rsp[-40:]
for i in range(0, acnt): # kudos to auk for explaining how formatting byte to ipv4 works
extracted = r[-4:] # ip is four values of up to four divided by a period
rsp_reverse = [str(j) for j in extracted] #since ipv4 is three numbers split between a period
rsp_reverse = ".".join(rsp_reverse)
print(" - " + rsp_reverse)
r = r[:len(r)-16] # to only get ip at the end
# ELSE CONDITION HANDLES DOMAIN NAME.
else:
q = b''
for p in parts:
q += bytes([len(p)]) + p.encode()
# RESOLVE TO GET IPV4
q1 = q + b'\0\0\1\0\1'
sd.send(hdr+q1)
rsp_ip_four = sd.recv(1024)
(id, flags, qcnt, acnt, ncnt, mcnt) = struct.unpack('!HHHHHH', rsp_ip_four[0:12])
# VERIFY IF DOMAIN EXISTS
if acnt == 0:
print("No IPv4 address exist under that domain")
else:
print("IPv4 Addresses: ")
r = list(rsp_ip_four)
for i in range(0, acnt): # kudos to Auk for explaining how formatting byte to ipv4 works
extracted = r[-4:] # ip is four values of up to three divided by a period
rsp_four = [str(j) for j in extracted] #since ipv4 is three numbers split between a period
rsp_four = ".".join(rsp_four)
print(" - " + rsp_four)
r = r[:len(r)-16] # to only get ip at the end
# RESOLVE TO GET IPV6
q2 = q + b'\0\0\x1c\0\1' # kudos to Tye for explaining what they meant by changing the question to get ipv4 vs ipv6
sd.send(hdr+q2)
rsp_ip_six = sd.recv(1024)
(id, flags, qcnt, acnt, ncnt, mcnt) = struct.unpack('!HHHHHH', rsp_ip_six[0:12])
# VERIFY IF DOMAIN EXISTS
if acnt == 0:
print("No IPv6 address exist under that domain")
else:
print("IPv6 Addresses: ")
r = rsp_ip_six.hex()
for m in range(0, acnt): # kudos to Auk for explaining how formatting byte to ipv6 works
extracted = r[-32:] # ip is six values of up to four divided by a colon
rsp_six = ":".join(extracted[n:n+4] for n in range(0,len(extracted), 4)) # since ipv6 is four numbers split between a colon
print(" - " + rsp_six)
r = r[:len(r)-56] # to only get ip at the end
# ADDED FOR BEST PRACTICE
if __name__ == '__main__':
resolve()
|
f05ce824139fec0cb77dccca802c40cbddc1015c | williamwebb35/Coding_Challenges | /FindingthePercentage.py | 1,360 | 4.28125 | 4 | #You have a record of N students. Each record contains the
#student's name, and their percent marks in Maths, Physics
#and Chemistry. The marks can be floating values. The user
#enters some integer followed by the names and marks for N
#students. You are required to save the record in a dictionary
#data type. The user then enters a student's name. Output the
#average percentage marks obtained by that student, correct to
#two decimal places.
#Input Format
#The first line contains the integer , the number of students.
#The next lines contains the name and marks obtained by that
#student separated by a space. The final line contains the name
#of a particular student previously listed.
#Sample Input
#3
#Krishna 67 68 69
#Arjun 70 98 63
#Malika 52 56 60
#Constraints
#2 <= N <= 10
#0 <= Marks <= 100
#Output Format
#Print one line: The average of the marks obtained by the particular
#student correct to 2 decimal places.
#Sample Output
#56.00
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
query_scores = student_marks[query_name]
print("{0:.2f}".format(sum(query_scores)/(len(query_scores))))
|
838fdf5d8d24feaa89d08ef78f434be1247e5756 | spohlson/Linked-Lists | /circular_linked.py | 1,557 | 4.21875 | 4 | """ Implement a circular linked list """
class Node(object):
def __init__(self, data = None, next = None):
self.data = data
self.next = next
def __str__(self):
# Node data in string form
return str(self.data)
class CircleLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def addNode(self, data):
# Add node to end of linked list to point to the head node to create/connect circle
node = Node(data)
node.data = data
node.next = self.head
if self.head == None:
self.head = node
if self.tail != None:
self.tail.next = node
self.tail = node
self.length += 1
def __str__(self):
# String representation of circular linked list
list_length = self.length
node = self.head
node_list = [str(node.data)]
i = 1 # head node has already been added to the list
while i < list_length:
node = node.next
node_list.append(str(node.data))
i += 1
return "->" + "->".join(node_list) + "->"
## Function to determine if a linked list has a loop ##
def circularLink(linked_list):
fast = linked_list.head
slow = linked_list.head
while fast != slow and fast != None:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
else:
return False
""" Create the Circular Linked List """
def main():
circle_ll = CircleLinkedList() # Create empty circular linked list
for x in range(1, 101): # Populate with 100 nodes
circle_ll.addNode(x)
print circle_ll # Display list as string
if __name__ == '__main__':
main() |
7f4bda3fe3bd950da74af02bf5c5da2082db01b3 | 0ReC0/ForPyQT | /qt7/1-5.py | 611 | 4 | 4 | import sqlite3
name = input()
with sqlite3.connect("music_db.sqlite") as con:
cur = con.cursor()
result = cur.execute("""
SELECT DISTINCT Track.Name FROM Track
WHERE AlbumId IN (
SELECT AlbumId FROM Album
WHERE ArtistId = (
SELECT Artist.ArtistId FROM Artist
WHERE Artist.Name = ?
)
) ORDER BY Name ASC
""", (name,))
for elem in result:
print(elem[0])
|
84d022feb419084c2d7b4383d92e17b0caa26707 | EnxiaoLuan/SWG_LIB | /WGbuilding.py | 3,917 | 3.734375 | 4 | # This function is design for the user to chose the line type to direct the SWG blocks in a waveguide
"""
Created on Thu Feb 20 15:49:24 2020
@author: edison.luan
"""
import numpy as np
import math
class curveclass:
def __init__(self,resolution=0.001):
self.resolution = resolution
def curve_func(self, eqn_key, params): # eqn_key is the number of function-type, params are the input parameters
switcher={
'Line': "2,%s*%s", ## y = a*x: first input = a, second input = x
'Circle': "2,math.sqrt(%s**2-(%s)**2)", ## y^2=r^2-x^2: first input = radius, second input = x
'Sigmoid': "3,%s/(1+math.exp(-%s*%s))", ## y = a/(1+e^(-b*x)): first input = a, second input = b, third input = x
'Lorentzian': "3,%s/(1+%s*(%s)**2)" ## y = a/(1+b*x^2): first input = a, second input = b, third input = x
}
self.nparams, self.eqn = switcher[eqn_key].split(',')
self.nparams = int(self.nparams)
if(len(params)== self.nparams):
self.ans = eval(self.eqn%tuple(params))
return(self.ans)
else:
print('Incorrect number of variables, %d required'%(self.nparams))
def step_func(self, xo, xn, pitch, width, eqn_key, params):
xarray = list(np.arange(xo,xn+pitch,self.resolution)) # get all x points from xo to (xn + 1*pitch) with default resolution, the last point will be deleted later
#xhigh = list(np.arange(xo,xn+pitch,self.resolution))
xhigh = list(np.arange(xo,xn,self.resolution))
yarray=[]
for i in range(0,len(xarray)):
params.append(xarray[i]) # add x value into the params list
yarray.append(self.curve_func(eqn_key,params)) #run the curve_func to calculate y value
del params[int((len(params)-1))] # remove the added x value in order to add next x value
yhigh = []
for i in range(0,len(xhigh)):
params.append(xhigh[i]) # add x value into the params list
yhigh.append(self.curve_func(eqn_key,params)) #run the curve_func to calculate y value
del params[int((len(params)-1))] # remove the added x value in order to add next x value
ii = 0
while ii < (len(xarray)-1):
dis = math.sqrt((xarray[ii+1]-xarray[ii])**2+(yarray[ii+1]-yarray[ii])**2) # calculate the distance between two adjacent points
if dis >= pitch:
#x_new.append(xarray[ii+1]) # put the point into new x_array
ii=ii+1 # add i to i+1
else:
del xarray[ii+1]
del yarray[ii+1]
# extract the theta information for each point
theta = []
for j in range(0,(len(xarray)-1)):
theta.append(math.degrees(math.atan((yarray[j+1]-yarray[j])/(xarray[j+1]-xarray[j]))))
thigh = []
for j in range(0,(len(xhigh)-1)):
thigh.append(math.atan((yhigh[j+1]-yhigh[j])/(xhigh[j+1]-xhigh[j])))
del xarray[-1] # remove the last point from x, y arrays, to make a constant index of x, y and angle arrays
del yarray[-1]
del xhigh[-1]
del yhigh[-1]
xcore = []
ycore = []
for ii in range(0,len(xhigh)):
xcore.append(xhigh[ii]-math.sin(thigh[ii])*(width/2))
ycore.append(yhigh[ii]+math.cos(thigh[ii])*(width/2))
#xcore.append(xhigh[ii])
#ycore.append(yhigh[ii]+w/2)
for ii in range(1,len(xhigh)-1):
xcore.append(xhigh[-ii]+math.sin(thigh[-ii])*(width/2))
ycore.append(yhigh[-ii]-math.cos(thigh[-ii])*(width/2))
#xcore.append(xhigh[-ii])
#ycore.append(yhigh[-ii]-w/2)
return xarray, yarray, theta, xcore, ycore
|
aecc4825912472a9fd2d1b911c4a97b0e66280d4 | gohdong/algorithm | /programmers/81302.py | 1,380 | 3.5625 | 4 | def solution(places):
answer = []
direction = {
'U' : [-1,0],
'R' : [0 ,1],
'D' : [ 1,0],
'L' : [0,-1],
}
def check_around(room,i,j,i2,j2):
is_ok = True
for d in direction:
y = i + direction[d][0]
x = j + direction[d][1]
if y == i2 and x == j2:
continue
elif y <0 or y > 4 or x <0 or x > 4:
continue
else:
if room[y][x] == 'P':
return False
elif room[y][x] == 'X':
continue
elif i==i2 and j==j2:
is_ok = is_ok and check_around(room,y,x,i,j)
return is_ok
for room in places:
flag = 1
for i,row in enumerate(room):
if flag:
for j,object in enumerate(row):
if object == 'P':
if not check_around(room,i,j,i,j):
flag = 0
break
answer.append(flag)
return answer
print(solution([["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]])) |
ae5a715067594cf95bb4e2e39f312f05fa2b82d7 | SophieLi0720/Calculator | /calculator_gui_creator.py | 4,351 | 3.796875 | 4 | from tkinter import *
from tkinter.ttk import *
B_ROWS = 5
B_COLUMN = 4
KEYS = [['AC', '+/-', '%', '/'],
['7', '8', '9', '*'],
['4', '5', '6', '-'],
['1', '2', '3', '+'],
['0', '.', '=', None]
]
class Calculator:
"""This class created the calculator window, display section and all the buttons"""
def __init__(self, window):
"""this is the upper frame which contains the result and equation window"""
self.equation = StringVar()
self.result = DoubleVar()
self.state = False # If the "=" key is pressed
frame_appearance = Style()
frame_appearance.configure('TFrame', background='white')
self.frame_display = Frame(window, borderwidth=8, relief=GROOVE, style="TFrame")
self.frame_display.pack_propagate(0)
self.frame_display.grid(row=0, column=0, sticky="EWNS")
self.frame_display.columnconfigure(0, weight=1)
# This is an equation label which will be updated every time a key is pressed.
self.display_equation = Label(self.frame_display, background='white',
textvariable=self.equation, font=('Helvetica', 12, 'bold', 'italic'))
self.display_equation.grid(row=0, column=0, padx=10, pady=10, sticky="ENS")
# This is a result label, which will show the result.
self.result_label = Label(self.frame_display, background='white',
textvariable=self.result, font=('Helvetica', 20, 'bold'))
self.result_label.grid(row=1, column=0, padx=10, sticky="ENS")
# This is the bottom frame contains all the keys.
self.frame_buttons = Frame(window, borderwidth=8, relief=GROOVE)
self.frame_buttons.pack_propagate(0)
self.frame_buttons.grid(row=1, column=0, sticky="EWNS")
self.button_appearance = Style()
self.button_appearance.configure('TButton', font=('Helvetica', 18, 'bold'))
# Creating individual frame for every button and add button
# into that from and label it by getting the values from list - keys
for i in range(B_ROWS): # the number of rows of buttons
self.frame_buttons.rowconfigure(i, weight=1) # setting the weight of rows to 1
for j in range(B_COLUMN): # number of cols of buttons
self.frame_buttons.columnconfigure(j, weight=1) # setting the weight of cols to 1
if KEYS[i][j] is not None:
self.frame_per_button = Frame(self.frame_buttons, height=50, width=100)
self.frame_per_button.pack_propagate(0)
self.frame_per_button.grid(row=i, column=j, sticky="EWNS")
self.buttons = Button(self.frame_per_button, text=KEYS[i][j],
style='TButton', command=lambda x=KEYS[i][j]: self.append_num(x))
self.buttons.pack(fill=BOTH, expand=1)
if i == 4 and j == 2:
# Merge last 2 columns and show equal sign it it.
self.frame_per_button.grid(columnspan=2)
def append_num(self, char):
"""this method will get the values from the buttons and show on the equation label,
once "=" is pressed it will call the function to process the equation."""
if self.equation.get() == "Error":
self.equation.set(char)
else:
if char == '=':
self.state = False
if self.equation.get() == '':
pass
else:
try:
result = eval(self.equation.get())
except Exception:
self.equation.set('Error')
self.result.set(0)
else:
self.result.set(result)
elif char == 'AC':
self.equation.set('')
self.result.set(0)
else:
if not self.state:
self.state = True
if char.isdigit():
self.equation.set(char)
else:
self.equation.set(str(self.result.get()) + char)
else:
self.equation.set(self.equation.get() + char)
|
31c0e55955cf10676b253c0c4b76252d134e0f14 | rknightly/primedice-simulator | /primediceSim/tests/test_results.py | 6,180 | 3.625 | 4 | from unittest import TestCase
from primediceSim.simulation import Results, AverageResults
class TestFindAverageBal(TestCase):
"""Ensure that the average balances are appropriately calculated"""
def test_single_result(self):
sample_result = Results([5, 6, 7, 5, 7])
average_result = AverageResults([sample_result])
self.assertEqual(average_result.overall_average_balance, 6,
"Average balance was incorrectly calculated over one"
" result")
def test_multiple_results(self):
sample_results = [Results([5, 6, 7, 9, -2]),
Results([2, 6, 8, 8]),
Results([0, 7, 14])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.overall_average_balance, 6,
"Average balance was incorrectly calculated over"
" multiple results")
def test_float_results(self):
sample_results = [Results([3, 5, 4, 1, 7]),
Results([5, 5, 10, 1])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.overall_average_balance, 4,
"Average balance was incorrectly calculated over"
" multiple results with a float average balance")
class TestFindAverageRollsUntilBankrupt(TestCase):
"""Ensure that the average rolls until bankrupt is found and returned
properly
"""
def test_single_result(self):
sample_result = Results([5, 6, 7, 5, 7])
average_result = AverageResults([sample_result])
self.assertEqual(average_result.find_average_rolls_until_bankrupt(), 4,
"Average rolls until bankrupt was incorrectly"
" calculated over one result with positive integers")
def test_multiple_results(self):
sample_results = [Results([5, 6, 7, 9, -2]),
Results([2, 6, 8, 8]),
Results([0, 7, 14])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.find_average_rolls_until_bankrupt(), 3,
"Average rolls until bankrupt was incorrectly"
" calculated over multiple results")
def test_float_average(self):
sample_results = [Results([3, 5, 4, 1, 7]),
Results([5, 5, 10, 1])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.find_average_rolls_until_bankrupt(), 3,
"Average rolls until bankrupt was incorrectly"
" calculated over multiple results with a float"
" average rolls value")
class TestFindAverageBalances(TestCase):
"""Ensure that the sequence of average balances is properly found"""
def test_single_result(self):
sample_result = Results([5, 6, 7, 5, 7])
average_result = AverageResults([sample_result])
self.assertEqual(average_result.get_average_balances(),
[5, 6, 7, 5, 7],
"Average balances were incorrectly calculated over "
"one result with integers")
def test_multiple_results(self):
sample_results = [Results([5, 8, 10, 9, 12]),
Results([4, 6, 5, 12]),
Results([0, 7, 15])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.get_average_balances(),
[3, 7, 10, 7, 4],
"Average balances were incorrectly calculated over"
"multiple results with integers")
def test_float_average(self):
sample_results = [Results([3, 5, 4, 1, 7]),
Results([4, 5, 10, 1])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.find_average_balances(),
[3, 5, 7, 1, 3],
"Average balances were incorrectly calculated over"
" multiple results with float average values")
class TestFindMedianBalances(TestCase):
"""Ensure that the median balances are correctly calculated"""
def test_single_result(self):
sample_result = Results([5, 6, 7, 5, 7])
average_result = AverageResults([sample_result])
self.assertEqual(average_result.get_median_balances(),
[5, 6, 7, 5, 7],
"Median balances were incorrectly calculated over "
"one result with integers")
def test_multiple_results(self):
sample_results = [Results([5, 8, 10, 9, 12]),
Results([4, 6, 5, 12]),
Results([0, 7, 15])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.get_median_balances(),
[4, 7, 10, 9, 0],
"Median balances were incorrectly calculated over"
"multiple results with integers")
def test_float_median(self):
sample_results = [Results([3, 5, 4, 1, 7]),
Results([4, 5, 10, 1])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.find_median_balances(),
[3, 5, 7, 1, 3],
"Median balances were incorrectly calculated over"
" multiple results with float average values")
def test_zeroes(self):
sample_results = [Results([5, 8, 10, 9, 12, 14, 16, 14, 13, 10, 6]),
Results([4, 6, 5, 12]),
Results([0, 7, 15])]
average_result = AverageResults(sample_results)
self.assertEqual(average_result.get_median_balances(),
[4, 7, 10, 9, 0],
"Median balances were incorrectly calculated when"
"data contained several ending medians of 0")
|
2be0e2cc73f78ec061464fca3630340435298f5c | Parasbuda/Python-start | /condition.py | 137 | 4.1875 | 4 | n=int(input("Enter the number: "))
if n > 0:
print("n is Positive")
elif n<0:
print("n is negative")
else:
print("n is zero") |
c69a97f14bd06d799cb4b43605b5bde43e5f72d0 | paulan94/CTCIPaul | /4_2_mintree.py | 730 | 3.53125 | 4 | #given sorted arr w unique int elements write alg to create BST w min height
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def create_min_bst(arr, start, end):
if start > end:
return None
else:
mid = (start + end)//2
root = Node(arr[mid])
root.left = create_min_bst(arr, start, mid-1)
root.right = create_min_bst(arr, mid+1, end)
return root
def print_bst_preorder(root):
if not root: return None
print (root.val)
print_bst_preorder(root.left)
print_bst_preorder(root.right)
arr = [1,2,3,4,5,6,7,9]
r = create_min_bst(arr,0, len(arr)-1)
print_bst_preorder(r)
#5,3,2,1,4,7,6,9
|
fc32b964eed3f0e1ff6f02355b8abf7e3402b81e | petewurster/CIS-106 | /Completed Exercises/wurster_character_counter_E1.py | 814 | 4.0625 | 4 | '''
analyze user-input string and display analysis
'''
#main prog as func
def countChars(x):
#values set to zero to begin tallying
up,low,dig,sym,sp=0,0,0,0,0
#iterate across string 'x'
for char in x:
#test charachters and tally appropriately
if char.isalpha():
if char.isupper(): up+=1
else: low+=1
if char.isdigit(): dig+=1
if not char.isalnum() and not char.isspace(): sym+=1
if char.isspace(): sp+=1
#display results
print('\nstring length:',len(x))
print('letters: ',up+low,'\t(uppercase:',up,'\tlowercase:',low,')',sep='')
print('numbers:',dig)
print('symbols:',sym)
print(' spaces:',sp)
#calls function assigning user input directly to 'x'
countChars(input('Type the string to be analyzed: '))
|
0a21ba3998d2a73f9aa369a1748d1b1b6b6af23d | JardelBrandon/Algoritmos_e_Programacao | /Atividades/Roteiro 5 - While/Programas/Roteiro 5 Questão 14.py | 2,724 | 3.78125 | 4 | '''
14. Uma loja deseja conhecer o perfil de seus (suas) clientes e para isso vai fazer uma pesquisa
usando um programa que ficará no caixa. Ele vai perguntar a cada cliente no momento da compra
as seguintes informações: idade, valor da compra e tipo de pagamento (C: cartão; V: à vista).
Essas perguntas serão feitas enquanto a resposta for SIM. Quando a resposta for NÃO, a pesquisa
deve ser encerrada e o programa deve exibir as seguintes informações:
- a quantidade de vendas realizadas;
- o total de vendas à vista e no cartão;
- a idade do cliente mais jovem;
- o valor da maior compra;
- a média de compras feitas à vista;
'''
vendas = 0
vendas_a_vista = 0
vendas_no_cartao = 0
maior_compra = 0
media_a_vista = 0
idade = float(input("Digite a idade do cliente : "))
valor_da_compra = float(input("Digite o valor da compra : "))
pagamento = input("Digite a forma de pagamento: \nConsidere (C para Cartão ou V para à vista)")
resposta = input("Digite se deseja continuar a pesquisa: \nConsidere (SIM para continuar ou NÃO para encerrar)")
vendas += 1
maior_compra = valor_da_compra
jovem = idade
while True :
idade = float(input("Digite sua idade : "))
valor_da_compra = float(input("Digite o valor da compra : "))
pagamento = input("Digite a forma de pagamento: \nConsidere (C para Cartão ou V para à vista)")
resposta = input("Digite se deseja continuar a pesquisa: \nConsidere (SIM para continuar ou NÃO para encerrar)")
vendas += 1
if pagamento == "V" :
vendas_a_vista += 1
if pagamento == "C" :
vendas_no_cartao += 1
if idade < jovem :
jovem = idade
if valor_da_compra > maior_compra :
maior_compra = valor_da_compra
if resposta == "NÃO" :
break
media_a_vista = vendas / vendas_a_vista
print("Total de vendas à vista e no cartão: ", vendas)
print("Idade do cliente mais jovem :", jovem)
print("Valor da maior compra :", maior_compra)
if media_a_vista == 0 :
print("Média de compras feitas à vista : 0")
else :
print("Média de compras feitas à vista :", media_a_vista)
# O Algoritmo do programa realiza os seguintes comandos :
# Declara os valores das variáveis
# Realiza a repetição pela primeira vez fora do laço while para se ter um valor de comparação
# Entra em um laço de repetição afirmando que o comando while (Enquanto) é True (Verdadeiro)
# Executa as operações matemáticas, faz as comparações das lógicas
# Realiza as operações em seus respectivos encadeamentos
# Imprime na tela o total de vendas, cliente mais jovem, valor da maior compra e média das compras feitas à vista
# Acrescidos das mensagens em aspas
# Atendendo o que se pede na questão
|
075d07119e257822279609175a8f99e14de7a180 | muziceci/Python-learning | /second/6、统计考试成绩.py | 973 | 3.953125 | 4 | # 统计考试成绩
def average_score(lst):
sum=0
for k in lst:
sum+=lst[k]
return sum/len(lst)
def sort_scores(lst):
lst1=sorted(lst,key=lst.get)
lst2=lst1.reverse()
lst3={}
for i in lst1:
lst3[i]=lst[i]
return lst3
def highest_score(lst):
temp=0
flag={}
for k in lst:
if lst[k]>temp:
flag=k
temp=lst[k]
return flag,lst[flag]
def lowest_score(lst):
temp=101
flag={}
for k in lst:
if lst[k]<temp:
flag=k
temp=lst[k]
return flag,lst[flag]
if __name__=="__main__":
student={"zhangsan":90,"lisi":78,"wangermazi":38,"goudan":67,"cuihua":96}
print("所有同学:",student)
print("平均成绩:",average_score(student))
print("按成绩降序排列:",sort_scores(student))
print("分数最高的同学:",highest_score(student))
print("分数最低的同学:",lowest_score(student))
|
245d2cbda8ad5f1d17291bcee4314e1828a71280 | seanchen513/leetcode | /matrix/0048_rotate_image.py | 4,413 | 4.46875 | 4 | """
48. Rotate Image
Medium
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
"""
from typing import List
###############################################################################
"""
Solution 1: transpose matrix, then reverse each row.
Can also reverse each column, then transpose matrix.
(r, c) -> (c, r) -> (c, n-r-1)
Note: to rotate 90 degrees CCW, can do either:
(1) transpose matrix, then reverse each row, OR
(2) reverse each column, then transpose matrix.
O(n^2) time
O(1) extra space
Runtime: 20 ms, faster than 99.70% of Python3 online submissions
Memory Usage: 12.9 MB, less than 97.92% of Python3 online submissions
"""
class Solution:
def rotate(self, m: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(m)
# transpose matrix
for i in range(n):
for j in range(i+1, n):
m[i][j], m[j][i] = m[j][i], m[i][j]
# reverse each row (of transposed matrix)
n1 = n - 1
for i in range(n):
for j in range(n//2):
m[i][j], m[i][n1-j] = m[i][n1-j], m[i][j]
"""
Solution 1b: reverse each column, then transpose matrix
"""
class Solution1b:
def rotate(self, m: List[List[int]]) -> None:
n = len(m)
m.reverse() # ie, reverse each column
# transpose matrix
for i in range(n):
for j in range(i+1, n):
m[i][j], m[j][i] = m[j][i], m[i][j]
###############################################################################
"""
Solution 2: do series of 4-position swaps. Ie, rotate 4 rectanges at a time.
0,0 0, n n,n n, 0
0,1 1, n n,n-1 n-1, 0
0,2 2, n n,n-2 n-2, 0
1,1 1,n-1 n-1,n-1 n-1,1
1,2 2,n-1 n-1,n-2 n-2,1
r,c c,n-r n-r,n-c n-c,r
Example:
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]]
First elements of each 4-cycle:
[
[ 5, 1, 9, ],
[ , 4, , ],
[ , , , ],
[ , , , ]]
"""
class Solution2:
def rotate(self, m: List[List[int]]) -> None:
n = len(m)
for r in range(n//2):
c = r
c2 = r2 = n - r - 1
for c in range(r, r2):
#print(f"r,c = {r},{c}")
m[r][c], m[c][r2], m[r2][c2], m[c2][r], = m[c2][r], m[r][c], m[c][r2], m[r2][c2]
c2 -= 1
###############################################################################
"""
Solution 3: concise, but not in-place...
"""
class Solution3:
def rotate(self, m: List[List[int]]) -> None:
return [list(row[::-1]) for row in zip(*m)]
###############################################################################
if __name__ == "__main__":
def print_matrix(mat):
print()
for row in mat:
for x in row:
print(f"{x:3}", end = "")
print()
def test(mat, comment=None):
print("="*80)
if comment:
print(comment)
print_matrix(mat)
res = sol.rotate(mat) # return value used for the non in-place solution
if res:
print(f"\nres = {res}\n")
else:
print_matrix(mat)
#sol = Solution() # transpose matrix, then reverse each row
sol = Solution1b() # reverse each column, then transpose matrix
#sol = Solution2() # series of 4-position swaps
#sol = Solution3() # concise, but not in-place
comment = "LC ex1"
mat = [
[1,2,3],
[4,5,6],
[7,8,9]]
test(mat, comment)
comment = "LC ex2"
mat = [
[5,1,9,11],
[2,4,8,10],
[13,3,6,7],
[15,14,12,16]]
test(mat, comment)
comment = "Trivial matrix"
mat = [[1]]
test(mat, comment)
|
3429530c5c661b938038a7483cb19bb512a6c22f | rominecarl/hafb-intro-python | /for_loops.py | 649 | 4.5625 | 5 | """
Practice for loops
Keyword: for
Python uses for each. parses through list and processes each element. No need to keep track of indexes etc
"""
cities = ["London", "New York","Madrid", "Paris", "Ogden"]
# iterate over the collection
for city in cities:
print(city)
#first item is the key, 2nd is the value
d = {'alice':'801-123-8988',
'pedro':'956-445-78-8966',
'john':'651-321-66-4477'}
#iterate over a dictionary
for item in d:
print(item) # by default a for loop processes the key of a dictionary
print(item, "=>", d[item]) # use the key to point to the element within the dictionary
|
52474f8c93a465a28eb2e7883a27176c357464bb | davidOdahcam/Algoritmos-e-Estruturas-de-Dados-I | /Lista Encadeada/main.py | 1,619 | 3.703125 | 4 | import time
import random
from linkedList import LinkedList
capacities = [10, 100, 1000, 10000, 100000, 1000000] # Capacidades solicitadas pelo professor
for c in capacities:
linkedList = LinkedList(c)
# Marcando o início da execução
begin = int(round(time.time() * 1000))
for i in range(linkedList.capacity):
linkedList.addBegin(random.randint(0, linkedList.capacity))
# Marcando o fim da execução
end = int(round(time.time() * 1000))
# Imprimindo o tempo de execução
print('Tempo de execução para inserir {} elementos: {}ms'.format(linkedList.capacity, (end - begin)))
# Armazenando a lista encadeada em um vetor
linkedList_array = linkedList.toList()
# Marcando o início da execução
begin = int(round(time.time() * 1000))
for i in range(linkedList.capacity):
linkedList.removeBegin()
# Marcando o fim da execução
end = int(round(time.time() * 1000))
# Imprimindo o tempo de execução
print('Tempo de execução para remover {} elementos: {}ms'.format(linkedList.capacity, (end - begin)))
# Marcando o início da execução
begin = int(round(time.time() * 1000))
# Realizando a ordenação no array
linkedList_array = linkedList.mergeSort(linkedList_array)
# Convertendo o array para uma lista encadeada
linkedList.toLinkedList(linkedList_array)
# Marcando o fim da execução
end = int(round(time.time() * 1000))
# Imprimindo o tempo de execução
print('Tempo de execução para ordenar {} elementos: {}ms\n'.format(linkedList.capacity, (end - begin)))
# Desfazendo a lista encadeada e o array
del linkedList, linkedList_array |
6b560034d2682cf1bfa75a685ef879fc6fe6e568 | venkatram64/python_ml | /pwork/p_ex02.py | 1,428 | 3.5 | 4 | import pandas as pd
from pandas import Series, DataFrame
import numpy as np
ser1 = Series([1, 2, 3, 4])
print(ser1)
ser2 = Series(['a', 'b', 'c'])
print(ser2)
#Create a pandas Index
idx = pd.Index(["New Yourk", "Los Angeles", "Chicago",
"Houston", "Philadelphia", "Phoenix",
"San Antonio", "San Diego", "Dallas"])
print(idx)
pops = Series([8550, 3972, 2721, 2296, 1567, np.nan, 1470, 1395, 1300],
index=idx, name="Population")
print(pops)
state = Series({"New Your": "New York", "Los Angeles": "California",
"Phoenix": "Arizona","San Antonio":"Texas",
"San Diego": "California", "Dallas": "Texas"}, name="State")
print(state)
area = Series({"New Your": 302.6, "Los Angeles": 468.7,
"Philadelphia": 134.1, "Phoenix": 516.7, "Austin": 322.48}, name="Area")
print(area)
mat = np.arange(0, 9).reshape(3, 3)
print(mat)
print(DataFrame(mat))
# Let's append new data to each Series
pops.append(Series({"Seattle": 684, "Denver": 683})) # Not done in place
df = DataFrame([pops, state, area]).T
df.append(DataFrame({"Population": Series({"Seattle": 684, "Denver": 683}),
"State": Series({"Seattle": "Washington", "Denver": "Colorado"}),
"Area": Series({"Seattle": np.nan, "Denver": np.nan})}))
df = DataFrame([pops, state, area]).T
# Saving data to csv file
df.to_csv("cities.csv") |
b7a3252fa1bec45fc59dc81fcca5c1efce1cc708 | codrelphi/stackoverflow.com | /python/last_number_from_loop.py | 620 | 3.921875 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
#=================================================================================
# author: Chancerel Codjovi (aka codrelphi)
# date: 2019-10-11
# source: https://stackoverflow.com/questions/58342215/getting-the-last-number-from-a-for-loop/58342301
#=================================================================================
# use a list
def LCM(minN,maxN):
count = 1
results = []
for i in range(count,(maxN*count)+1):
results.append(minN*count)
count = count + 1
print(results[-1]) # print the last elements of the list.
LCM(5, 7) # print 35.
|
3cde7e644ec35aa85549ccbbebff462fcea73e9f | koziscool/embankment_4 | /e206.py | 1,601 | 3.609375 | 4 |
import time
def e206():
sevens_number = 7 + 10 ** 8
sevens_number_squared = sevens_number ** 2
while sevens_number_squared < 2 * 10 ** 16:
sevens_squared_str = str(sevens_number_squared)
if ( sevens_squared_str[0] == '1' and sevens_squared_str[2] == '2' and
sevens_squared_str[4] == '3' and sevens_squared_str[6] == '4' and
sevens_squared_str[8] == '5' and sevens_squared_str[10] == '6' and
sevens_squared_str[12] == '7' and sevens_squared_str[14] == '8' and
sevens_squared_str[16] == '9' ):
return sevens_number * 10
sevens_number += 10
sevens_number_squared = sevens_number ** 2
threes_number = 3 + 10 ** 8
threes_number_squared = threes_number ** 2
while threes_number_squared < 2 * 10 ** 16:
threes_squared_str = str(threes_number_squared)
if ( threes_squared_str[0] == '1' and threes_squared_str[2] == '2' and
threes_squared_str[4] == '3' and threes_squared_str[6] == '4' and
threes_squared_str[8] == '5' and threes_squared_str[10] == '6' and
threes_squared_str[12] == '7' and threes_squared_str[14] == '8' and
threes_squared_str[16] == '9' ):
return threes_number * 10
threes_number += 10
threes_number_squared = threes_number ** 2
if __name__ == '__main__':
start = time.time()
print
print "Euler 206 solution is:", e206()
end = time.time()
print "elapsed time is: %.4f milliseconds" % (1000 * (end - start))
|
f00e7edd5240b74c72905823b62d432af7a1d948 | nishikaverma/Python_progs | /sortde().py | 338 | 3.921875 | 4 | mylist=[]
n=1
while n<6:
num=input("enter an integer")
mylist.append(num)
n=n+1
print("the list you entered is", mylist)
i=0
l=len(mylist)
while i<l:
j=i
while j<l:
if mylist[j]>mylist[j+1]:
mylist[i],mylist[j]=mylist[j],mylist[i]
j+=1
i+=1
print("the sorted list is",mylist)
|
5217001988eca289299e176c6d314421f45de1d2 | SirBanner/Performance-Task-CSP | /Basic Word Function.py | 629 | 3.9375 | 4 | from words import wordlist
import random
def get_word():
word = random.choice(wordlist)
return word.upper()
def play(word):
word_complettion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print("Start Hangman.")
print(display_hangman(tries))
print(word_complettion)
print("\n")
while not guessed and tries > 0:
guess = input("Guess a letter or word: ").upper()
if len(guess) == 1 and guess.isalpha():
elif len(guess) == len(word) and guess.isalpha():
else:
pring("Not Valid Guess")
print(display_hangman(tries))
print("\n")
|
1aaf41f7af803fd42f3249b8c58e85464aa72924 | aayushi-droid/Python-Thunder | /Solutions/harshadNumber.py | 694 | 3.859375 | 4 | """
Probem Task : "A number is said to be Harshad if it's exactly divisible by the sum of its digits. Create a function that determines whether a number is a Harshad or not."
Problem Link : https://edabit.com/challenge/eADRy5SA5QbasA3Qt
"""
def is_harshad(inp):
sum_of_digits = sum([int(digit) for digit in str(inp)])
if inp % sum_of_digits == 0:
return True
else:
return False
if __name__=='__main__':
if is_harshad(481) == True:
print("Case 1 passed")
if is_harshad(89) == False:
print("Case 2 passed")
if is_harshad(516) == True:
print("Case 3 passed")
if is_harshad(200) == True:
print("Case 4 passed") |
6e9af73893f930bba884c6021aaa7272cd322e59 | al-eax/robotik_ws1718 | /ub4/UB4_2_2_remi.py | 1,583 | 3.78125 | 4 |
# coding: utf-8
# In[74]:
'''
After measuring , we write the function that takes the given streering angle of the car and
return the steering angle in the reality.
The convertion of measurements in angles didn't make so sense much that why we decided to continue with our
an intuitiv apprixomation observed in the labor : (the more car turn the less precise it is! )
'''
import pandas as pd
import numpy as np
def function_approx(angle):
x=[0, 30, 60, 70, 90, 160,180]
# our intuitiv approximation ( assumed from our intuition )
y=[0, 32, 65, 78, 100 , 165,200]
# polynomimal approximation (the set polynome to maximal degree)
z = np.polyfit(x, y,6 )
# evaluation of the
angle_correction = np.polyval( z, angle)
return angle_correction
# make table
'''
here we just make the table.
'''
given_angle= [0, 30,60, 90,120,150, 180]
real_angle= list( map(function_approx, given_angle))
real_angle=list( map(int,real_angle))
real_angle= np.array(real_angle)
real_angle= pd.DataFrame(real_angle).T
xy=[[0, 1.0, 2.0, 3.0, 4.0, 5.0,6.0],[0, 1.0, 2.0, 3.0, 4.0, 5.0,6.0]]
xy= pd.DataFrame(xy ,index=['given angle ','real'])
xy.drop('given angle ', inplace=True)
table =pd.concat([xy, real_angle], axis=0)
table.rename(columns={1: '30', 2: '60',3: '90',4: '120',5: '150',6: '180'},inplace=True)
table.drop('real', inplace=True)
table.rename(index={0:' real values'},inplace=True)
'main'
function_test= function_approx(35)
print('turn in real world: ',function_test )
print (table)
# In[ ]:
|
f41c1fe0a95f1691da9809994b644bd7b9bf549c | tathagatnawadia/Python_Experiments | /archive/newfile/new.py | 391 | 4.03125 | 4 | import sys
def write():
print('Creating new text file')
name = input('Enter name of text file: ')+'.txt'
try:
file = open(name,'w') # Trying to create a new file or open one
file.close()
except:
print('Something went wrong! Can\'t tell what?')
sys.exit(0) # quit Python
def main:
write()
if __name__ == '__main__':
main()
|
f7439d5e86fd647175a025c7310537f7ed9ec06a | jgarcia-r7/scripts-tools | /templates/doc_downloads.py | 812 | 3.65625 | 4 | #!/usr/bin/env python3
# Template: urllib Downloads Template
# Author: Jessi
# Purpose: Download documents from a list of urls, print error if a 404 error comes up and continue.
# Standalone Usage: python3 doc_downloads.py <urlfile> <oudir> (Ex. python3 doc_downloads.py urls.txt outdir/)
import urllib.request
import sys
infile = sys.argv[1]
outdir = sys.argv[2]
print("[!] Downloading Files")
def download_url(url,filename):
try:
r = urllib.request.urlretrieve(url,filename)
print(f"[+] Downloading: {url}")
except urllib.error.HTTPError as exception:
print(f"[X] Download Failed For: {url}")
with open(infile) as f:
for i in f:
url = i.rstrip()
name = url.rsplit('/', 1)[1]
filename = outdir + name
download_url(url,filename)
print("[+] Done")
|
0d86f85482f7a043f274ea9b8bf1412dbd28bdfe | sametcem/Python | /thenewboston_pythonGUI/Tkinter_12.py | 356 | 3.84375 | 4 | from tkinter import *
import tkinter.messagebox
#MESSAGE BOX
root = Tk()
tkinter.messagebox.showinfo('Pencere basligi','Maymunlar 300 yasına kadar yasayabilir' )
answer= tkinter.messagebox.askquestion('Soru1','Adin Cem mi?')
if answer == 'yes':
print('Merhaba Cem')
else:
print('Lutfen adinizi giriniz')
root.mainloop()
|
c4703c397c16efb7b86208e54807fd2e57ce9ff8 | guyna25/WixProductCounter | /csvArranger.py | 3,398 | 3.578125 | 4 | import os
import pandas as pd
ARG_NUM = 1
PAYMENT_METHOD = "אשראי"
MARK_CHAR = "V"
TAX_FACTOR = 1.17
OUTPUT_NAME = "result.csv"
csv_name = ""
DEFAULT_ENCODING = "utf-8"
class csv_arranger():
"""
This object has methods for the specific transformation of the wix site product output
"""
def get_column_items(self, data, name):
"""This function produces the product names from the user csv"""
return data[name].unique()
def extract_info(self, columns, item_dict, temp_df):
"""
Extracts relevent info from a df
:param columns: the column names of the csv
:param item_dict: dicionary that matches between item name in the csv and in the output table
:param temp_df: the diff with current matching rows
:return:
"""
columns = list(columns)
res = [0] * len(columns)
for idx, row in temp_df.iterrows():
res[0] = row["Date"]
res[1] = row["Billing Customer"]
res[2] += row["Qty"] # products purchased
try:
res[columns.index(item_dict[row["Item's Name"]])] += row["Qty"]
except Exception as e:
print(item_dict)
res[-1] = "V" # invoice receipt
res[-2] = "אשראי" # payment method
res[-3] = "סופק" # soopak
res[-4] = row["Total"] / TAX_FACTOR # income with no tax
res[-5] = row["Total"] # income with tax
res[-6] = row["Shipping"] # shipping
return res
def transform_csv(self, csv_filepath, columns, item_dict, used_args='all', output_name="result"):
"""
Transform the csv into a user product purchase count by date form
:param csv_filepath: the path to the csv to transform
:param columns: the column of the csv
:param item_dict: dicionary that matches between item name in the csv and in the output table
:param used_args: the agruments relveant to the csv transform, default is to use all df columns
:param output_name: the name of the result csv
:return: The transformed csv
"""
res = pd.DataFrame(columns=columns)
row_idx = 0
df = pd.read_csv(csv_filepath)
if (not used_args == 'all'):
df = df[used_args]
for idx, date_group in df.groupby("Date"):
for useless_idx, daily_customer_purchase in date_group.groupby("Billing Customer"):
new_row = self.extract_info(columns, item_dict, daily_customer_purchase)
res.loc[row_idx] = new_row
row_idx += 1
res.to_csv(path_or_buf=os.path.dirname(os.path.realpath(__file__)) + "\\" + OUTPUT_NAME, columns=columns[
:-1],
encoding='ISO-8859-8')
def get_column_names(self, csv_path, encoding=DEFAULT_ENCODING):
"""
:param csv_path:The path to the the csv file
:param encoding: the encoding of the csv (mainly relevant for non-english files)
:return: the column names in the file, note that this method assumes the columns are named
"""
return pd.read_csv(csv_path, encoding=encoding).columns
|
38edbdc9ba68f9bc6a914ddc278479f8147f6e64 | caoxiang104/-offer | /4.py | 1,650 | 3.75 | 4 | # -*- coding:utf-8 -*-
"""
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例
如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,
2,1,5,3,8,6},则重建二叉树并返回
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
def recurse(pre, tin, node):
if pre:
temp_node = TreeNode(pre[0])
node = temp_node
index = tin.index(pre[0])
left = tin[:index]
right = tin[index + 1:]
pre.pop(0)
if len(left) > 0:
node.left = recurse(pre, left, node.left)
if len(right) > 0:
node.right = recurse(pre, right, node.right)
return node
node = recurse(pre, tin, None)
# list_ = []
# temp = []
# temp.append(node)
#
# def level(temp, list_):
# if temp:
# node = temp.pop(0)
# list_.append(node.val)
# if node.left:
# temp.append(node.left)
# if node.right:
# temp.append(node.right)
# level(temp, list_)
# level(temp, list_)
return node
s = Solution()
print(s.reConstructBinaryTree([1,2,4,7,3,5,6,8], [4,7,2,1,5,3,8,6]))
|
b7c6ad6371178641a5858acf0cff96ff6b58fb69 | milenacudak96/python_fundamentals | /labs/07_classes_objects_methods/07_00_planets.py | 392 | 4.4375 | 4 | '''
Create a Planet class that models attributes and methods of
a planet object.
Use the appropriate dunder method to get informative output with print()
'''
class Planet:
def __init__(self, name, color):
self.name = name
self.color = color
def __str__(self):
return f' Planet {self.name} is {self.color}'
Mars = Planet('Mars', 'blue')
print(Mars.name)
|
b994a2f10075a358084a825f7090eaf213a3eb38 | Evan8456/Hyper-Sudoku-Solver | /HyperSudoku.py | 4,264 | 4 | 4 |
class HyperSudoku:
@staticmethod
def solve(grid):
"""
Input: An 9x9 hyper-sudoku grid with numbers [0-9].
0 means the spot has no number assigned.
grid is a 2-Dimensional array. Look at
Test.py to see how it's initialized.
Output: A solution to the game (if one exists),
in the same format. None of the initial
numbers in the grid can be changed.
'None' otherwise.
"""
def solve(grid):
if(HyperSudoku.solveSudoku(grid)):
return grid
else:
return None
@staticmethod
def printGrid(grid):
"""
Prints out the grid in a nice format. Feel free
to change this if you need to, it will NOT be
used in marking. It is just to help you debug.
Use as: HyperSudoku.printGrid(grid)
"""
print("-"*25)
for i in range(9):
print("|", end=" ")
for j in range(9):
print(grid[i][j], end=" ")
if (j % 3 == 2):
print("|", end=" ")
print()
if (i % 3 == 2):
print("-"*25)
@staticmethod
def usedInRow(grid, row, num):
for x in range(1,10):
if(grid[row-1][x-1] == num):
return True
return False
@staticmethod
def usedInCol(grid, col , num):
for x in range(1,10):
if(grid[x-1][col-1] == num):
return True
return False
@staticmethod
def usedInHyperBox(grid, r, c, num):
if r == -1:
return False
elif c == -1:
return False
else:
if((2<=r<=4) and (2<=c<=4)):
for x in range(2,5):
for y in range(2,5):
if(grid[x-1][y-1] == num):
return True
elif((2<=r<=4) and (6<=c<=8)):
for x in range(2,5):
for y in range(6,9):
if(grid[x-1][y-1] == num):
return True
elif((6<=r<=8) and (2<=c<=4)):
for x in range(6,9):
for y in range(2,5):
if(grid[x-1][y-1] == num):
return True
elif((6<=r<=8) and (6<=c<=8)):
for x in range(6,9):
for y in range(6,9):
if(grid[x-1][y-1] == num):
return True
return False
@staticmethod
def usedInBox(grid, boxStartRow, boxStartCol, num):
for x in range(0,3):
for y in range(0,3):
if(grid[x + boxStartRow-1][y+boxStartCol-1] == num):
return True
return False
@staticmethod
def noConflicts(grid, row, col, num):
if col == 1 or col == 2 or col == 3:
startcol=1
elif col == 4 or col == 5 or col == 6:
startcol=4
else:
startcol = 7
if row == 1 or row == 2 or row == 3:
startrow=1
elif row == 4 or row == 5 or row == 6:
startrow=4
else:
startrow = 7
return ( not HyperSudoku.usedInRow(grid, row, num) and not HyperSudoku.usedInCol(grid, col, num)
and not HyperSudoku.usedInBox(grid, startrow, startcol, num) and not HyperSudoku.usedInHyperBox(grid, row, col, num))
@staticmethod
def findUnassignedLocation(grid):
for x in range(1,10):
for y in range(1,10):
if(grid[x-1][y-1] == 0):
return (x, y, True)
return(-1, -1, False)
@staticmethod
def solveSudoku(grid):
(row, col, sol) = HyperSudoku.findUnassignedLocation(grid)
if(sol is False):
return(grid)
for i in range(1,10):
if(HyperSudoku.noConflicts(grid, row, col, i)):
grid[row-1][col-1] = i
if(HyperSudoku.solveSudoku(grid)):
return(grid)
else:
grid[row-1][col-1] = 0
return None
|
d59ff742cbafad7f201b09874eadaf32bc37cfaf | mahadevTW/py_uploader | /vowel/test_vowels.py | 1,178 | 3.515625 | 4 | from unittest import TestCase
from vowel.vowels import is_vowel_line, print_file_vowels
class Test(TestCase):
def test_is_vowel_line_false_for_some_char_vowels_and_some_consonants(self):
line = "hi, i am mahadev"
assert is_vowel_line(line) == False
def test_is_vowel_line_false_empty_line(self):
line = ""
assert is_vowel_line(line) == False
def test_is_vowel_line_false_null_line(self):
line = None
assert is_vowel_line(line) == False
def test_is_vowel_line_true_for_all_vowels_present_in_line(self):
line = "brown fix attempt undone"
assert is_vowel_line(line) == True
def test_print_file_vowels_throws_exception_if_file_not_found(self):
self.assertRaises(Exception, print_file_vowels, "blah.txt")
def test_print_file_vowels(self):
from unittest.mock import patch
from io import StringIO
expected_output = "brown fix attempt undone\n"
with patch('sys.stdout', new=StringIO()) as fake_out:
print_file_vowels("test_data/demo.txt")
self.assertEqual(fake_out.getvalue(), expected_output)
|
bc9f54ddfc714283dca4a11291cebda06c070c39 | gourav071295/PythonCodes | /food.py | 395 | 3.75 | 4 | print "\t\t\t\tWelcome user"
Food_1 = raw_input("Please enter your favorite food :")
Food_2 = raw_input("Please enter your another favorite food :")
print "\n\nThanks for the input."
name = raw_input("Please enter your name:")
print "Hi, " +name.title()
print "This is your food List you love " + Food_1.upper() + " and " + Food_2.upper()
raw_input("Press enter to exit")\
|
615f1cdba93be66b89a60ebbc23a352c8dc450a9 | vgrozev/SofUni_Python_hmwrks | /Programming Basics with Python - април 2018/02. Прости пресмятания/12. Currency Converter.py | 857 | 3.578125 | 4 |
bgn_const = 1
usd_const = 1.79549
eur_const = 1.95583
gbp_const = 2.53405
amount = float(input())
from_currency = input()
to_currency = input()
###########################################
# convert everything to BGN as a first step
if from_currency == 'USD':
bgn_step = amount * usd_const
elif from_currency == 'EUR':
bgn_step = amount * eur_const
elif from_currency == 'GBP':
bgn_step = amount * gbp_const
else:
bgn_step = amount
###########################################
# convert from BGN to output currency
if to_currency == 'USD':
converted_amount = bgn_step / usd_const
elif to_currency == 'EUR':
converted_amount = bgn_step / eur_const
elif to_currency == "GBP":
converted_amount = bgn_step / gbp_const
else:
converted_amount = bgn_step / bgn_const
print(round(converted_amount, 2), to_currency)
|
141f5df3aa49ca94999e34f4223339c1ddd46214 | atulgupta9/DigitalAlpha-Training-Programs | /Day2/prog2.py | 430 | 4.125 | 4 | # Generate a dictionary contains radius and area of the circle,
# radius ranging from 1 to n. Print the dictionary. Input is n.
print("Enter value of n")
n = int(input())
areaDictionary = {}
for x in range(1, n + 1):
areaDictionary[x] = (22 / 7) * pow(x, 2)
print(areaDictionary)
print("Pretty Printing the area dictionary")
for num, area in areaDictionary.items():
print("Radius is %d, Area is %f"%(num,area))
|
6e9e557c1c31d6364b47d36a689f8a4de3af7096 | rubenhortas/python_examples | /functions/builtin_functions/frozen_set.py | 535 | 3.875 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# The frozenset() is an inbuilt function in Python which takes an iterable object as input and makes them immutable.
# Simply it freezes the iterable objects and makes them unchangeable.
frozen_numbers = frozenset(numbers)
try:
# If you want to change the frozenset an exception will raise
# noinspection PyUnresolvedReferences
frozen_numbers[1] = 0
except TypeError as ex:
print(ex)
|
d3187079630299dc6067ce5a0acbd8cf76bd4092 | GuoJing/leetcode | /algorithms/median/run.py | 803 | 3.59375 | 4 | # https://leetcode.com/problems/median-of-two-sorted-arrays/
from bisect import bisect_left
class Solution(object):
def isodd(self, n):
return n % 2 == 1
def find_index(self, t):
if self.isodd(t):
return (t/2, t/2)
else:
return (t/2 - 1, t/2)
def findMedianSortedArrays(self, nums1, nums2):
l1= len(nums1)
for i, n in enumerate(nums2):
_i = bisect_left(nums1, n)
nums1.insert(_i, n)
l1 += 1
x, y = self.find_index(l1)
vx = nums1[x]
vy = nums1[y]
if x == y:
return float(vx)
return float((vx + vy)) / 2
if __name__ == '__main__':
n1 = [1, 3]
n2 = [2]
s = Solution()
r = s.findMedianSortedArrays(n1, n2)
print r
|
d3c5f4f17cb7c4c131606879be59b98d6e67ff81 | CS7591/Python-Classes | /5. Python TKINTER/23. Input Validation.py | 2,866 | 4.21875 | 4 | import tkinter as tk
def read_values():
number = entry_1_var.get()
text = entry_2_var.get()
entry_1_var.set('')
entry_2_var.set('')
label.configure(text=f'Number:{number} / Text:{text}')
# Functions that will allow only float input from the user
def float_only(action, value_if_allowed, text):
permitted = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-', '+']
if action == '1':
if text in permitted:
try:
float(value_if_allowed)
return True
except ValueError:
return False
else:
return False
else:
return True
# Functions that will allow only char input from the user
def string_only(action, text):
if action == '1':
if text.isalpha() or text == ' ':
return True
else:
return False
else:
return True
root = tk.Tk()
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
# The callback functions must be registered in tkinter
validate_numbers = root.register(float_only)
validate_strings = root.register(string_only)
'''
Callback substitution codes
'%d' Action code:
0 for an attempted deletion,
1 for an attempted insertion,
-1 if the callback was called for focus in, focus out, or a change to the textvariable.
'%i' When the user attempts to insert or delete text,
this argument will be the index of the beginning of the insertion or deletion.
If the callback was due to focus in, focus out, or a change to the textvariable,
the argument will be -1.
'%P' The value that the text will have if the change is allowed.
'%s' The text in the entry before the change.
'%S' If the call was due to an insertion or deletion, this argument will be the text
being inserted or deleted.
'%v' The current value of the widget's validate option.
'%V' The reason for this callback: one of 'focusin', 'focusout', 'key', or 'forced'
if the textvariable was changed.
'%W' The name of the widget.
'''
entry_1_var = tk.StringVar()
entry_1 = tk.Entry(root, textvariable=entry_1_var, justify='center', width=20,
validate='all', validatecommand=(validate_numbers, '%d', '%P', '%S'))
entry_2_var = tk.StringVar()
entry_2 = tk.Entry(root, textvariable=entry_2_var, justify='center', width=20,
validate='all', validatecommand=(validate_strings, '%d', '%S'))
entry_1.grid(row=0, column=0, sticky='nsew')
entry_2.grid(row=0, column=1, sticky='nsew')
button = tk.Button(root, text='Read Values', command=read_values)
button.grid(row=1, column=0, columnspan=2, sticky='nsew')
label = tk.Label(root, text='Values')
label.grid(row=2, column=0, columnspan=2, sticky='nsew')
if __name__ == '__main__':
root.mainloop()
|
33e31286330ed646456c62a880bcf2a38890cf85 | suyeonkwong/3D_Games | /HELLOPYTHON/day07/mynumpy.py | 151 | 3.828125 | 4 | import numpy as np
arr = [1,2,3]
arr_n = np.array(arr) #원래는 [1,2,3] 인데 np의 array함수를 쓰면 [1 2 3]
arr_n = arr_n % 2
print(arr_n) |
e1590751edf912eba0358fe4114a2ba404ca5e2d | matthewgiem/data_science_from_scratch.py | /Chapter 4/Linear Algebra.py | 4,859 | 4.1875 | 4 | ### VECTORS ###
height_weight_age = [70, # inches,
170, # pounds,
40] # years
grades = [95, # exam 1
80, # exam 2
75, # exam 3
62] # exam 4
# zip is used to create an itirable were a list isn't an itirable
def vector_add(v, w):
'''adds corresponding elements'''
return[v_i + w_i, for v_i, w_i in zip(v, w)]
def vector_subtract(v, w):
'''subtracts corresponding elements'''
return[v_i - w_i, for v_i, w_i in zip(v, w)]
def vector_sum(vectors):
'''take a list of vectors and sum there corresponding parts'''
result = vectors[0] # start with the first vector
for vector in vectors[1:]: # loop over the rest of the vectors
result = vector_add(result, vector) # add vectors to the result and rename result
return result
# the same can be done by using reduce()
def reduce_vector_sum(vectors):
return reduce(vector_add, vectors)
# or using partial()
vector_sum = partial(reduce, vector_add) # look into how partial works
def scalar_multiply(c, v):
'''c is a number, v is a vector'''
return[c * v_i, for v_i in v]
def vector_mean(vectors):
'''compute a vector whos ith element is the mean of the ith elements of the input vectors'''
n = len(vectors)
return scalar_multiply(1/n, vector_sum(vectors))
def dot(v, w):
'''v_1 * w_1 + v_2 + w_2 + ... + v_n + w_n'''
return sum(v_i * w_i, for v_i, w_i in zip(v, w))
def sum_of_squares(v):
'''v_1^2 + v_2^2 + ... + v_n^2'''
return dot(v, v)
import math
def magnitude(v):
'''square root (v_1^2 + v_2^2 + ... + v_n^2)'''
return math.sqrt(sum_of_squares(v))
def sqaured_distance(v, w):
'''(v_1 - w_1)^2 + ... + (v_n - w_n)^2'''
return sum_of_squares(vector_subtract(v, w))
def distance(v, w):
'''distance = square root of ((v_1 - w_1)^2 + ... + (v_n - w_n)^2)'''
return math.sqrt(sqaured_distance(v, w))
def cleaner_distance(v, w):
'''cleaner way find distance using functions already created'''
return magnitude(vector_subtract(v,w))
### MATRICES ###
# typicall use capitol letters to represent matrices
A = [[1,2,3], # A has 2 rows and 3 columns
[4,5,6]]
B = [[1,2], # B has 3 rows and 2 columns
[3,4],
[5,6]]
# the matrix A has len(A) rows, and len(A[0]) columns
def shape(A):
'''returns the number of rows and columns'''
num_rows = len(A)
num_col = len(A[0]) if A else 0 # number of elemens in the first row
return num_rows, num_col
def get_row(A, i):
'''return the ith row of matrix A'''
return A[i] # A[i] is already the ith row
def get_col(A, j):
'''return the ith col of matrix A'''
return [A_i[j] # jth element of row A_i
for A_i in A] # for each row A_i
def make_matrix(num_rows, num_cols, entry_fn):
'''return a num_rows X num_cols matrix
whose (i,j)th entry is entry_fn(i,j)'''
return [[entry_fn(i, j) # given i, create a list
for j in range(num_cols)] # [entry_fn(i,0), ... ]
for i in range(num_rows)] # create one list for each j
def is_diagonal(i, j):
'''1's on the 'diagonal', 0's everywhere else'''
return 1 if i == j else 0
# identity_matrix = make_matrix(5, 5, is_diagonal)
# identity_matrix = [[1, 0, 0, 0, 0],
# [0, 1, 0, 0, 0],
# [0, 0, 1, 0, 0],
# [0, 0, 0, 1, 0],
# [0, 0, 0, 0, 1]]
friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4),
(4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]
# can be represented as a matrix
def always_zero(x,y):
return 0
friendships_matrix = make_matrix(10, 10, always_zero)
for pair in friendships:
friendships_matrix[pair[0]][pair[1]] = 1
friendships_matrix[pair[1]][pair[0]] = 1
friendships_matrix = [[0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 1, 1, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
friends_of_five = [i # only need
for i , is_friend in enumerate(friendships_matrix[5]) # to look at
if is_friend] # one row
|
59b81bbe6ad8d55c144ea08ac5c01b7e8fb0f3fa | fatFish41/CP1404-Practicals | /A1/Assignment 1.py | 5,149 | 4.125 | 4 | import csv
import copy
import operator
# use for organize the data, organize them into different part
def sort_data(data):
data.sort(key=operator.itemgetter(3, 2))
return data
# this is to organize the places into a list
# the things about the row is use for putting the number in order
# and the V shows the place that have not visit yet which will show by *
def show_list():
locationreader = open('places.csv')
location = list(csv.reader(locationreader, delimiter=','))
location_temp = copy.copy(location)
for row in location_temp:
row[2] = int(row[2])
location_temp = sort_data(location_temp)
for i in range(1, len(location_temp)+1, 1):
if location_temp[i-1][3] == 'V':
location_temp[i-1][3] = '*'
else:
location_temp[i-1][3] = ''
print(i, '. {:1} {:10} {:1} {:15} {} {} {}'.format(location_temp[i-1][3], location_temp[i-1][0], 'in',
location_temp[i-1][1], ' Priority(', location_temp[i-1][2], ')'))
# this is the option for menu which is the main function
def main():
print("Travel Tracker 1.0 - by Weilun Tu")
data = list(csv.reader(open("places.csv")))
menu = ">>> "
print("Menu:\nL - List places\nA - Add new place\nM - Mark a place as visited\nQ - Quit")
while menu.upper() != 'Q':
for row in data:
row[2] = int(row[2])
data = sort_data(data)
menu = input()
if menu == "L" or menu == "l":
show_list()
print("{} places. You still want to visit {} places.".format(len(data), get_unvisited_num(data)))
print("Menu:\nL - List places\nA - Add new place\nM - Mark a place as visited\nQ - Quit")
elif menu == "A" or menu == "a":
name = input("Name: ")
newplaces = []
while name == "":
print("Input can not be blank")
name = input("Name: ")
newplaces.append(name)
country=input("Country: ")
while country == "":
print("Input can not be blank")
country = input("Country: ")
newplaces.append(country)
valid_input = False
while not valid_input:
try:
Priority = int(input("Priority:"))
except ValueError:
print("Invaild input; exnter a vaild number.")
else:
if Priority <= 0:
print("cannot be less than 0")
else:
valid_input = True
newplaces.append((Priority))
newplaces.append("V")
with open('places.csv', 'a') as places:
writer = csv.writer(places)
writer.writerow(newplaces)
print("{} in {} (priority {}) added to Travel Tracker".format(name, country, Priority))
print("")
print("Menu:\nL - List places\nA - Add new place\nM - Mark a place as visited\nQ - Quit")
elif menu == "M" or menu == "m":
if get_unvisited_num(data) == 0:
print("No unvisited places")
else:
show_list()
print("Enter the number of a place to mark as visited")
num_mark = input(">>> ")
while mark(num_mark) != 0:
num_mark = input(">>> ")
while int(num_mark) > len(data):
print("Invalid place number")
num_mark = input(">>> ")
if data[int(num_mark)-1][3] == "Y":
print("That place is already visited")
else:
data[int(num_mark)-1][3] = "Y"
with open("places.csv", "w") as csv_places:
writer = csv.writer(csv_places, delimiter=",")
for row in data:
writer.writerow([row[0], row[1], row[2], row[3]])
print(data[int(num_mark)-1][0] + " in " + data[int(num_mark)-1][1] + " visited!")
print("Menu:\nL - List places\nA - Add new place\nM - Mark a place as visited\nQ - Quit")
elif menu == "Q" or menu == "q":
print(str(len(data))+" places saved to places.csv. Have a nice day :)")
else:
print("Invalid menu choice")
print("Menu:\nL - List places\nA - Add new place\nM - Mark a place as visited\nQ - Quit")
# this is a function to get the number of unvisited
def get_unvisited_num(data):
unvisited_num = 0
for i in range(len(data)):
if data[i][3] == "V":
unvisited_num += 1
return unvisited_num
# this ia to make sure that the user does not put in the wrong number
def mark(num):
try:
num = int(str(num))
if isinstance(num, int) == True:
if num <= 0:
print("Number must be > 0")
return 1
return 0
else:
return 2
except:
print("Invalid input; enter a valid number")
return 2
main()
|
5bdc2db07b61727912506e2d6e38283922a26969 | Joss233/Learing-Python | /exercise/练习实例4.py | 677 | 3.578125 | 4 | # -*- coding:utf-8 -*-
# 输入某年某月某日,判断这一天是这一年的第几天?
time = input("请输入年月日(如20150815):")
year = int(time[:4])
month = int(time[4:6])
day = int(time[6:])
days = [0,31,28,31,30,31,30,31,31,30,31,30,31]
sumdays = 0
print("%d年%d月%d日" % (year,month,day))
# 1.先计算普通年份天数
for i in range(0,month):
sumdays = days[i] + sumdays
# 2.判断闰年,若月份大于2则总天数+1
if (year%4==0 and year%100!=0) or (year%100==0 and year%400==0):
if month > 2:
sumdays += 1
sumdays = sumdays + day
print("这是%d年的第%d天" % (year,sumdays))
|
2e26d7fc80d1ac7d5fc5690f17b91868219df079 | mohitsharma14/HackerRank-Python-Solutions | /Easy/sumArrayElements.py | 331 | 4.03125 | 4 | """
Given an array of integers, find the sum of its elements.
For example, if the array is [2,3,4] so return 9.
"""
# Adding numbers of an array
def main():
print(simpleArraySum(ar = [1,2,3,4,5]))
def simpleArraySum(ar):
sum = 0
for i in range(0, len(ar)):
sum = sum + ar[i]
return(sum)
if __name__ == '__main__':
main()
|
22b3cd7285e3e930a0e252bb189740875cf25f64 | pulinghao/LeetCode_Python | /239. 滑动窗口最大值.py | 833 | 3.8125 | 4 | #!/usr/bin/env python
# _*_coding:utf-8 _*_
"""
@Time :2021/1/2 10:17 下午
@Author :pulinghao@baidu.com
@File :239. 滑动窗口最大值.py
@Description :
"""
import heapq
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
n = len(nums)
# 注意 Python 默认的优先队列是小根堆
q = [(-nums[i], i) for i in range(k)]
heapq.heapify(q)
ans = [-q[0][0]]
for i in range(k, n):
heapq.heappush(q, (-nums[i], i))
while q[0][1] <= i - k:
heapq.heappop(q)
ans.append(-q[0][0])
return ans
if __name__ == '__main__':
nums = [1,3,-1,-3,5,3,6,7]
k = 3
print Solution().maxSlidingWindow(nums,k)
|
705157a9c86340c40af079c11544d77cbb43ebdd | SanjaySantokee/Algorithms-Implementation | /LongestCommonSub/LongestCommonSub.py | 2,145 | 3.9375 | 4 | """
/*
Full Name: Sanjay Santokee
Email: sanjay.santokee@my.uwi.edu
*/
Given two sequences, find the length k of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order,
but not necessarily contiguous from both A and B.
For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, and more are subsequences of “abcdefg”
"""
def LCS(A: str, B: str):
m, n = len(A) + 1, len(B) + 1
L = []
# Initialize all values to 0
for i in range(m):
L.append(
[0 for j in range(n)])
for i in range(1, m):
for j in range(1, n):
if A[i - 1] == B[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i][j - 1], L[i - 1][j])
return L
def printLCS(A: str, B: str, L: list):
# Begin at the bottom-right corner of the LCS table and
# work your way up to the top (value by value)
i, j = len(A), len(B)
# Create a list to hold the final LCS string
C = []
while i > 0 and j > 0:
if A[i - 1] == B[j - 1]:
# It is inserted at 0 since it traverses in a reverse way and needs
# to store it in the reversed fashion by pushing everything into
# the list C backwards.
C.insert(0, A[i - 1]) # Put the character in the list
# reduce values of i and j
i -= 1
j -= 1
else:
# If it is not the same, find the number larger in size (of the two)
# And proceed to go in the path of that number which is larger
if L[i - 1][j] > L[i][j - 1]:
i -= 1 # remove last character of A
else:
j -= 1 # remove last character of B
print('The length of LCS is ', len(C))
print('The LCS C is "', ''.join(C), '"')
if __name__ == "__main__":
with open('lcs.txt') as file:
strings = file.readline().strip('\n').split(' ')
table = LCS(strings[0], strings[1])
print('LCS of: ', strings[0], ', ', strings[1])
printLCS(strings[0], strings[1], table)
|
80cd0654162b9d29d3ed43ee3829ff31449b1bb5 | timManas/PythonProgrammingRecipes | /project/src/ObjectOrientedConcepts/ChangingClassMembersExample/ChangingClassMembersExample.py | 1,500 | 3.5625 | 4 | # from project.src.ObjectOrientedConcepts.ChangingClassMembersExample.CSStudent import * # This works
from project.src.ObjectOrientedConcepts.ChangingClassMembersExample import CSStudent # This doesent work ?
def main():
student1 = CSStudent("Tim", 12345)
student2 = CSStudent("John", 346)
student3 = CSStudent("Romero", 233424234234234)
#Print Student Stream
print("Stream of Student1: ", student1.stream)
print("Stream of Student2: ", student2.stream)
print("Stream of Student3: ", student3.stream)
# Changing the member of the Class by referring to the CLASS NAME directly
CSStudent.stream = "Mathematics"
#Print Student Stream
print("\nStream of Student1: ", student1.stream)
print("Stream of Student2: ", student2.stream)
print("Stream of Student3: ", student3.stream)
# Now we only want Student#3 to be back to BIOLOGY
student3.stream = "BIOLOGY"
#Print Student Stream
print("\nStream of Student1: ", student1.stream)
print("Stream of Student2: ", student2.stream)
print("Stream of Student3: ", student3.stream)
pass
if __name__ == '__main__':
main()
'''
Theres going to be instances when we want to change the static members for ALLLLLLL the classes
If we want to change the instance of all the object which REFER to that class
- We must use the CLASS NAME instead of the object name
But if we want to change individual objects
- Then we must use the individual object name member
''' |
695dd66b352ad00531f26c75a331cd578498477c | cecatto/hackerrank | /data_structures/trees/swap_nodes.py | 2,056 | 3.734375 | 4 | import sys
class Node:
def __init__(self, data):
self.data=data
self.left = None
self.right = None
def print_tree(root):
# inorder recursive
# if not root: return
#
# print_tree(root.left)
# sys.stdout.write(str(root.data) + ' ')
# print_tree(root.right)
# inorder iterative
stack = []
node = root
while True:
while node:
stack.append(node)
node = node.left
if not stack:
break
node = stack.pop()
sys.stdout.write(str(node.data) + ' ')
node = node.right
def swap_nodes(root, k, height):
queue = [root]
cur_k = 1
while cur_k < height:
for _ in range(k):
if cur_k % k != 0:
for _ in range(len(queue)):
cur_node = queue.pop(0)
if cur_node.left: queue.append(cur_node.left)
if cur_node.right: queue.append(cur_node.right)
cur_k += 1
for _ in range(len(queue)):
node = queue.pop(0)
node.left, node.right = node.right, node.left
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
def levelOrder(root):
queue = [root]
level = 1
while queue:
cur_node = queue.pop(0)
level += 1
# sys.stdout.write(str(cur_node.data) + ' ')
if cur_node.left: queue.append(cur_node.left)
if cur_node.right: queue.append(cur_node.right)
return level
# main
root = Node(1)
n = int(input().strip())
queue = [root]
for _ in range(n):
a, b = map(int, input().strip().split(' '))
cur_node = queue.pop(0)
if a > -1:
left = Node(a)
cur_node.left = left
queue.append(left)
if b > -1:
right = Node(b)
cur_node.right = right
queue.append(right)
t = int(input().strip())
for _ in range(t):
k = int(input().strip())
swap_nodes(root, k, levelOrder(root))
print_tree(root)
sys.stdout.write('\n')
|
f5b296a4121d7a4e7e90987b6b65a430437a9b09 | wanni0928/-algorithm | /python/recursive_call/recursive_call5.py | 235 | 3.953125 | 4 | #회문
def pailndrome(string):
if len(string) <=1:
return True
if string[0] == string[-1]:
return pailndrome(string[1:-1])
else:
return False
print(pailndrome("level"))
print(pailndrome("avante")) |
b811c3541f9668f23c4e2472282b791af31656bd | Luxasz/wdcw | /zad3.3.py | 140 | 3.640625 | 4 | import sys
import numpy
produkty={"pietruszka":"kg", "wino": "l"}
a=[name for name, value in produkty.items() if value =="l"]
print(a)
|
e1b8dd79f98f4e5a351ad83fbd605f3d5a9b6939 | Ansh-Kumar/Ansh-Fun-and-Learn | /Ansh Learn/SayMyName.py | 92 | 3.859375 | 4 | name = input("What is your name? ")
for x in range(1000):
print(name, end = " ")
|
eb50e031b26bdc41f48777cb6b35eb443e5b4808 | malekmahjoub635/holbertonschool-higher_level_programming-2 | /0x07-python-test_driven_development/5-text_indentation.py | 779 | 4.125 | 4 | #!/usr/bin/python3
"""
Module to print a text with 2 new lines
"""
def text_indentation(text):
"""
a function that prints a text with 2 new lines/
after each of these characters: ., ? and :
Args:
text(str): the given text
Raises:
TypeError: if the text is not str
Returns:
the new text
"""
if not isinstance(text, str):
raise TypeError("text must be a string")
i = 0
while i < len(text):
print(text[i], end='')
if text[i] in ":.,?":
print('\n')
if i == len(text) - 1:
break
if text[i + 1] == ' ':
i += 1
while text[i] == ' ' and text[i + 1] == ' ' and i + 1 < len(text):
i += 1
i += 1
|
a7a5c207f5db15f7fe9d2bcddbfd441e4583343f | schlogl2017/rates_measurement | /src/convert_codon_tree_to_aa_tree.py | 581 | 3.65625 | 4 | import sys
import re
def main():
if len(sys.argv) != 3: # wrong number of arguments
print """Usage:
python convert_codon_tree_to_aa_tree.py <codon_tree_file> <output_dir>
"""
sys.exit()
tree_file = sys.argv[1]
output_dir = sys.argv[2]
f = open(tree_file,'r')
tree=f.readline()
m = re.search('\d+\.\d+', tree)
codon_bl=float(m.group(0))
aa_bl=codon_bl*0.7702233
new_tree='(t1:'+str(aa_bl)+',t2:'+str(aa_bl)+');'
new_tree_file=output_dir+'/'+'n2_codon_bl%.2f.tre' %codon_bl
print new_tree_file
out = open(new_tree_file,'w')
out.write(new_tree)
main()
|
6e8019f4f1f9b90f6ef9e50706a6ae095e90b2a3 | pnnl/apt | /OPTICS-APT/TreeNode.py | 10,053 | 3.578125 | 4 | """
A TreeNode class that supports hierachical clustering.
Each node represents a cluster at current hierachical level.
"""
import numpy as np
import heapdict
__version__ = '0.2'
class TreeNode:
"""
A data class that represents hierarchy in hierachical clustering using a tree representation.
A node can have many children but only one parent.
"""
def __init__(self, start, end, local_maxima):
"""
start:
start index of the current node, note that start is inclusive and end is exclusive, [start, end)
end:
end index of the current node, note that start is inclusive and end is exclusive, [start, end)
LM:
local maximum list, a priority queue (using heapdict)
"""
self.index_range = (start, end)
self.size = end - start
self.local_maxima = local_maxima
self.children = []
self.parent = None
self.split_point = None
def average_RD(self, ordered_RD):
return np.mean(ordered_RD[self.index_range[0]:self.index_range[1]])
def add_child(self, child_node):
child_node.parent = self
self.children.append(child_node)
def remove_child(self, child_node):
"""
Remove child from current node. All the entire subtree started at child node
will be lost after deletion.
It the child node is not a child of current node, do nothing.
"""
try:
child_node.parent = None
self.children.remove(child_node)
except ValueError:
pass
def is_root(self):
return self.parent == None
def is_leaf(self):
return len(self.children) == 0
def next_lm(self):
try:
return self.local_maxima.popitem()
except IndexError: # index error for popitem in heapdict. Not key error.
return None
def is_lm_empty(self):
return len(self.local_maxima) == 0
def merge(node_1, node_2):
"""
Merge two nodes. The merged node will be a child of the common parent, and will \
inherit children from both nodes.
Only children from the same parent can be mergered. And these two nodes has \
to be neighboer in terms of index.
That is e.g. if node_1 index range is (0, 10), and node_2 (20, 30), merge will not proceed.
Note will be proceed if node_2 is (10, 20).
node_1, node_2:
the node to be merged with.
return:
the new node.
"""
#check if has the same parent
if node_1.parent is node_2.parent:
#check neighbor condition
start_1, end_1 = node_1.index_range
start_2, end_2 = node_2.index_range
if end_1 == start_2:
new_start = start_1
new_end = end_2
elif end_2 == start_1:
new_start = start_2
new_end = end_1
else:
print('merge failed, two node are not neighbors')
return
new_lm = heapdict.heapdict()
new_lm.update(node_1.local_maxima)
new_lm.update(node_2.local_maxima)
new_children = node_1.children + node_2.children
new_node = TreeNode(new_start, new_end, new_lm)
node_1.parent.add_child(new_node)
for child in new_children:
new_node.add_child(child)
node_1.parent.remove_child(node_2)
node_1.parent.remove_child(node_1)
return new_node
else:
print('merge failed, two nodes are not from same parent')
return
def divide(node, split_point, is_similar=False):
"""
Divide the current node into two nodes at the split point. \
There are two ways to added these two nodes:
1. If the RD of split point for current node is similar \
to the RD of split point of its parent, the two new nodes \
will be the children of the parent node, current node will be \
deleted.
2. if not similar, then two new nodes will be added as children \
to current node.
The node been divided must not have children.
split_point:
an index at which the current node will be splited.
is_similar:
flag to regulate how to add the two new nodes.
Return:
new_left_node, new_right node,\
or \
None, None
"""
if node.is_leaf(): #check if has children
start, end = node.index_range
local_maxima_left = heapdict.heapdict() # LM for left node
local_maxima_right = heapdict.heapdict() # LM for right node
while not node.is_lm_empty():
key, val = node.next_lm()
if key < split_point:
local_maxima_left[key] = val
elif key > split_point:
local_maxima_right[key] = val
new_node_left = TreeNode(start, split_point, local_maxima_left)
new_node_right = TreeNode(split_point, end, local_maxima_right)
if (not is_similar) or (node.is_root()): # is not similar or is root node.
node.add_child(new_node_left)
node.add_child(new_node_right)
else: # is similar and node is not root.
node.parent.add_child(new_node_left)
node.parent.add_child(new_node_right)
node.parent.remove_child(node)
return new_node_left, new_node_right
else:
print('node is not leaf, can not divide')
return None, None
def retrieve_leaf_nodes(node, leaf_list):
"""
A recursive algorithm to extract leaf nodes.
"""
if node is not None:
if node.is_leaf():
leaf_list.append(node)
for item in node.children:
retrieve_leaf_nodes(item, leaf_list)
return leaf_list
def extract_tree(root, ordered_RD):
"""
Extract all nodes from the tree below root node using deepth-first search.
reture:
a list has the structure [[node_id, start_idx, end_idx, average_RD, level_id, parent_id],\
[...]...]
"""
level = 0
node_id = 0
parent_id = [-1]
to_be_processed = [root]
next_level = []
next_level_parent_id = []
tree = []
while len(to_be_processed) > 0:
current_node = to_be_processed.pop()
next_level.extend(current_node.children)
# keep track of parent for updating parent id
current_parent_id = parent_id.pop()
next_level_parent_id.extend([node_id]*len(current_node.children))
start, end = current_node.index_range
ave_RD = current_node.average_RD(ordered_RD)
tree.append([node_id, start, end, ave_RD, level, current_parent_id])
node_id += 1
if len(to_be_processed) == 0: # unless current_children_list is also empty, current notde is refilled and loop continue
to_be_processed = next_level
parent_id = next_level_parent_id
next_level_parent_id = []
next_level = []
level += 1
return tree
def tree_to_file(tree, fname):
"""
Write the extracted tree to txt file.
"""
header = 'node_id start end ave_RD level parent_id\n'
with open(fname, 'w') as out_f:
out_f.write(header)
for lst in tree:
line = ' '.join(str(el) for el in lst) + '\n'
out_f.write(line)
####################################
# Test
####################################
if __name__ == '__main__':
# Test TreeNode
RD = np.random.random(10)
start_1 = 0
end_1 = 6
LM_1 = heapdict.heapdict(zip(range(start_1, end_1), RD[start_1:end_1]))
start_1_1 = 0
end_1_1 = 3
LM_1_1 = heapdict.heapdict(zip(range(start_1_1, end_1_1), RD[start_1_1:end_1_1]))
start_1_2 = 3
end_1_2 = 6
LM_1_2 = heapdict.heapdict(zip(range(start_1_2, end_1_2), RD[start_1_2:end_1_2]))
hr_node_1 = TreeNode(start_1, end_1, LM_1)
hr_node_1_1 = TreeNode(start_1_1, end_1_1, LM_1_1)
hr_node_1_2 = TreeNode(start_1_2, end_1_2, LM_1_2)
start_2 = 6
end_2 = 10
LM_2 = heapdict.heapdict(zip(range(start_2, end_2), RD[start_2:end_2]))
start_2_1 = 6
end_2_1 = 8
LM_2_1 = heapdict.heapdict(zip(range(start_2_1, end_2_1), RD[start_2_1:end_2_1]))
hr_node_2 = TreeNode(start_2, end_2, LM_2)
hr_node_2_1 = TreeNode(start_2_1, end_2_1, LM_2_1)
hr_node_root = TreeNode(start_1, end_2, heapdict.heapdict(zip(range(start_1, end_2), RD)))
hr_node_root.add_child(hr_node_1)
hr_node_root.add_child(hr_node_2)
hr_node_1.add_child(hr_node_1_1)
hr_node_1.add_child(hr_node_1_2)
hr_node_2.add_child(hr_node_2_1)
# test add child
print('Test add child, children of roots should be (2), actual are ', len(hr_node_root.children))
# test remove child
hr_node_2_1.parent.remove_child(hr_node_2_1)
print('Test remove child, child of hr node 2 should be (0), actual are ', len(hr_node_2.children))
# test merge
new_child = merge(hr_node_1, hr_node_2)
print('test merge, hr node 1 and 2 should be merged (True), is new node a child of root:', new_child == hr_node_root.children[0])
print('test merge, (Two) grand children will be inhereted by new child, number of new children are: ', len(new_child.children))
# test divide
new_left, new_right = divide(hr_node_1_2, 4, False)
print('test divide. assume new nodes are not similar, should be (2) child of new child:', len(hr_node_1_2.children))
print('test divide. assume new nodes are not similar, new child parent is hr_node_1_2 (True):', new_left.parent is hr_node_1_2)
new_left, new_right = divide(hr_node_1_1, 1, True)
print('test divide. assume new nodes are similar, root should has no child hr_node_1_1 (True)', hr_node_1_1 not in new_child.children)
print('test divide. assume new nodes are similar, new left parent is new_child (True):', new_left.parent is new_child)
# test extract_tree
tree = extract_tree(hr_node_root, RD)
print(tree)
# test tree_to_file
fname = 'test_tree_file.txt'
tree_to_file(tree, fname) |
0d06de8531814c361ef436c71b445ebefe1b0d75 | cihan/calc | /calc.py | 553 | 3.890625 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
def topla(a,b):
sonuc= a+b
return sonuc
def cikar(a,b):
sonuc= a-b
return sonuc
def carp(a,b):
sonuc=a*b
return sonuc
def bol(a,b):
sonuc=((a/1.0)/b)
return sonuc
a= input("İlk sayıyı giriniz: ")
b= input("İkinci sayıyı giriniz: ")
islem = raw_input("İşlem: \ntopla-cikar-carp-bol\n")
if islem == "topla":
print topla(a,b)
elif islem == "cikar":
print cikar(a,b)
elif islem == "carp":
print carp(a,b)
elif islem == "bol":
print bol(a,b)
else:
print "İşlemi yanlış girdiniz..."
|
252c0553ef341820ee207a1a75c657023a5d27a3 | namkiseung/python_BasicProject | /python-package/question_python(resolved)/chapter4_conditional_and_loops_풀이/iv_vowel_or_not.py | 345 | 3.9375 | 4 | # -*- coding: utf-8 -*-
def vowel_or_not(char):
""" 문자를 전달받아서 모음(aeiou)중 하나면 True를, 아니면 False를 반환하는 함수를 작성하자
"""
if char in "aeiou":
return True
else:
return False
if __name__ == "__main__":
print vowel_or_not('a')
print vowel_or_not('c')
|
f736d8317ad003cfbb91eb650067798a75e2d2fe | TrevorDewalt/twitoff-DS-27 | /examples/request_examples.py | 649 | 3.84375 | 4 | """An example of getting data through a URL request"""
import requests
# This is a twitter user example pulling info about Elon Musk
r = requests.get("https://lambda-ds-twit-assist.herokuapp.com/user/elonmusk")
print("The request was made with status code: {}".format(r.status_code))
# This turns the json file into a python dict
elonmusk_dict = r.json()
print(elonmusk_dict["tweets"][0]["full_text"])
# This is an example with the poke api
poke_r = requests.get("https://pokeapi.co/api/v2/pokemon/squirtle")
print("The request was made with status code: {}".format(poke_r.status_code))
squirtle_dict = poke_r.json()
print(squirtle_dict["name"])
|
b828529386aaee4749320011bf4d23408a2ef8db | AndrewKalil/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 1,143 | 3.890625 | 4 | #!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class Test_max_integer(unittest.TestCase):
"""Test for max_integer([])
Arguments:
unittest {module} -- module containing test tool for python
"""
def test_empty_list(self):
self.assertEqual(max_integer([]), None)
def test_positive_numbers(self):
self.assertEqual(max_integer([1, 9, 99, 11, 0]), 99)
def test_negative_numbers(self):
self.assertEqual(max_integer([-1, -55, -5, -3, -11]), -1)
def test_what_about_zero(self):
self.assertEqual(max_integer([-23, -25, -9, -1, 0]), 0)
def test_mixed(self):
self.assertEqual(max_integer([-100, -50, 0, 50, 100]), 100)
def test_characters(self):
self.assertEqual(max_integer(["j", "z", "a", "l"]), "z")
def test_string(self):
self.assertEqual(max_integer(["abcd", "bcde"]), "bcde")
def test_bool(self):
self.assertEqual(max_integer([True, False]), True)
def test_types(self):
self.assertRaises(TypeError, max_integer, [3, 5, "string"])
|
bbb0a03e002fae0a8169ce798244d41dc4bb7ef9 | jorgevasquez397/MyCSSI2019Lab | /WeLearn/M3-Python/Labs/Lab1-PluralizeIt/pluralize.py | 975 | 4 | 4 | num = str(raw_input("Number:"))
word = str(raw_input("Object:"))
print(num)
print(word)
if num == 0 or int > 1 and word[-3:] == "ife":
print(num + " " + word[:-3] + "ves")
elif num == 0 or int > 1 and word[-2:] == "sh":
print(num + " " + word[:-2] + "shes")
elif num == 0 or int > 1 and word[-2:] == "ch":
print(num + " " + word[:-2] + "ches")
elif num == 0 or int > 1 and word[-2:] == "us":
print(num + " " + word[:-2] + "i")
elif num == 0 or int > 1 and word[-2:] == "ay":
print(num + " " + word[:-2] + "ays")
elif num == 0 or int > 1 and word[-2:] == "oy":
print(num + " " + word[:-2] + "oys")
elif num == 0 or int > 1 and word[-2:] == "ey":
print(num + " " + word[:-2] + "eys")
elif num == 0 or int > 1 and word[-2:] == "uy":
print(num + " " + word[:-2] + "uys")
elif num == 0 or int > 1 and word[-1:] == "y":
print(num + " " + word[:-1] + "ies")
elif num == 0 or int > 1:
print(num + " " + word + 's')
else:
print(num + word)
|
410a6fc2e48936df0a5755dab7ef8853cdfa0982 | CodyBuilder-dev/Algorithm-Coding-Test | /problems/programmers/lv2/pgs-67257-evaljoin.py | 717 | 3.65625 | 4 | def solution(expression):
operations = [('+', '-', '*'),('+', '*', '-'),('-', '+', '*'),('-', '*', '+'),('*', '+', '-'),('*', '-', '+')]
answer = []
for op in operations:
a = op[0]
b = op[1]
temp_list = []
for e in expression.split(a):
temp = [f"({i})" for i in e.split(b)]
temp_list.append(f'({b.join(temp)})')
answer.append(abs(eval(a.join(temp_list))))
return max(answer)
# 테스트 케이스
print(solution("100-200*300-500+20"),60420)
print(solution("177-661*999*99-133+221+334+555-166-144-551-166*166-166*166-133*88*55-11*4+55*888*454*12+11-66+444*99"),6083974714)
print(solution("2-990-5+2"),995)
print(solution("50*6-3*2"),300) |
c0f238a6398eceed6f853550ed659e1cf013de8c | Seisembayev/Case_tickets | /validator.py | 499 | 3.5625 | 4 | # class fov validating numbers, percent signs and currencies
class Validator:
def __init__(self):
self.currencies = ['USD', 'EUR', 'KZT', 'RUB']
self.percents = ['PERCENT', 'PCT', '%', 'PERCENTS']
def is_percent(self, text):
if text in self.percents:
return True
return False
def is_number(self, text):
try:
a = float(text)
# print(a)
return True
except:
return False
def is_currency(self, text):
if text in self.currencies:
return True
return False |
7054fe8c1baa7867f531183dbde283b598f135a3 | zhangzongyan/python0702 | /day04/strfun.py | 1,145 | 3.96875 | 4 |
'''字符串常用函数 unicode编码'''
s = "python程序设计"
print(len(s))
print(ord('a'))
print(ord('b'))
print(ord('A'))
print(ord('0'))
print(ord('张'))
print(chr(65))
# 读入用户输入的字符串,大写转小写,小写转大写
#s = input("请输入一个字符串:")
s = 'test'
i = 0
while i < len(s):
if ord('a') <= ord(s[i]) <= ord('z'):
# 转大写
print(chr(ord(s[i]) - (ord('a') - ord('A'))))
else:
print(chr(ord(s[i]) + (ord('a') - ord('A'))))
i += 1
s1 = s.swapcase() # 大写转小写, 小写转大写
print(s1)
if s.islower():
print('小写')
elif s.isdigit():
print('数字')
elif s.isupper():
print('大写')
else:
print('不认识')
s = str(234)
print(type(s))
# s.index(sub)
s = "hello py1thonpy1hello"
t = "py"
print(s.index(t))
t = "py1"
print(s.find(t))
print(s.count(t))
# s.split()
s = " hello, boys,girls "
print(s.split(","))
'''
# s.format()
num1, num2 = eval(input("输入两个整型数:"))
s = "{1:.2f}+{0:.2f} = {2:.2f}".format(num1, num2, num1+num2)
print(s)
'''
s = "python"
print("{:*>30}".format(s))
print("{:-^30}".format(s))
print("{:#<30}".format(s))
|
836c5ff0fa81bae42c8cf63b6ee461d52bc323bf | SaketJNU/software_engineering | /rcdu_2750_practicals/rcdu_2750_dataType.py | 1,457 | 4.34375 | 4 | """
# dataTypes :
List[] , Tuple() perentheses are optional, Dictionary{} ,Set , Sequence ,String(immutable)
# sequence :
[List ,Tuple ,String] (It follows indexing)
# indexing :
starts from 0
its supports (in , not in ) during flow control
"""
newSting = "shubham"
for char in newSting:
print(char)
list = ["s","h","u","b","h","a","m"] # this is list
print(" printing list : ",list)
for char in list:
print(char)
tuple=("s","h","u","b","h","a","m") # this is tuple
print("printing tuple : ",tuple)
for char in tuple:
print(char)
print("Lenght of shubham : ",len(newSting))
print(newSting[0:2]) # it strat from 0 index and ends to index 2(-1)
zoo = ["elephant","tiger","rabbit"]
print("before appending : ",zoo)
zoo.append("Lion") # .append use for appending data into list
print("After appending data : ",zoo)
newzoo=[zoo,"camel"]
print(newzoo)
newzoo.append(zoo)
newzoo.append("camel")
print(newzoo)
newzoo1 = ["elephant", "tiger", "mohit","karala"]
zooset= set(zoo)
newzooset= set(newzoo1)
print (zooset & newzooset)
print(zooset.intersection(newzooset))
# Dictionary : {"key":"value"} pair
dict1 = {"name":"shubham", "course":"b.voc", "students":5 , "studentName":["a","b","c"]}
print(dict1.keys())
print(dict1.values())
for key , value in dict1.items():
print(key, "and it's values =", value)
del dict1["students"]
print(dict1)
print(dict1.get("name")) |
74d63ff5d3054f177e5c88b4ee54af3f196b9456 | toanhtran/gocode_tt | /waitress_tt.py | 3,841 | 4.75 | 5 | '''You will create a Menu/Bill App for a waitress to keep track of her bills
- you will display a built in set menu (it does not change)
Appetizers:
Mozarella Sticks: $2.50
Garden Salad: $3.25
French Fries: $3.75
Main:
Burger: $5.50
BLT: $4.75
Steak and Cheese: $5.25
Chiken Parm sandwich: $6.25
Italian Sandwich: $6.00
Drinks:
soda: $2.00
juices: $2.50
iced tea: $1.75
water(Bottled): $1.25
- When the waitress starts a bill, she can give it a name
- The waitress will enter the item name and it will be added to a bill
- Every time the bill displays, it will show the item, cost, and total for the bill
- The waitress can remove an item from the bill
Commands:
n - creates a new bill, asks user for the name of the bill
l - lists ALL the bills
d - deletes a bill
a - User enters "Garden Salad" - this gets added to the bill:
Two ways to do this:
* when the total is populated, it goes back to look up all the prices and adds them together
* when the item is stored, the price is stored as well and you keep a running total
r- removes item from bill
s- shows items in bill
tips:
- Write this down and plan it out on paper and in english
- Use functions
- Think about what data structures you want to use to store the menu and bills
'''
def create_bill(new_dict):#creates a bill
ask_user = raw_input("Enter new bill name: ")
array_item = []
new_dict[ask_user] = array_item
return new_dict
def list_bills(listOfBill):
for name in listOfBill:
print name
def add_item(array_item):
new_item = raw_input("What food item do you want to add? ")
array_item.append(new_item)
return array_item
print array_item
def remove_item(array_item):
delete_item = raw_input("What item do you want to remove? ")
array_item.remove(delete_item)
return array_item
print array_item
def total_bill(array_item,menu):
Menu = {"Mozarella sticks": 2.50, "Garden salad": 3.25, "French Fries": 3.75, "Burger": 5.50, "BLT": 4.75, "Steak&Cheese": 5.25, "ChickenParm": 6.25, "ItalianSand": 6.00, "Soda": 2.00, "Juice": 2.50, "IceTea": 1.75, "Water": 1.25}
total = 0
for item in all_bills[bill_total]:
total +=1float(menu[add_item])
print "Your total is " + str(total)
print item
def display_menu():
Menu = {"Mozarella sticks": 2.50, "Garden salad": 3.25, "French Fries": 3.75, "Burger": 5.50, "BLT": 4.75, "Steak&Cheese": 5.25, "ChickenParm": 6.25, "ItalianSand": 6.00, "Soda": 2.00, "Juice": 2.50, "IceTea": 1.75, "Water": 1.25}
total = 0
for i in Menu:
print i, ":", Menu[i]
def ui_loop():
all_bills = {}
cost = []
while True:
name = raw_input("Enter \n'm' to see menu items\n'n' to create and name new bill \n'l' list all bills \n'd' deletes a bill \n'a' add items in bill \n'r' remove item from bill\n't' to total and finalize\n'q' to quit: ")
if name == 'm':
display_menu()
elif name == 'n':
all_bills = create_bill(all_bills)
elif name == 'l':
list_bills(all_bills)
print all_bills
elif name == 'a':
display_menu()
bill_search = raw_input("What bill do you want to add items? ")
if all_bills.has_key(bill_search):
all_bills[bill_search] = add_item(all_bills[bill_search])
print all_bills
else:
print"No bill exist with that name."
elif name == 'r':
bill_remove = raw_input("What bill do you want to remove items? ")
if all_bills.has_key(bill_remove):
all_bills[bill_remove] = remove_item(all_bills[bill_remove])
print all_bills
elif name == 'd':
bill_cancel = raw_input("What bill do you want to cancel? ")
all_bills.pop(bill_cancel)
print all_bills
print "You have deleted a bill."
elif name == 't':
bill_total = raw_input("What bill do you want to total and finalize? ")
total_bill(all_bills,menu)
else:
name == 'q'# user will quit program
break
#print list_bills(all_bills)
ui_loop()
|
78a0576932f77c78a9d1aaf07d20314180b5022b | Drunk-Mozart/card | /DL_05_if compare.py | 266 | 4.03125 | 4 | Holiday = input("Please input holiday name: ")
if Holiday == "qingren jie":
print("maihua")
print("kandianying")
elif Holiday == "chrismas eve":
print("buy apple")
elif Holiday == "birthday":
print("buy cake")
else:
print("every day is holiday")
|
bafd2d1f56e1224fb64a3f94a654cee155b6da2b | JariMutikainen/pyExercise | /pythonMorsels/earliest.py | 882 | 4.375 | 4 | # This program takes in a list of dates in the format 'MM/DD/YYYY' and returns
# the earliest one of them. The range of MM is 01 - 99 and the range of
# DD is 01 - 99. This piece of unrealism was added to the task to prevent
# people from using the datetime module of python for solving the problem.
# At first the program takes in only two dates, but the final version sould be
# able to process any number of dates.
def get_earliest(*args):
def date2days(date):
"""
Converts a date into a number of days since the birth of Jesus.
"""
month, day, year = date.split('/')
return int(int(year) * 356 + int(month) * 30.5 + int(day))
return sorted(args, key= lambda date: date2days(date))[0]
# Testing
#date = "01/27/1756"
#print(get_earliest("01/27/1756", "01/27/1802"))
#print(get_earliest("01/27/1802", "01/27/1756", "06/17/1964"))
|
ecedebaef93833c1e8ea1553bd38aff9eb4844e7 | kumarsaurav20/pythonchapters | /07_property_decorater.py | 514 | 3.578125 | 4 | class Employee:
company = "Google"
salary = 4500
salarybonus= 500
@property
def totalsalary(self):
s = (self.salary + self.salarybonus)
return s
#or we can use
# return self.salarybonus+self.salary
@totalsalary.setter
def totalsalary(self,val):
self.salarybonus= val-self.salary
e = Employee()
print(e.totalsalary)
e.totalsalary = 5000 #if we want to change the value of totalsalary
print(e.salary)
print(e.salarybonus)
|
c3f3e66dfd7448c16b9d03977853b3b3305fa4c6 | animesh920/backup | /Deep Learning/assignment2 Regularization and Convolution Nets/cs231n/layers.py | 28,767 | 3.890625 | 4 | import numpy as np
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N
examples, where each example x[i] has shape (d_1, ..., d_k). We will
reshape each input into a vector of dimension D = d_1 * ... * d_k, and
then transform it to an output vector of dimension M.
Inputs:
- x: A numpy array containing input data, of shape (N, d_1, ..., d_k)
- w: A numpy array of weights, of shape (D, M)
- b: A numpy array of biases, of shape (M,)
Returns a tuple of:
- out: output, of shape (N, M)
- cache: (x, w, b)
"""
out = None
#############################################################################
# TODO: Implement the affine forward pass. Store the result in out. You #
# will need to reshape the input into rows. #
#############################################################################
params=x.shape
N=x.shape[0]
x_dash=x.reshape(N,-1)
#############################################################################
# END OF YOUR CODE #
#############################################################################
out=np.dot(x_dash,w)+b
cache = (x, w, b)
return out, cache
def affine_backward(dout, cache):
"""
Computes the backward pass for an affine layer.
Inputs:
- dout: Upstream derivative, of shape (N, M)
- cache: Tuple of:
- x: Input data, of shape (N, d_1, ... d_k)
- w: Weights, of shape (D, M)
Returns a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Gradient with respect to w, of shape (D, M)
- db: Gradient with respect to b, of shape (M,)
"""
x, w,b= cache
dx, dw, db = None, None, None
params=x.shape
N=x.shape[0]
x_dash=x.reshape(N,-1)
#############################################################################
# TODO: Implement the affine backward pass. #
#############################################################################
db=np.sum(dout,axis=0)
#x has a shape of N x M
dw=np.dot(x_dash.T,dout)
dx=np.dot(dout,w.T)
dx=dx.reshape(x.shape)
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx, dw, db
def relu_forward(x):
"""
Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: x
"""
out = None
#############################################################################
# TODO: Implement the ReLU forward pass. #
#############################################################################
x_dash=x
x_dash=x_dash.reshape(1,-1)
x_dash[x_dash<=0]=0
x_dash=x_dash.reshape(x.shape)
out=x_dash
#############################################################################
# END OF YOUR CODE #
#############################################################################
cache = x
return out, cache
def relu_backward(dout, cache):
"""
Computes the backward pass for a layer of rectified linear units (ReLUs).
Input:
- dout: Upstream derivatives, of any shape
- cache: Input x, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
dx, x= None, cache
x_dash=x
mask=np.zeros_like(x)
mask[x>0]=1
# mask=x_dash>0
# x_dash=x_dash.reshape(1,-1)
#############################################################################
# TODO: Implement the ReLU backward pass. #
#############################################################################
# dout=dout.reshape(1,-1)
# print 'x_dash',x_dash
# print dout
dx=dout*mask
# print dout
return dx
#############################################################################
# ReLU backward pass. #
#############################################################################
#############################################################################
# END OF YOUR CODE #
#############################################################################
def batchnorm_forward(x, gamma, beta, bn_param):
"""
Forward pass for batch normalization.
During training the sample mean and (uncorrected) sample variance are
computed from minibatch statistics and used to normalize the incoming data.
During training we also keep an exponentially decaying running mean of the mean
and variance of each feature, and these averages are used to normalize data
at test-time.
At each timestep we update the running averages for mean and variance using
an exponential decay based on the momentum parameter:
running_mean = momentum * running_mean + (1 - momentum) * sample_mean
running_var = momentum * running_var + (1 - momentum) * sample_var
Note that the batch normalization paper suggests a different test-time
behavior: they compute sample mean and variance for each feature using a
large number of training images rather than using a running average. For
this implementation we have chosen to use running averages instead since
they do not require an additional estimation step; the torch7 implementation
of batch normalization also uses running averages.
Input:
- x: Data of shape (N, D)
- gamma: Scale parameter of shape (D,)
- beta: Shift paremeter of shape (D,)
- bn_param: Dictionary with the following keys:
- mode: 'train' or 'test'; required
- eps: Constant for numeric stability
- momentum: Constant for running mean / variance.
- running_mean: Array of shape (D,) giving running mean of features
- running_var Array of shape (D,) giving running variance of features
Returns a tuple of:
- out: of shape (N, D)
- cache: A tuple of values needed in the backward pass
"""
mode = bn_param['mode']
eps = bn_param.get('eps', 1e-5)
momentum = bn_param.get('momentum', 0.9)
N, D = x.shape
running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype))
running_var = bn_param.get('running_var', np.zeros(D, dtype=x.dtype))
out, cache = None, None
if mode == 'train':
#############################################################################
# TODO: Implement the training-time forward pass for batch normalization. #
# Use minibatch statistics to compute the mean and variance, use these #
# statistics to normalize the incoming data, and scale and shift the #
# normalized data using gamma and beta. #
# #
# You should store the output in the variable out. Any intermediates that #
# you need for the backward pass should be stored in the cache variable. #
# #
# You should also use your computed sample mean and variance together with #
# the momentum variable to update the running mean and running variance, #
# storing your result in the running_mean and running_var variables. #
#############################################################################
N=x.shape[0]
#step 1
mu=(1.0/N)*np.sum(x,axis=0)
#step 2
xmu=x-mu
#step 3
xmu_sq=xmu**2
#step 4
var=(1.0/N)*np.sum(xmu_sq,axis=0)
#step 5
std=np.sqrt(var)
#step 6
inv_std=(1.0/std)
#step 7
x_norm=xmu*inv_std
#step 8
out=gamma*x_norm+beta
#updating the running mean and the running variance.
#ie adding the previous running mean and currently calculated new mean to running average,
#this running mean and running variance is used to normalize the data during the test time.
running_mean = momentum * running_mean + (1 - momentum) * mu
running_var = momentum * running_var + (1 - momentum) * var
cache=(x, gamma, beta, bn_param,out,x_norm,inv_std,std,var,xmu_sq,xmu,mu)
#############################################################################
# END OF YOUR CODE #
#############################################################################
elif mode == 'test':
#############################################################################
# TODO: Implement the test-time forward pass for batch normalization. Use #
# the running mean and variance to normalize the incoming data, then scale #
# and shift the normalized data using gamma and beta. Store the result in #
# the out variable. #
#############################################################################
x_dash=(x-running_mean)/np.sqrt((running_var))
x_dash=x_dash*gamma+beta
out=x_dash
cache=(x_dash)
#############################################################################
# END OF YOUR CODE #
#############################################################################
else:
raise ValueError('Invalid forward batchnorm mode "%s"' % mode)
# Store the updated running means back into bn_param
bn_param['running_mean'] = running_mean
bn_param['running_var'] = running_var
return out, cache
def batchnorm_backward(dout, cache):
"""
Backward pass for batch normalization.
For this implementation, you should write out a computation graph for
batch normalization on paper and propagate gradients backward through
intermediate nodes.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from batchnorm_forward.
Returns a tuple of:
- dx: Gradient with respect to inputs x, of shape (N, D)
- dgamma: Gradient with respect to scale parameter gamma, of shape (D,)
- dbeta: Gradient with respect to shift parameter beta, of shape (D,)
"""
dx, dgamma, dbeta = None, None, None
#############################################################################
# TODO: Implement the backward pass for batch normalization. Store the #
# results in the dx, dgamma, and dbeta variables. #
#############################################################################
(x, gamma, beta, bn_param,out,x_norm,inv_std,std,var,xmu_sq,xmu,mu)=cache
N,D=x.shape
dgamma=np.sum(dout*x_norm,axis=0)
dbeta=np.sum(dout,axis=0)
#backprop in step 8
dx_norm=gamma*dout
#backprop in step 7
dxmu=dx_norm*inv_std
dinv_std=np.sum(dx_norm*xmu,axis=0)
#backprop in step 6
dstd=(dinv_std)*(-1./(std**(2)))
#backprop in step 5
dvar=dstd*0.5*((var)**(-0.5))
#backprop in step 4
dxmu_sq=1 / float(N) * np.ones((xmu_sq.shape)) * dvar
#backprop in step 3
dxmu+=(2*xmu*dxmu_sq)
#back prop in step 2
dx=dxmu*1
dmu = - np.sum(dxmu, axis=0)
#back prop in step 1
dx+=(1.0/float(N))*np.ones((dxmu.shape))*dmu
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx, dgamma, dbeta
def batchnorm_backward_alt(dout, cache):
"""
Alternative backward pass for batch normalization.
For this implementation you should work out the derivatives for the batch
normalizaton backward pass on paper and simplify as much as possible. You
should be able to derive a simple expression for the backward pass.
Note: This implementation should expect to receive the same cache variable
as batchnorm_backward, but might not use all of the values in the cache.
Inputs / outputs: Same as batchnorm_backward
"""
dx, dgamma, dbeta = None, None, None
#############################################################################
# TODO: Implement the backward pass for batch normalization. Store the #
# results in the dx, dgamma, and dbeta variables. #
# #
# After computing the gradient with respect to the centered inputs, you #
# should be able to compute gradients with respect to the inputs in a #
# single statement; our implementation fits on a single 80-character line. #
#############################################################################
pass
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx, dgamma, dbeta
def dropout_forward(x, dropout_param):
"""
Performs the forward pass for (inverted) dropout.
Inputs:
- x: Input data, of any shape
- dropout_param: A dictionary with the following keys:
- p: Dropout parameter. We drop each neuron output with probability p.
- mode: 'test' or 'train'. If the mode is train, then perform dropout;
if the mode is test, then just return the input.
- seed: Seed for the random number generator. Passing seed makes this
function deterministic, which is needed for gradient checking but not in
real networks.
Outputs:
- out: Array of the same shape as x.
- cache: A tuple (dropout_param, mask). In training mode, mask is the dropout
mask that was used to multiply the input; in test mode, mask is None.
"""
p, mode = dropout_param['p'], dropout_param['mode']
if 'seed' in dropout_param:
np.random.seed(dropout_param['seed'])
mask = None
out = None
if mode == 'train':
###########################################################################
# TODO: Implement the training phase forward pass for inverted dropout. #
# Store the dropout mask in the mask variable. #
###########################################################################
mask=np.random.rand(*x.shape)<p
out=x
out=out*mask
###########################################################################
# END OF YOUR CODE #
###########################################################################
elif mode == 'test':
###########################################################################
# TODO: Implement the test phase forward pass for inverted dropout. #
###########################################################################
# print 'x',x
out=x
# mask=np.random.uniform(size=x.shape)
# mask=mask>0
# print 'mask',mask
# out=out*(1/(1-p))
# print 'test'
# print out
###########################################################################
# END OF YOUR CODE #
###########################################################################
cache = (dropout_param, mask)
out = out.astype(x.dtype, copy=False)
return out, cache
def dropout_backward(dout, cache):
"""
Perform the backward pass for (inverted) dropout.
Inputs:
- dout: Upstream derivatives, of any shape
- cache: (dropout_param, mask) from dropout_forward.
"""
dropout_param, mask = cache
mode = dropout_param['mode']
dx = None
if mode == 'train':
###########################################################################
# TODO: Implement the training phase backward pass for inverted dropout. #
###########################################################################
dx=dout*mask
###########################################################################
# END OF YOUR CODE #
###########################################################################
elif mode == 'test':
dx = dout
return dx
def conv_forward_naive(x, w, b, conv_param):
"""
A naive implementation of the forward pass for a convolutional layer.
The input consists of N data points, each with C channels, height H and width
W. We convolve each input with F different filters, where each filter spans
all C channels and has height HH and width HH.
Input:
- x: Input data of shape (N, C, H, W)
- w: Filter weights of shape (F, C, HH, WW)
- b: Biases, of shape (F,)
- conv_param: A dictionary with the following keys:
- 'stride': The number of pixels between adjacent receptive fields in the
horizontal and vertical directions.
- 'pad': The number of pixels that will be used to zero-pad the input.
Returns a tuple of:
- out: Output data, of shape (N, F, H', W') where H' and W' are given by
H' = 1 + (H + 2 * pad - HH) / stride
W' = 1 + (W + 2 * pad - WW) / stride
- cache: (x, w, b, conv_param)
"""
# out = None
# #############################################################################
# # TODO: Implement the convolutional forward pass. #
# # Hint: you can use the function np.pad for padding. #
# #############################################################################
stride=conv_param["stride"]
pad=conv_param["pad"]
x_dash= np.pad(x, [(0,0), (0,0), (pad,pad), (pad,pad)], 'constant')
(N, C, H, W)=x.shape
(F, C, HH, WW)=w.shape
H_dash=1 + (H + 2 * pad - HH) / stride
W_dash= 1 + (W + 2 * pad - WW) / stride
out=np.zeros((N,F,H_dash,W_dash))
for i in range(N):
#this for loop is for each data point
for j in range(F):
#this for loop is for each filter. So for example i have 20 filter then this for loop
#runs through all 20 filters.
for k in range(H_dash):
#this loop is for image region selection along the height
start_height=k*stride
for l in range(W_dash):
#this loop is for image region selection along the width
start_width=l*stride
#selecting the data
selected_data=x_dash[i,:,start_height:start_height+HH,start_width:start_width+WW]
out[i,j,k,l]=np.sum(np.multiply(selected_data,w[j,:,:,:]))+b[j]
#############################################################################
# # END OF YOUR CODE #
# #############################################################################
cache = (x, w, b, conv_param)
return out, cache
def conv_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b
"""
dx, dw, db = None, None, None
#############################################################################
# TODO: Implement the convolutional backward pass. #
#############################################################################
x,w,b,conv_param=cache
print 'dout shape',dout.shape
print 'x',x.shape
(N, C, H, W)=x.shape
(F, C, HH, WW)=w.shape
stride=conv_param["stride"]
pad=conv_param["pad"]
x_dash=np.pad(x,[(0,0), (0,0), (pad,pad), (pad,pad)], 'constant')
dW=np.zeros(w.shape)
db=np.zeros(b.shape)
dX=np.zeros(x_dash.shape)
#calculating the dW
H_dash=1 + (H + 2 * pad - HH) / stride
W_dash= 1 + (W + 2 * pad - WW) / stride
print w.shape
for i in range(N):
for j in range(F):
for k in range(H_dash):
start_height=k*stride
for l in range(W_dash):
start_width=l*stride
selected_data=x_dash[i,:,start_height:start_height+HH,start_width:start_width+WW]
dW[j]+=selected_data*dout[i,j,k,l]
db[j]+=dout[i,j,k,l]
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx, dW, db
def max_pool_forward_naive(x, pool_param):
"""
A naive implementation of the forward pass for a max pooling layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The width of each pooling region
- 'stride': The distance between adjacent pooling regions
Returns a tuple of:
- out: Output data
- cache: (x, pool_param)
"""
out = None
#############################################################################
# TODO: Implement the max pooling forward pass #
#############################################################################
pool_height=pool_param["pool_height"]
pool_width=pool_param["pool_width"]
stride=pool_param["stride"]
(N, C, H, W)=x.shape
H_dash=1 + (H - pool_height) / stride
W_dash= 1 + (W -pool_width) / stride
out=np.zeros((N,C,H_dash,W_dash))
for i in range(N):
for j in range(C):
for k in range(H_dash):
start_height=k*stride
for l in range(W_dash):
start_width=l*stride
# print 'start',start_width
selected_data=x[i,j,start_height:start_height+pool_height,start_width:start_width+pool_width]
# print selected_data
out[i,j,k,l]=np.max(selected_data)
#############################################################################
# END OF YOUR CODE #
#############################################################################
cache = (x, pool_param)
return out, cache
def max_pool_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a max pooling layer.
Inputs:
- dout: Upstream derivatives
- cache: A tuple of (x, pool_param) as in the forward pass.
Returns:
- dx: Gradient with respect to x
"""
dx = None
x,pool_param=cache
pool_height=pool_param["pool_height"]
pool_width=pool_param["pool_width"]
stride=pool_param["stride"]
(N,C,H,W)=x.shape
dx=np.zeros(x.shape)
#dout always has the same shape as the out of the layer. so for the layer based architecture
#to work the shape of upstream dout has to have the same shape as the output of the layer
H_dash=1 + (H - pool_height) / stride
W_dash= 1 + (W -pool_width) / stride
#############################################################################
# TODO: Implement the max pooling backward pass #
#############################################################################
for i in range(N):
for j in range(C):
for k in range(H_dash):
start_height=k*stride
for l in range(W_dash):
start_width=l*stride
selected_data=x[i,j,start_height:start_height+pool_height,start_width:start_width+pool_width]
max_val=np.max(selected_data)
mask=(selected_data==max_val)
# m,n = np.unravel_index(np.argmax(selected_data), np.shape(selected_data))
dx[i,j,start_height:start_height+pool_height,start_width:start_width+pool_width]+=(mask*dout[i,j,k,l])
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx
def spatial_batchnorm_forward(x, gamma, beta, bn_param):
"""
Computes the forward pass for spatial batch normalization.
Inputs:
- x: Input data of shape (N, C, H, W)
- gamma: Scale parameter, of shape (C,)
- beta: Shift parameter, of shape (C,)
- bn_param: Dictionary with the following keys:
- mode: 'train' or 'test'; required
- eps: Constant for numeric stability
- momentum: Constant for running mean / variance. momentum=0 means that
old information is discarded completely at every time step, while
momentum=1 means that new information is never incorporated. The
default of momentum=0.9 should work well in most situations.
- running_mean: Array of shape (D,) giving running mean of features
- running_var Array of shape (D,) giving running variance of features
Returns a tuple of:
- out: Output data, of shape (N, C, H, W)
- cache: Values needed for the backward pass
"""
out, cache = None, None
#############################################################################
# TODO: Implement the forward pass for spatial batch normalization. #
# #
# HINT: You can implement spatial batch normalization using the vanilla #
# version of batch normalization defined above. Your implementation should #
# be very short; ours is less than five lines. #
#############################################################################
pass
#############################################################################
# END OF YOUR CODE #
#############################################################################
return out, cache
def spatial_batchnorm_backward(dout, cache):
"""
Computes the backward pass for spatial batch normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, C, H, W)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient with respect to inputs, of shape (N, C, H, W)
- dgamma: Gradient with respect to scale parameter, of shape (C,)
- dbeta: Gradient with respect to shift parameter, of shape (C,)
"""
dx, dgamma, dbeta = None, None, None
#############################################################################
# TODO: Implement the backward pass for spatial batch normalization. #
# #
# HINT: You can implement spatial batch normalization using the vanilla #
# version of batch normalization defined above. Your implementation should #
# be very short; ours is less than five lines. #
#############################################################################
pass
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx, dgamma, dbeta
def svm_loss(x, y):
"""
Computes the loss and gradient using for multiclass SVM classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
N = x.shape[0]
correct_class_scores = x[np.arange(N), y]
margins = np.maximum(0, x - correct_class_scores[:, np.newaxis] + 1.0)
margins[np.arange(N), y] = 0
loss = np.sum(margins) / N
num_pos = np.sum(margins > 0, axis=1)
dx = np.zeros_like(x)
dx[margins > 0] = 1
dx[np.arange(N), y] -= num_pos
dx /= N
return loss, dx
def softmax_loss(x, y):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
probs = np.exp(x - np.max(x, axis=1, keepdims=True))
probs /= np.sum(probs, axis=1, keepdims=True)
# print 'probs',probs
N = x.shape[0]
loss = -np.sum(np.log((probs[np.arange(N), y]))) / N
dx = probs.copy()
dx[np.arange(N), y] -= 1
dx /= N
# print 'loss',loss
return loss, dx
|
f721e01d046579bcb7066abbd3d80b29955f70bd | arafat-hasan/bangladatetime | /bangladatetime/date.py | 23,245 | 3.546875 | 4 | """Concrete date/time and related types.
See http://www.iana.org/time-zones/repository/tz-link.html for
time zone and DST data sources.
"""
__all__ = ("date", "MINYEAR", "MAXYEAR")
import time as _time
from operator import index as _index
def _cmp(x, y):
return 0 if x == y else 1 if x > y else -1
MINYEAR = 1
MAXYEAR = 9999
# _MAXORDINAL = 3652059 # date.max.toordinal()
_MAXORDINAL = 3651695
# Utility functions, adapted from Python's Demo/classes/Dates.py, which
# also assumes the current Gregorian calendar indefinitely extended in
# both directions. Difference: Dates.py calls January 1 of year 0 day
# number 1. The code here calls January 1 of year 1 day number 1. This is
# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
# and Reingold's "Calendrical Calculations", where it's the base calendar
# for all computations. See the book for algorithms for converting between
# proleptic Gregorian ordinals and many other calendar systems.
# -1 is a placeholder for indexing purposes.
_GREGORIAN_DAY_AT_END_OF_BANGLA_MONTH = [
-1, 14, 13, 14, 13, 14, 14, 15, 15, 15, 16, 15, 15
]
_BANGLA_DAY_AT_GREGORIAN_MONTH_START = [
-1, 17, 18, 16, 18, 18, 18, 17, 17, 17, 16, 16, 16
]
_BANGLA_DAY_AT_GREGORIAN_MONTH_END = [
-1, 17, 15, 17, 17, 17, 16, 16, 16, 15, 15, 15, 16
]
_DAYS_IN_GREGORIAN_MONTH = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
_DAYS_IN_BANGLA_MONTH = [-1, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 29, 30]
_MONTHNAMES = [
None, "Bois", "Jyoi", "Asha", "Shra", "Bhad", "Ashs", "Kart", "Ogro",
"Pous", "Magh", "Falg", "Choi"
]
_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
_DAYS_BEFORE_MONTH = [-1] # -1 is a placeholder for indexing purposes.
dbm = 0
for dim in _DAYS_IN_BANGLA_MONTH[1:]:
_DAYS_BEFORE_MONTH.append(dbm)
dbm += dim
del dbm, dim
def _is_leap(year):
year = year + 594
"year -> 1 if leap year, else 0."
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
# def _days_before_year(year): # this funtion needs further checking
# "year -> number of days before January 1st of year."
# y = year - 1
# return y * 365 + y // 4 - y // 100 + y // 400
def _days_before_year(year): # this funtion needs further checking
"year -> number of days before January 1st of year."
y = year - 1
yy = y + 594
# yy is gregorian year respective to bangla year
# and 144 is number of gregorian leap years till 594
return y * 365 + yy // 4 - yy // 100 + yy // 400 - 144
def _gregorian_day_at_bangla_month_end(gregorian_year, gregorian_month):
"""
gregorian_year, gregorian_month -> number of days in that month in that
year.
"""
assert 1 <= gregorian_month <= 12, gregorian_month
return _GREGORIAN_DAY_AT_END_OF_BANGLA_MONTH[gregorian_month]
def _bangla_day_at_gregorian_month_end(gregorian_year, gregorian_month):
"""
gregorian_year, gregorian_month -> number of days in that month in that
year.
"""
assert 1 <= gregorian_month <= 12, gregorian_month
if gregorian_month == 2 and _is_leap(gregorian_year - 594):
return 16
return _BANGLA_DAY_AT_GREGORIAN_MONTH_END[gregorian_month]
def _bangla_day_at_gregorian_month_start(gregorian_year, gregorian_month):
"""
gregorian_year, gregorian_month -> number of days in that month in that
year.
"""
assert 1 <= gregorian_month <= 12, gregorian_month
if gregorian_month == 3 and _is_leap(gregorian_year - 594):
return 17
return _BANGLA_DAY_AT_GREGORIAN_MONTH_START[gregorian_month]
def _days_in_gregorian_month(gregorian_year, gregorian_month):
"""
gregorian_year, gregorian_month -> number of days in that gregorian month
in that gregorian year.
"""
assert 1 <= gregorian_month <= 12, gregorian_month
if gregorian_month == 2 and _is_leap(gregorian_year - 594):
return 29
return _DAYS_IN_GREGORIAN_MONTH[gregorian_month]
def _days_in_month(year, month):
"year, month -> number of days in that bangla month in that bangla year."
assert 1 <= month <= 12, month
if month == 11 and _is_leap(year):
return 30
return _DAYS_IN_BANGLA_MONTH[month]
def _days_before_month(year, month):
"year, month -> number of days in year preceding first day of month."
assert 1 <= month <= 12, 'month must be in 1..12'
return _DAYS_BEFORE_MONTH[month] + (month > 11 and _is_leap(year))
def _ymd2ord(year, month, day):
"year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
assert 1 <= month <= 12, 'month must be in 1..12'
dim = _days_in_month(year, month)
assert 1 <= day <= dim, ('day must be in 1..%d' % dim)
return (_days_before_year(year) + _days_before_month(year, month) + day)
_DI400Y = _days_before_year(401) # number of days in 400 years
_DI100Y = _days_before_year(101) # number of days in 100 years
_DI4Y = _days_before_year(5) # number of days in 4 years
# A 4-year cycle has an extra leap day over what we'd get from pasting
# together 4 single years.
assert _DI4Y == 4 * 365 + 1
# Similarly, a 400-year cycle has an extra leap day over what we'd get from
# pasting together 4 100-year cycles.
assert _DI400Y == 4 * _DI100Y + 1
# OTOH, a 100-year cycle has one fewer leap day than we'd get from
# pasting together 25 4-year cycles.
assert _DI100Y == 25 * _DI4Y - 1
def _ord2md(year, od):
bar = 365 + _is_leap(year)
if not 1 <= od <= bar:
raise ValueError('Ordinal date must be in 1..%d' % bar, od)
for month in range(12, 0, -1):
before = _days_before_month(year, month)
if od > before:
day = od - before
year, month, day = _check_date_fields(year, month, day)
return (month, day)
def _ord2ymd(n):
"ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
if not 1 <= n <= _MAXORDINAL:
raise ValueError('Ordinal date must be in 1..3651695', n)
"""
Boishakh 1, 0001 is ordinal date 1
"""
n -= 1
n400, n = divmod(n, _DI400Y)
year = n400 * 400 # ..., -399, 1, 401, ...
n100, n = divmod(n, _DI100Y)
year += n100 * 100
n4, n = divmod(n, _DI4Y)
year += n4 * 4
isleappossible = True
if n4 == 1:
isleappossible = False
if n100 == 2:
isleappossible = True
if n4 >= 2:
n += 1
if (n100 == 2 and n4 >= 2) or (n100 > 2):
n -= 1
if n == 730 and isleappossible:
return year + 2, 12, 30
if n >= 731 and isleappossible:
n -= isleappossible
n1, n = divmod(n, 365)
year += n1 + 1
if isleappossible and n1 == 1:
dumpyear = 2
else:
dumpyear = 1
month, day = _ord2md(dumpyear, n + 1)
return year, month, day
def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
wday = (_ymd2ord(y, m, d) + 6) % 7
dnum = _days_before_month(y, m) + d
return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
def _format_time(hh, mm, ss, us, timespec='auto'):
specs = {
'hours': '{:02d}',
'minutes': '{:02d}:{:02d}',
'seconds': '{:02d}:{:02d}:{:02d}',
'milliseconds': '{:02d}:{:02d}:{:02d}.{:03d}',
'microseconds': '{:02d}:{:02d}:{:02d}.{:06d}'
}
if timespec == 'auto':
# Skip trailing microseconds when us==0.
timespec = 'microseconds' if us else 'seconds'
elif timespec == 'milliseconds':
us //= 1000
try:
fmt = specs[timespec]
except KeyError:
raise ValueError('Unknown timespec value')
else:
return fmt.format(hh, mm, ss, us)
# Helpers for parsing the result of isoformat()
def _parse_isoformat_date(dtstr):
# It is assumed that this function will only be called with a
# string of length exactly 10, and (though this is not used) ASCII-only
year = int(dtstr[0:4])
if dtstr[4] != '-':
raise ValueError('Invalid date separator: %s' % dtstr[4])
month = int(dtstr[5:7])
if dtstr[7] != '-':
raise ValueError('Invalid date separator')
day = int(dtstr[8:10])
return [year, month, day]
def _parse_hh_mm_ss_ff(tstr):
# Parses things of the form HH[:MM[:SS[.fff[fff]]]]
len_str = len(tstr)
time_comps = [0, 0, 0, 0]
pos = 0
for comp in range(0, 3):
if (len_str - pos) < 2:
raise ValueError('Incomplete time component')
time_comps[comp] = int(tstr[pos:pos + 2])
pos += 2
next_char = tstr[pos:pos + 1]
if not next_char or comp >= 2:
break
if next_char != ':':
raise ValueError('Invalid time separator: %c' % next_char)
pos += 1
if pos < len_str:
if tstr[pos] != '.':
raise ValueError('Invalid microsecond component')
else:
pos += 1
len_remainder = len_str - pos
if len_remainder not in (3, 6):
raise ValueError('Invalid microsecond component')
time_comps[3] = int(tstr[pos:])
if len_remainder == 3:
time_comps[3] *= 1000
return time_comps
# Just raise TypeError if the arg isn't None or a string.
def _check_tzname(name):
if name is not None and not isinstance(name, str):
raise TypeError("tzinfo.tzname() must return None or string, "
"not '%s'" % type(name))
def _check_gregorian_date_fields(year, month, day):
year = _index(year)
month = _index(month)
day = _index(day)
if not MINYEAR <= year <= MAXYEAR:
raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
if not 1 <= month <= 12:
raise ValueError('month must be in 1..12', month)
dim = _days_in_gregorian_month(year, month)
if not 1 <= day <= dim:
raise ValueError('day must be in 1..%d' % dim, day)
return year, month, day
def _check_date_fields(year, month, day):
year = _index(year)
month = _index(month)
day = _index(day)
if not MINYEAR <= year <= MAXYEAR:
raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
if not 1 <= month <= 12:
raise ValueError('month must be in 1..12', month)
dim = _days_in_month(year, month)
if not 1 <= day <= dim:
raise ValueError('day must be in 1..%d' % dim, day)
return year, month, day
def _check_time_fields(hour, minute, second, microsecond, fold):
hour = _index(hour)
minute = _index(minute)
second = _index(second)
microsecond = _index(microsecond)
if not 0 <= hour <= 23:
raise ValueError('hour must be in 0..23', hour)
if not 0 <= minute <= 59:
raise ValueError('minute must be in 0..59', minute)
if not 0 <= second <= 59:
raise ValueError('second must be in 0..59', second)
if not 0 <= microsecond <= 999999:
raise ValueError('microsecond must be in 0..999999', microsecond)
if fold not in (0, 1):
raise ValueError('fold must be either 0 or 1', fold)
return hour, minute, second, microsecond, fold
def _cmperror(x, y):
raise TypeError("can't compare '%s' to '%s'" %
(type(x).__name__, type(y).__name__))
def _divide_and_round(a, b):
"""divide a by b and round result to the nearest integer
When the ratio is exactly half-way between two integers,
the even integer is returned.
"""
# Based on the reference implementation for divmod_near
# in Objects/longobject.c.
q, r = divmod(a, b)
# round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
# The expression r / b > 0.5 is equivalent to 2 * r > b if b is
# positive, 2 * r < b if b negative.
r *= 2
greater_than_half = r > b if b > 0 else r < b
if greater_than_half or r == b and q % 2 == 1:
q += 1
return q
def _isoweek1monday(year):
# Helper to calculate the day number of the Monday starting week 1
# XXX This could be done more efficiently
THURSDAY = 3
firstday = _ymd2ord(year, 1, 1)
firstweekday = (firstday + 6) % 7 # See weekday() above
week1monday = firstday - firstweekday
if firstweekday > THURSDAY:
week1monday += 7
return week1monday
class date:
"""Concrete date type.
Constructors:
__new__()
fromtimestamp()
today()
fromordinal()
Operators:
__repr__, __str__
__eq__, __le__, __lt__, __ge__, __gt__, __hash__
__add__, __radd__, __sub__ (add/radd only with timedelta arg)
Methods:
timetuple()
toordinal()
weekday()
isoweekday(), isocalendar(), isoformat()
ctime()
strftime()
Properties (readonly):
year, month, day
"""
__slots__ = '_year', '_month', '_day', '_hashcode'
def __new__(cls, year, month=None, day=None):
"""Constructor.
Arguments:
year, month, day (required, base 1)
"""
if (month is None and isinstance(year, (bytes, str)) and len(year) == 4
and 1 <= ord(year[2:3]) <= 12):
# Pickle support
if isinstance(year, str):
try:
year = year.encode('latin1')
except UnicodeEncodeError:
# More informative error message.
raise ValueError(
"Failed to encode latin1 string when unpickling "
"a date object. "
"pickle.load(data, encoding='latin1') is assumed.")
self = object.__new__(cls)
self.__setstate(year)
self._hashcode = -1
return self
year, month, day = _check_date_fields(year, month, day)
self = object.__new__(cls)
self._year = year
self._month = month
self._day = day
self._hashcode = -1
return self
# Additional constructors
@classmethod
def fromgregorian(cls,
gregorian_year=None,
gregorian_month=None,
gregorian_day=None):
gregorian_year, gregorian_month, gregorian_day = \
_check_gregorian_date_fields(gregorian_year,
gregorian_month,
gregorian_day)
bar = gregorian_month < 4 or \
(gregorian_month == 4 and gregorian_day < 14)
bangla_year = gregorian_year - 593 - bar
foo = _gregorian_day_at_bangla_month_end(gregorian_year,
gregorian_month)
if gregorian_day <= foo:
bangla_month = (gregorian_month + 8) % 12 or 12
bangla_day = gregorian_day + (_bangla_day_at_gregorian_month_start(
gregorian_year, gregorian_month) - 1)
else:
bangla_month = (gregorian_month + 9) % 12 or 12
bangla_day = gregorian_day - (
_days_in_gregorian_month(gregorian_year, gregorian_month) -
_bangla_day_at_gregorian_month_end(gregorian_year,
gregorian_month))
return cls(bangla_year, bangla_month, bangla_day)
@classmethod
def fromtimestamp(cls, t):
"Construct a date from a POSIX timestamp (like time.time())."
y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
print("called from date class fromtimestamp method")
return cls.fromgregorian(y, m, d)
@classmethod
def today(cls):
"Construct a date from time.time()."
t = _time.time()
return cls.fromtimestamp(t)
@classmethod
def fromordinal(cls, n):
"""Construct a date from a proleptic Gregorian ordinal.
January 1 of year 1 is day 1. Only the year, month and day are
non-zero in the result.
"""
y, m, d = _ord2ymd(n)
return cls(y, m, d)
@classmethod
def fromisoformat(cls, date_string):
"""Construct a date from the output of date.isoformat()."""
if not isinstance(date_string, str):
raise TypeError('fromisoformat: argument must be str')
try:
assert len(date_string) == 10
return cls(*_parse_isoformat_date(date_string))
except Exception:
raise ValueError(f'Invalid isoformat string: {date_string!r}')
# Conversions to string
def __repr__(self):
"""Convert to formal string, for repr().
>>> dt = datetime(2010, 1, 1)
>>> repr(dt)
'datetime.datetime(2010, 1, 1, 0, 0)'
>>> dt = datetime(2010, 1, 1, tzinfo=timezone.utc)
>>> repr(dt)
'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)'
"""
return "%s.%s(%d, %d, %d)" % (self.__class__.__module__,
self.__class__.__qualname__, self._year,
self._month, self._day)
# XXX These shouldn't depend on time.localtime(), because that
# clips the usable dates to [1970 .. 2038). At least ctime() is
# easily done without using strftime() -- that's better too because
# strftime("%c", ...) is locale specific.
def ctime(self):
"Return ctime() style string."
weekday = self.toordinal() % 7 or 7
return "%s %s %2d 00:00:00 %04d" % (_DAYNAMES[weekday],
_MONTHNAMES[self._month],
self._day, self._year)
def __format__(self, fmt):
if not isinstance(fmt, str):
raise TypeError("must be str, not %s" % type(fmt).__name__)
if len(fmt) != 0:
return self.strftime(fmt)
return str(self)
def isoformat(self):
"""Return the date formatted according to ISO.
This is 'YYYY-MM-DD'.
References:
- http://www.w3.org/TR/NOTE-datetime
- http://www.cl.cam.ac.uk/~mgk25/iso-time.html
"""
return "%04d-%02d-%02d" % (self._year, self._month, self._day)
__str__ = isoformat
# Read-only field accessors
@property
def year(self):
"""year (1-9999)"""
return self._year
@property
def month(self):
"""month (1-12)"""
return self._month
@property
def day(self):
"""day (1-31)"""
return self._day
# Standard conversions, __eq__, __le__, __lt__, __ge__, __gt__,
# __hash__ (and helpers)
def timetuple(self):
"Return local time tuple compatible with time.localtime()."
return _build_struct_time(self._year, self._month, self._day, 0, 0, 0,
-1)
def toordinal(self):
"""Return proleptic Gregorian ordinal for the year, month and day.
January 1 of year 1 is day 1. Only the year, month and day values
contribute to the result.
"""
return _ymd2ord(self._year, self._month, self._day)
def replace(self, year=None, month=None, day=None):
"""Return a new date with new values for the specified fields."""
if year is None:
year = self._year
if month is None:
month = self._month
if day is None:
day = self._day
return type(self)(year, month, day)
# Comparisons of date objects with other.
def __eq__(self, other):
if isinstance(other, date):
return self._cmp(other) == 0
return NotImplemented
def __le__(self, other):
if isinstance(other, date):
return self._cmp(other) <= 0
return NotImplemented
def __lt__(self, other):
if isinstance(other, date):
return self._cmp(other) < 0
return NotImplemented
def __ge__(self, other):
if isinstance(other, date):
return self._cmp(other) >= 0
return NotImplemented
def __gt__(self, other):
if isinstance(other, date):
return self._cmp(other) > 0
return NotImplemented
def _cmp(self, other):
assert isinstance(other, date)
y, m, d = self._year, self._month, self._day
y2, m2, d2 = other._year, other._month, other._day
return _cmp((y, m, d), (y2, m2, d2))
def __hash__(self):
"Hash."
if self._hashcode == -1:
self._hashcode = hash(self._getstate())
return self._hashcode
# Computations
def weekday(self):
"Return day of the week, where Monday == 0 ... Sunday == 6."
return (self.toordinal() + 6) % 7
# Day-of-the-week and week-of-the-year, according to ISO
def isoweekday(self):
"Return day of the week, where Monday == 1 ... Sunday == 7."
# 1-Jan-0001 is a Monday
return self.toordinal() % 7 or 7
def isocalendar(self):
"""Return a named tuple containing ISO year, week number, and weekday.
The first ISO week of the year is the (Mon-Sun) week
containing the year's first Thursday; everything else derives
from that.
The first week is 1; Monday is 1 ... Sunday is 7.
ISO calendar algorithm taken from
http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
(used with permission)
"""
year = self._year
week1monday = _isoweek1monday(year)
today = _ymd2ord(self._year, self._month, self._day)
# Internally, week and day have origin 0
week, day = divmod(today - week1monday, 7)
if week < 0:
year -= 1
week1monday = _isoweek1monday(year)
week, day = divmod(today - week1monday, 7)
elif week >= 52:
if today >= _isoweek1monday(year + 1):
year += 1
week = 0
return year, week + 1, day + 1
# Pickle support.
def _getstate(self):
yhi, ylo = divmod(self._year, 256)
return bytes([yhi, ylo, self._month, self._day]),
def __setstate(self, string):
yhi, ylo, self._month, self._day = string
self._year = yhi * 256 + ylo
def __reduce__(self):
return (self.__class__, self._getstate())
# _date_class = date # so functions w/ args named "date" can get at the class
# date.min = date(1, 1, 1)
# date.max = date(9999, 12, 30)
# try:
# from _bangladatetime import *
# except ImportError:
# pass
# else:
# # Clean up unused names
# del (_GREGORIAN_DAY_AT_END_OF_BANGLA_MONTH,
# _BANGLA_DAY_AT_GREGORIAN_MONTH_START,
# _BANGLA_DAY_AT_GREGORIAN_MONTH_END, _DAYS_IN_GREGORIAN_MONTH,
# _DAYS_IN_BANGLA_MONTH, _DAYNAMES, _DAYS_BEFORE_MONTH, _DI100Y,
# _DI400Y, _DI4Y, _MAXORDINAL, _MONTHNAMES, _build_struct_time,
# _check_date_fields, _check_time_fields, _check_tzname, _cmp,
# _cmperror, _date_class, _days_before_month, _days_before_year,
# _days_in_month, _format_time, _is_leap, _isoweek1monday, _ord2ymd,
# _time, _ymd2ord, _divide_and_round)
# # XXX Since import * above excludes names that start with _,
# # docstring does not get overwritten. In the future, it may be
# # appropriate to maintain a single module level docstring and
# # remove the following line.
# from _datetime import __doc__
|
6e670a224c34d3e4bc5feab1d7fd3d37e4dd5efb | seungbok3240/Algorithm | /10610.py | 137 | 3.5 | 4 | n = list(input())
n.sort(reverse=True)
if sum([int(num) for num in n]) % 3 == 0 and '0' in n:
print(''.join(n))
else:
print(-1) |
1f89f934083cd3d34d653ec4226c833278eb2808 | Kunal352000/python_GUI | /LOgin.py | 519 | 3.703125 | 4 | from tkinter import*
root=Tk()
root.geometry("500x500")
root.resizable(0,0)
un=Label(root,text="Enter Name:",font=("Arial",22))
un.grid(row=0,column=0,pady=18,sticky=W)
e1=Entry(root,font=("Arial",20))
e1.grid(row=0,column=1,pady=18)
up=Label(root,text="Enter Password:",font=("Arial",22))
up.grid(row=1,column=0,pady=18,)
e1=Entry(root,font=("Arial",20))
e1.grid(row=1,column=1,pady=18)
b1=Button(root,text="Login",font=("Arial",22))
b1.grid(row=2,column=0,columnspan=2)
root.mainloop()
|
3b1d0f4f464f06987564946eb720995f5f7e9b28 | bobyaaa/Competitive-Programming | /Bruce/Bruno and Pumpkins.py | 1,363 | 3.65625 | 4 | #Solution by Andrew Xing
import sys
n = input()
t = input()
dp_but_not_really = [input() for x in range(n)]
dp_but_not_really.sort()
#We sort our dp. This is because we just want to find the optimal solutions. Say we have -4 -3 -2 1 8. Why would you try
#to compute the distance (if you want three pumpkins) for -4, -3, 1, when clearly -4, -3, -2, will give you a better answer.
#All the optimal answers come from indexes subsequent to one another. So like (-4, -3, -2), (-3, -2, 1), (-2, 1, 8).
#Those are the only things we need to check, and we can run this in O(N) time.
result = 10000
for x in range(t-1, n):
#Find the minimum of the furthest negative and furthest positive
#Use it to compute minimum distance
#If there is only positive, or only negative, then we just use the furthest positive/furthest negative
#as our distance.
if dp_but_not_really[x-(t-1)] <= 0 and dp_but_not_really[x] <= 0:
save = abs(dp_but_not_really[x-(t-1)])
elif dp_but_not_really[x-(t-1)] >= 0 and dp_but_not_really[x] >= 0:
save = abs(dp_but_not_really[x])
else:
minimum = min(abs(dp_but_not_really[x-(t-1)]), dp_but_not_really[x])
if minimum == abs(dp_but_not_really[x-(t-1)]):
save = minimum*2 + dp_but_not_really[x]
else:
save = minimum*2 + abs(dp_but_not_really[x-(t-1)])
if save < result:
result = save
print result
|
d93aaf927cea1f1c23e3666adf5329b0cc46085a | fj2008/python | /Selenium/showDaillyRanking.py | 1,923 | 3.765625 | 4 | from datetime import datetime
import argparse
today = datetime.now()
today = today.strftime("%Y%m%d")
#argqarse 모듈을 사용해서 프로그램실행시 전달하는 값(argument) 를 전달받을 수 있음
parser = argparse.ArgumentParser()
#첫번째 매개변수 = argument의 이름
#두번째 매개변수 = argument의 타입
#세번째 매개변수 = argument의 기본값
parser.add_argument("--date", type=str, default=today)
args = parser.parse_args()
today = args.date
ranking = []
with open("C:/Users/ITPS/Desktop/app_rank/"+today+".tsv","r",encoding="UTF-8") as file:
file.readline()
while True :
line = file.readline()
if line == "":
break
line = line.split("\t")
ranking.append(line[0])
start = 0
end = 20
while True :
for i in range(start,end):
print("{},{}".format(i+1, ranking[i]))
if start == 0 :
print("[ 1. 다음 순위 ({}위~{}위)]".format(start+21,end+20))
print("[ 2. 종료 ]")
elif start >= 20 and end < 200:
print("[ 1. 다음 순위 ({}위~{}위)]".format(start+21,end+20))
print("[ 2. 이전 순위 ({}위~{}위)]".format(start-19,end-20))
print("[ 3. 종료 ]")
elif end >= 200 :
print("[ 1. 이전 순위 ({}위~{}위)]".format(start-19,end-20))
print("[ 2. 종료 ]")
menu = int(input())
if menu == 1:
if end == 200:
start = start -20
end = end-10
start = start+ 20
end = end + 20
else :
start =start+20
end =end + 20
elif menu == 2:
if start ==0:
print("프로그램을 종료합니다.")
break
else:
start = start-20
end = end - 20
else :
if 20 <= start and start <=160:
break
else:
print("존재하지 않는 메뉴입니다.") |
d13e08bdcb8be81a187b03b9d865b38220117f19 | uu64/project-euler | /problem010.py | 450 | 3.609375 | 4 | # -*- coding: utf-8 -*-
MAX = 2000000
MAX_ROOT = MAX**0.5
def main():
# 2以外の偶数は素数じゃないので予め除く
numbers = [i for i in range(3, MAX+1, 2)]
idx = 0
while True:
n = numbers[idx]
if n > MAX_ROOT:
break
numbers = list(filter(lambda x: x<=n or x%n!=0, numbers))
idx += 1
# 除いた2を足す
print(2 + sum(numbers))
if __name__ == "__main__":
main() |
84178f9b3eb63bd768becf5611082644cb910ce9 | philokey/Algorithm-Problems | /Leetcode/Merge Intervals.py | 724 | 3.796875 | 4 | # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Interval
# @return a list of Interval
def merge(self, intervals):
n = len(intervals)
if n == 0: return []
intervals.sort(key = lambda x:x.start)
ret = []
l = intervals[0].start
r = intervals[0].end
for i in range (1,n):
if r < intervals[i].start:
ret.append([l,r])
l = intervals[i].start
r = intervals[i].end
else :
r = max(r,intervals[i].end)
ret.append([l,r])
return ret
|
fefa1c2d37699e0808efd4759e4c6550d0610a1e | atharva07/python-files | /uncommon.py | 485 | 4 | 4 | # function to return all uncommon words
def UncommonWords(A,B):
# count will contain all word counts
count = {}
# insert word of string A into hash
for word in A.split():
count[word] = count.get(word, 0) + 1
# insert word of string B into hash
for word in B.split():
count[word] = count.get(word, 0) + 1
return[word for word in count if count[word] == 1]
A = "Geeks for Geeks"
B = "Geeks for Geeks is awesome"
print(UncommonWords(A,B)) |
270446ceee5205190b3d6eab396455af82982c2e | pmatsinopoulos/effective_python | /19_1_provide_optional_behavior_in_keyword_arguments.py | 239 | 3.625 | 4 | def remainder(number, divisor):
return number % divisor
assert remainder(6, 4) == 2
assert remainder(10, 3) == 1
assert remainder(20, divisor=7) == remainder(number=20, divisor=7)
assert remainder(divisor=7, number=20) == 20 % 7
|
9dedfe38d67e0b14608fe0ee02e8bc0a2a86267b | Brilliant-Kwon/bitpy-adv | /test01/python03.py | 420 | 3.671875 | 4 | def gugu(dan):
print(dan, "단")
print("----------")
# 여기에 코드를 작성합니다
for i in range(0, 10):
print(dan, "*", i, "=", dan * i)
# BEGIN: 점검을 위한 코드이니 수정하지 마십시오
gugu(3)
# END: 점검을 위한 코드이니 수정하지 마십시오
# 테스트를 위해 아래 주석을 해제하고 다른 값을 입력해 보셔도 좋습니다
# gugu(9)
|
cc68e38504b6c167ea31503c63fb8c7115b87928 | lincht/DSA | /ch3/linear_data_structure_ll.py | 1,706 | 4.5 | 4 | from list_ import UnorderedList
class Stack:
"""Implementation of the stack abstract data type using linked lists."""
def __init__(self):
self.items = UnorderedList()
def is_empty(self):
return self.items.is_empty()
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
previous = None
current = self.items.head
while current is not None:
previous = current
current = current.get_next()
return previous.get_data()
def size(self):
return self.items.length()
class Queue:
"""Implementation of the queue abstract data type using linked lists."""
def __init__(self):
self.items = UnorderedList()
def is_empty(self):
return self.items.is_empty()
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return self.items.length()
class Deque:
"""Implementation of the deque abstract data type using linked lists, where
the rear of the deque is at position 0.
"""
def __init__(self):
self.items = UnorderedList()
def is_empty(self):
return self.items.is_empty()
def add_front(self, item):
self.items.append(item)
def add_rear(self, item):
self.items.insert(0, item)
def remove_front(self):
return self.items.pop()
def remove_rear(self):
return self.items.pop(0)
def size(self):
return self.items.length() |
bada36af3fdbed1f52af9a63beabb4389dc952bf | mepky/grade_managemet- | /grademanagement system/backend.py | 1,849 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 2 23:14:45 2018
"""
import sqlite3
#iss code ko backend.py se save karna
def connect():
conn = sqlite3.connect('student.db')
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS data(id INTEGER PRIMARY KEY,name text,username text,email_id text,password text)")
conn.commit()
conn.close()
def insert(name,username, email_id, password):
conn = sqlite3.connect('student.db')
cur = conn.cursor()
cur.execute("INSERT INTO data VALUES(NULL,?,?,?,?)", (name,username, email_id, password))
conn.commit()
conn.close()
k=("select * from data")
return k[0]
def view():
conn = sqlite3.connect('student.db')
cur = conn.cursor()
cur.execute("SELECT * FROM data")
row = cur.fetchall()
conn.close()
return row
def search(name='',username='', email_id='', password=''):
conn = sqlite3.connect('student.db')
cur = conn.cursor()
cur.execute("SELECT * FROM data WHERE name=? OR username=? OR email_id=? OR password=?", (name,username, email_id, password))
rows = cur.fetchall()
conn.close()
return rows
def update(id,name,username, email_id, password):
conn = sqlite3.connect('student.db')
cur = conn.cursor()
cur.execute("UPDATE data SET name=? OR username=? OR email_id=? OR password=? WHERE id=?", (name,username, email_id, password,id))
conn.commit()
conn.close()
def delete(id):
conn = sqlite3.connect('student.db')
cur = conn.cursor()
cur.execute("DELETE FROM data WHERE id=?",(id,))
conn.commit()
conn.close()
connect()
#insert("deepak","kumar","qasselephant","fucku")
#delete(1)
#update(1,'vikash','kumar','qasselephant','fucku')
print(search(name='saif'))
#print(view())
|
dd65ed5e70f40f471f3c67e480323d21df6365d0 | Romko97/Python | /Softserve/room_work_03.py | 3,748 | 4.375 | 4 | # 1. Написати скрипт, який з двох введених чисел визначить, яке з них більше,
# а яке менше.
'''
a = int(input("enter first number:"))
b = int(input("enter sekond number:"))
print(f"number {a} is biger then {b}"if a > b else f"number {b} is biger then {a}")
'''
# 2. Написати скрипт, який перевірить чи введене число парне чи непарне
# і вивести відповідне повідомлення.
'''
number = int(input("Enter pleas number:"))
print("number is even"if number % 2 == 0 else "number is odd")
'''
# 3. Написати скрипт, який обчислить факторіал введеного числа.
'''
number = int(input("Enter pleas number:"))
a = int(number)
while a != 1:
number = number * (a-1)
a = a-1
print(number)
chyslo = input('enter factorial :')
t = 1
for i in range(1, int(chyslo)+1):
t *= i
print(t)
'''
# 1. Роздрукувати всі парні числа менші 100 (написати два варіанти коду: один
# використовуючи цикл while, а інший з використанням циклу for).
'''
a = 1
while a < 100:
if a % 2 == 0:
print(a)
a = a + 1
'''
'''
for i in range(0,101,2):
print(i)
'''
# 2. Роздрукувати всі непарні числа менші 100. (написати два варіанти коду:
# один використовуючи оператор continue, а інший без цього оператора).
'''
a = 0
while a < 100:
a = a + 1
if a % 2 == 0:
continue
else:
print(a)
'''
'''
for i in range(100):
if i % 2 == 0:
continue
else:
print(i)
'''
'''
a = 0
while a < 100:
a = a + 1
if a % 2 == 0:
pass
else:
print(a)
'''
'''
for i in range(100):
if i % 2 == 0:
pass
else:
print(i)
'''
'''
for i in range(1,100,2):
print(i)
'''
# 3. Перевірити чи список містить непарні числа.
# (Підказка: використати оператор break)
'''
pass
'''
# 4. Створити список, який містить елементи цілочисельного типу, потім за
# допомогою циклу перебору змінити тип даних елементів на числа з плаваючою
# крапкою. (Підказка: використати вбудовану функцію float ()).
'''
spysok = list(range(10))
for i in spysok:
spysok[i] = float(spysok[i])
print(spysok)
'''
# 5. Вивести числа Фібоначі включно до введеного числа n, використовуючи
# цикли. (Послідовність чисел Фібоначі 0, 1, 1, 2, 3, 5, 8, 13 і т.д.)
'''
number = int(input("Enter the number for generat sequence of namber Fibonacci:"))
fibo = [0, 1]
for i in range(number-1):
fibo[i+1] = fibo[i-1] + fibo[i]
fibo.append(fibo[i+1])
fibo.remove(fibo[i+1])
print(fibo)
'''
def fib(n):
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a + b
print()
'''
fib(1000)
'''
def fib2(n):
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a + b
print(result)
'''
fib2(100)
'''
# 6. Створити список, що складається з чотирьох елементів типу string. Потім,
# за допомогою циклу for, вивести елементи по черзі на екран.
'''
spysok = ["Helow,", "World!", "how're", "you?"]
for i in spysok:
print(i)
'''
|
b5644376df6b025f263c98cc1b11d6ef1bafb315 | imcinerney/argot | /dictionary/merriam_webster_scraper.py | 24,232 | 3.546875 | 4 | """This module handles scraping dictionary entries and adding them to the db
This module handles visiting a website to look up a word's definition and then
navigating the HTML to extract the desired information to store in the database.
Main Functions:
scrape_word(word, search_synonym=False)
word: string of word to lookup
search_synonym: boolean indicating whether or not to look up the
synonyms listed for a word, if set false this information is stored in
a table for a later lookup
This function is the main function of the module, it handles looking up
a word and storing it in the databse. The function will check to make
sure that the word already isn't in the database. It returns True if
the word entered had a valid entry, returns False if the site didn't
match a word.
Example:
python3 manage.py shell
from dictionary import merriam_webster_scraper as mws
mws.scrape_word('bolster', True)
load_list_of_words(filename)
filename: name of file to lookup stored in dictionary/word_lists/
Scraped the definition of every word in the file. Each line should be a
word to lookup. The default search_synonym for this words is True,
meaning that the scraper will visit the entry pages for every
synonym and antonym listed on the page. Easy way to fill the database
with a lot of entries at once.
Example:
python3 manage.py shell
from dictionary import merriam_webster_scraper as mws
mws.load_list_of_words('top_gre_words.txt')
fill_in_synonyms()
This function will look at all of the synonyms for the base words whose
synonyms we have not added yet. Depending on how many words are in the
database, this function could take a while to complete. Fills in
incompete entries.
Example:
python3 manage.py shell
from dictionary import merriam_webster_scraper as mws
mws.fill_in_synonyms()
"""
from bs4 import BeautifulSoup
import requests
import time
import random
import os
import re
from dictionary import models
from django.db import transaction
from django.db.models import F
from django.db.utils import IntegrityError
@transaction.atomic()
def scrape_word(word, search_synonym=False):
"""Scrape entry for page and loads into database
Keyword arguments:
word -- word to add to database
search_synonym -- boolean to add all synonyms listed to database as well
Returns True if word found, False if not
"""
if _already_entered(word, search_synonym):
return True
url = 'https://www.merriam-webster.com/dictionary/' + word
try:
r = requests.get(url, timeout=10)
except requests.exceptions.Timeout:
time.sleep(5)
return scrape_word(word, search_synonym)
if r.status_code == 404:
return False
soup = BeautifulSoup(r.content, 'html5lib')
_manage_dictionary_entries(soup, word, search_synonym)
return True
def load_list_of_words(filename):
"""Loads list of words and adds to db if not already in"""
word_list_file = os.path.join('dictionary', 'word_lists', filename)
word_list = _load_word_list(word_list_file)
variant_word_set = models.VariantWord.objects.values_list('name', flat=True)
for word in word_list:
if word not in variant_word_set:
print(word)
scrape_word(word, search_synonym=True)
time.sleep(1)
def fill_in_synonyms():
"""Adds the synonyms for all basewords that haven't been added yet"""
qs = models.BaseWord.objects.filter(searched_synonym=False)
for word in qs:
print(word.name)
scrape_word(word.name, search_synonym=True)
time.sleep(2)
def _already_entered(word, search_synonym):
"""Checks to see if a word is already entered.
If a word has been entered, check if the synonyms have been searched. If
they haven't and search_synonym is true, then lookup all of the words
associated with the baseword in the SynonymsToLookUp table
"""
variant_word_set = models.VariantWord.objects.all().values_list('name',
flat=True)
if word in variant_word_set:
if search_synonym:
base_word_ = models.VariantWord.objects.get(name=word).base_word
if not base_word_.searched_synonym:
synonyms_to_lookup = base_word_.synonymstolookup_set.all()
for synonym in synonyms_to_lookup:
if synonym.is_synonym:
print(f'Looking up the synonym: {synonym.lookup_word}')
else:
print(f'Looking up the antonym: {synonym.lookup_word}')
valid_word = scrape_word(synonym.lookup_word)
synonym_word = synonym.lookup_word
if valid_word:
synonym_vw = models.VariantWord.objects \
.get(name=synonym_word)
if synonym.is_synonym:
_ = models.Synonym.objects \
.get_or_create(base_word=base_word_,
synonym=synonym_vw)
else:
_ = models.Antonym.objects \
.get_or_create(base_word=base_word_,
antonym=synonym_vw)
synonym.delete()
base_word_.searched_synonym = True
base_word_.save()
return True
else:
return False
def _manage_dictionary_entries(soup, word, search_synonym):
"""Searches soup for pertinent sections and sends to functions to handle"""
def_wrapper = soup.find('div', {'id': 'definition-wrapper'})
left_content = def_wrapper.find('div', {'id' : 'left-content'})
#If there's an entry, probably a more commonly spelled name to search
first_entry = left_content.find('div', {'id' : 'dictionary-entry-1'})
new_word = first_entry.find('a', {'class' : 'cxt', 'rel' : 'prev'})
if new_word is not None:
time.sleep(1)
new_word = new_word.getText().strip()
print(f'revising search from {word} to {new_word}')
return scrape_word(new_word, search_synonym)
variant_word_set = models.VariantWord.objects.all().values_list('name',
flat=True)
(word_name, base_word_) = _handle_main_dictionary_entry(left_content,
variant_word_set,
search_synonym)
if base_word_ is None:
return None
_compile_alternate_spellings(left_content, word_name, word, base_word_,
variant_word_set)
_add_synonyms(left_content, base_word_, search_synonym)
def _handle_main_dictionary_entry(left_content, variant_word_set,
search_synonym):
"""Searches for content containing the main aspects of a dictionary entry
Keyword argument:
left_content -- section of wepage containing the text of the dictionary
entries
variant_word_set -- list of all spellings of words currently in the
database
search_synonym -- whether or not we will search for synonyms for the word
Loops through the main sections of the webpage. Will create the base_word,
form_words, the definitions, pos, examples for a word
"""
entries = (left_content.find_all('div', {'class': 'entry-header'},
recursive=False))
i = 1
first_entry = entries[0]
remaining_entries = entries[1:]
(base_word_, word_name) = _add_base_and_form(first_entry,
i, left_content,
variant_word_set,
search_synonym)
#Loop through all definition sections, broken down by part of speech
for entry in remaining_entries:
i += 1
#We only use the return values for the first entry
if base_word_ is not None:
_ = _add_base_and_form(entry, i, left_content,
variant_word_set, search_synonym)
else:
(base_word_, _) = _add_base_and_form(entry, i, left_content,
variant_word_set,
search_synonym)
return (word_name, base_word_)
def _add_base_and_form(entry, i, left_content, variant_word_set,
search_synonym):
"""Function to add baseword and formword entries to db
Keyword arguments:
entry -- section of page that contains information on the word name and
part of speech
i -- used to identify which section the corresponding defintion and example
is located
left_content -- main section that contains all information on the entries
for words
variant_word_set -- list of all spellings of words currently in the
database
search_synonym -- whether or not we will search for synonyms for the word
Returns:
(base_word_, word_name)
base_word_ -- BaseWord object for the dictionary page
word_name -- The word_name as appears on the webpage (could be diff from
what gets searched)
"""
word_name = entry.find('div').find(['h1', 'p'], {'class' : 'hword'}) \
.getText().lower()
word_name = _clean_word_name(word_name)
if word_name is None:
return (None, None)
base_word_, _ = models.BaseWord.objects.get_or_create(name=word_name,
searched_synonym=search_synonym)
pos_ = _find_pos(entry)
#If there's no pos, probably not a valid dictionary entry
if pos_ is None:
return (None, word_name)
form_word_, _ = (models.FormWord.objects
.get_or_create(pos=pos_,
base_word=base_word_,))
_add_definition_and_examples(i, left_content, form_word_)
return (base_word_, word_name)
def _add_definition_and_examples(dictionary_entry_num, left_content,
form_word_):
"""Helper function to find the defintion & example sentence sections
Keyword arguments:
dictionary_entry_num -- Used to locate the correct HTML tag
left_content -- The part of the webpage that contains all pertinent info
form_word_ -- FormWord object to link definition to
Merriam webster does not keep all information for an entry in one parent
HTML tag. Instead, it puts information regarding the word name and part of
speech in one tag and then another tag for the defintions and example
sentence in the next tag. We use the dictionary_entry_num to locate the
associated definition entry with the correct word and pos.
Returns nothing, as we just create the entries unless they are already in
the database.
"""
def_entry_num = 'dictionary-entry-' + str(dictionary_entry_num)
def_entry = left_content.find('div', {'id' : def_entry_num})
definition_headers = def_entry.find_all('div', {'class' : 'vg'},
recursive=False)
for def_header in definition_headers:
definitions = def_header.find_all('span', {'class' : 'dtText'})
for definition in definitions:
#These are examples or quotes we don't need in the definition
extra_text = definition.find_all('span', {'class' : 'ex-sent'})
examples = definition.find_all('span', {'class' : 't'})
clean_defs = _clean_definition(definition, extra_text)
for clean_def in clean_defs:
word_def, _ = models.WordDefinition.objects \
.get_or_create(form_word=form_word_,
definition=clean_def)
for example in examples:
example_text = _clean_example_text(example.getText())
_, _ = models.ExampleSentence.objects \
.get_or_create(definition=word_def,
sentence=example_text)
def _find_pos(entry):
"""Helper function to find the pos on the site and return pos object
Keyword arguments:
entry -- the section of HTML that contains word_name, def, and pos
The part of speech can be found in different sections. Most of the time it
it stored in the 'import-blue-link' class within the entry. Otherwise, it
is in the 'fl' class. If it isn't in either of those, return a None. If it
is found, returns a PartOfSpeech object.
"""
try:
pos_text = _clean_pos_text(entry
.find('a', {'class' : 'important-blue-link'})
.getText())
except AttributeError:
try:
pos_text = _clean_pos_text(entry.find('span' , {'class' : 'fl'})
.getText())
except AttributeError:
return None
pos_, _ = models.PartOfSpeech.objects.get_or_create(name=pos_text)
return pos_
def _clean_example_text(example_text):
"""Returns just a sentence"""
p = re.compile('([A-z][A-z ,-\\\/()\']*)')
match = p.search(example_text)
if match is None:
raise (ValueError(f'Something wrong happened when extracting the part '
f'of speech. The extracted text is: {example_text}'))
return match.group()
def _clean_definition(definition, extra_text):
"""Clean a scraped definition"""
def_text = definition.getText().strip()
for text in extra_text:
extra = text.getText().strip()
def_text = def_text.replace(extra, '')
def_text = def_text.replace('archaic :', 'archaic --')
def_text = re.sub('\(see.*\)', '', def_text)
def_text = re.sub('sense [0-9][a-zA-Z]?', '', def_text)
def_text = re.sub('sense [a-zA-Z]?', '', def_text)
def_text = re.sub(' +', ' ', def_text)
split_defs = def_text.split(':')
p = re.compile('([a-zA-Z][a-zA-Z ,-\\\/()\']*)')
return [p.search(split_def).group().strip()
for split_def in split_defs
if p.search(split_def) is not None]
def _clean_pos_text(pos_text):
"""Limit to just the word"""
p = re.compile('([A-z ]*)')
match = p.search(pos_text)
if match.group() is None:
raise (ValueError(f'Something wrong happened when extracting the part '
f'of speech. The extracted text is: {pos_text}'))
else:
return match.group().strip()
def _clean_word_name(word):
"""Cleans the text for a word name, returns None if no match
Prevents us from adding entries that are just prefixes of suffixes, e.g.
-phobia.
"""
p = re.compile('(^[\w]+[\w-]*[\w]+)')
match = p.search(word)
if match is None:
#Make sure we aren't excluding one letter words
p = re.compile('(^[\w]$)')
match = p.search(word)
if match is None:
return None
else:
return match.group(0)
else:
return match.group(0)
def _compile_alternate_spellings(left_content, word_name, word, base_word_,
variant_word_set):
"""Search the page to add all the alternatative spellings of a word
Merriam webster sometimes stores this info in two parts, thus the adding
of the words in 'variants' section an dalso the 'alternate_forms' sections
"""
alternate_forms = left_content.find_all('span', {'class' : 'vg-ins'})
variants = left_content.find_all('a', {'class' : 'va-link'})
other_word_section = left_content.find('div', {'id' : 'other-words-anchor'})
if other_word_section:
other_words = other_word_section.find_all('div', {'class' : 'uro'})
else:
other_words = []
different_spellings = set()
different_spellings.add(word_name)
different_spellings.add(word)
for variant in variants:
different_spellings.add(variant.getText().strip())
for alternate_form in alternate_forms:
different_forms = alternate_form.find_all('span', {'class' : 'if'})
for different_form in different_forms:
different_spellings.add(different_form.getText().strip())
for other_word in other_words:
different_spellings.add(other_word.find('span', {'class' : 'ure'})
.getText().strip())
different_spellings = [spelling for spelling in different_spellings
if spelling not in variant_word_set]
for spelling in different_spellings:
_, _ = (models.VariantWord.objects.get_or_create(base_word=base_word_,
name=spelling))
def _add_synonyms(left_content, base_word_, search_synonym):
"""Adds synonyms to database
Keyword arguments:
left_content -- the portion of the merriam-webster webpage that stores the
pertinent information for building our entry
base_word_ -- BaseWord object associated with the word we are looking up
search_synonym -- tells us whether to lookup the synonyms or stow them in
the SynonymsToLookUp table
Adds synonyms listed on page, checks to see if words are in database,
if they are not, call scrape_word() to add them and then add to database.
The large issue with getting synonyms on Merriam-Webster is that sometimes
Merriam-Webster's entry for a word does not have the synonym/antonym section
that most entries do. However, there's another section that contains a list
of synonyms. _scrape_main_synonym_section() handles the default synonym
section, while _scrape_alternative_synonym_section() handles the alternative
synonym section. They return a list that contains a tuple that stores a list
of words to add to the dictionary and synonym table.
"""
try:
synonym_list = _scrape_main_synonym_section(left_content)
except AttributeError:
try:
synonym_list = _scrape_alternative_synonym_section(left_content)
except AttributeError:
return
if search_synonym:
_create_synonyms(left_content, base_word_, synonym_list)
else:
_create_synonym_lookups(left_content, base_word_, synonym_list)
def _scrape_main_synonym_section(left_content):
"""Scrapes the main/default synonym section for a word.
If there is no pos listed, use the one listed for the word
"""
synonym_header = left_content.find('div',
{'class' : 'synonyms_list'})
synonym_labels = synonym_header.find_all('p',
{'class' : 'function-label'})
synonym_lists = synonym_header.find_all('p', {'class' : None})
if len(synonym_labels) != len(synonym_lists):
raise ValueError('There are an uneven number of labels and lists')
synonym_list = []
for label, s_list in zip(synonym_labels, synonym_lists):
word_list = s_list.find_all('a')
word_list_text = [word for word in word_list]
pos_synonym_flag = label.getText().lower()
synonym_list.append((pos_synonym_flag, word_list_text))
return synonym_list
def _scrape_alternative_synonym_section(left_content):
"""Scrapes the alternative synonym listing"""
synonym_header = left_content.find('div',
{'class' : 'syns_discussion'})
synonym_lists = synonym_header.find_all('p', {'class' : 'syn'})
synonym_list = []
for s_list in synonym_lists:
word_list = s_list.find_all('a')
word_list_text = [word for word in word_list]
#Only will list synonyms, so just add synonym as flag
synonym_flag = 'synonyms: '
synonym_list.append((synonym_flag, word_list_text))
return synonym_list
def _create_synonyms(left_content, base_word_, synonym_list):
"""Creates synonyms for a word"""
p = re.compile('(^[\w\-]*)')
for (pos_synonym_flag, word_list) in synonym_list:
for word in word_list:
variant_word_set = models.VariantWord.objects.values_list('name',
flat=True)
word_text = _clean_word_name(word.getText().lower())
if word_text == base_word_.name:
continue
m = p.match(pos_synonym_flag)
synonym_flag = m.group(1)
if word_text not in variant_word_set:
synonym_variant_word = _handle_creating_synonyms(word_text,
variant_word_set, synonym_flag)
else:
synonym_variant_word = models.VariantWord.objects.all() \
.get(name=word_text)
if synonym_flag == 'synonyms':
_, _ = models.Synonym.objects \
.get_or_create(base_word=base_word_,
synonym=synonym_variant_word)
else:
_, _ = models.Antonym.objects \
.get_or_create(base_word=base_word_,
antonym=synonym_variant_word)
def _create_synonym_lookups(left_content, base_word_, synonym_list):
"""Stows away synonyms to lookup when we don't have to look them up now"""
p = re.compile('(^[\w\-]*)')
for (pos_synonym_flag, word_list) in synonym_list:
for word in word_list:
word_text = _clean_word_name(word.getText().lower())
if word_text == base_word_.name:
continue
m = p.match(pos_synonym_flag)
synonym_flag = m.group(1)
is_synonym = synonym_flag == 'synonyms'
_, _ = models.SynonymsToLookUp.objects \
.get_or_create(base_word=base_word_,
lookup_word=word_text,
is_synonym=is_synonym)
def _handle_creating_synonyms(word_text, variant_word_set, synonym_flag):
"""Adds synonym to db and returns the associated base word
Keyword arguments:
word_text -- the synonym/anonym listed to lookup
variant_word_set -- list of all different spellings of words in the db
Sometimes a word will be listed as a synonym that and has an entry page that
lists an alternative spelling that has its own page. If later on, a synonym
for a different word lists an alternative spelling of the word with its own
page, this can cause a failure to lookup a word successfully. For example,
if we look up the word 'capricious,' it lists 'settled' as an antonym.
'Settled' directs to the 'settle' entry that lists 'settling' as an
alternative form of the word. The word 'precipitate' lists 'settlings' as a
synonym. 'settlings' does not show up as an alternative form/spelling for
'settle.' Thus, we would look up 'settlings,' which goes to the 'settling'
page. When we try to add 'settling' to the database, there will be an error,
because 'settling' was already added to the variant word set. Thus, we try
to remove an 's' if the main spelling fails.
"""
if synonym_flag == 'synonyms':
msg = 'synonym'
else:
msg = 'antonym'
print(f'looking up the {msg}: {word_text}')
time.sleep(2)
try:
scrape_word(word_text)
except IntegrityError:
word_text = re.sub('s$', '', word_text)
if word_text not in variant_word_set:
scrape_word(word_text)
return models.VariantWord.objects.all().get(name=word_text)
def _load_word_list(filename):
"""Reads file of words into list"""
with open(filename, 'r') as f:
return [line.strip() for line in f]
|
564038a23819cb8cf28f2d0c36cbc84ae47f12ba | daniel-reich/ubiquitous-fiesta | /W7S25BPmjEMSzpnaB_2.py | 500 | 3.578125 | 4 |
def n_bonacci_generator(n, k):
if k == 1:
yield 0
return
if n == 1:
for _ in range(k):
yield 1
base = [0 for _ in range(n - 1)]
for _ in range(n - 1):
yield 0
yield 1
base.append(0)
base.append(1)
for _ in range(k - n):
for i in range(n):
base[i] = base[i + 1]
base[n] = 0
base[n] = sum(base)
yield base[n]
def bonacci(N, k):
return list(n_bonacci_generator(N, k))[-1]
|
462a53c5f18f9e4eb5a5bfb3acf6241a21b93489 | kant/AtCoder | /AVC/GoriRadioGym/012/c.py | 150 | 3.796875 | 4 | x=int(input())
if x % 11 == 0:
print(x // 11 * 2)
else:
if x % 11 > 6:
print(x // 11 * 2 + 2)
else:
print(x // 11 * 2 + 1) |
5ec2c29269dd8ab7b64329f165ef2fa801696a24 | mvieiradev/CursoemVideoPython3 | /exe31.py | 288 | 3.859375 | 4 | #Custo de Viagen
distancia = float(input('Quale a distancia da sua viagem?'))
print('Voce esta prestes a comecar uma viagen de {}Km.'.format(distancia))
preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45
print('E o preço da sua passagem sera de R${:.2f}'.format(preço)) |
e232c6a4e49c85be11b66c74725c7f7dc2a0b898 | JohnnyFang/datacamp | /12-Introduction-to-Databases-in-Python/02-applying-filtering-ordering-and-grouping-to-queries/10-determining-the-population-sum-by-state.py | 1,065 | 3.6875 | 4 | '''
Import func from sqlalchemy.
Build an expression to calculate the sum of the values in the pop2008 field labeled as 'population'.
Build a select statement to get the value of the state field and the sum of the values in pop2008.
Group the statement by state using a .group_by() method.
Execute stmt using the connection to get the count and store the results as results.
Print the keys/column names of the results returned using results[0].keys().
'''
# Import func
from sqlalchemy import func
# Build an expression to calculate the sum of pop2008 labeled as population
pop2008_sum = func.sum(census.columns.pop2008).label('population')
# Build a query to select the state and sum of pop2008: stmt
stmt = select([census.columns.state, pop2008_sum])
# Group stmt by state
stmt = stmt.group_by(census.columns.state)
# Execute the statement and store all the records: results
results = connection.execute(stmt).fetchall()
# Print results
print(results)
# Print the keys/column names of the results returned
print(results[0].keys())
|
87f4be25fda7bf6c364ba86e28a70d5fa6953dfb | rklabs/python_cookbook_snippets | /priority_queue.py | 1,192 | 4.40625 | 4 | #!/usr/bin/env python
'''
Priority queue implements object ordering based on priority attached to that
object. The item is pushed into the queue along with priority and index.
Before understanding why index is required lets see tuple comparison. Tuple
comparison is done element by element in same position. This is true for all
sequence types. Index is required when two Items have the same priority. If
name and priority is two Item's is same then they are compared based on index
value.
'''
import heapq
class PriorityQueue(object):
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
class Item(object):
def __init__(self, name):
self._name = name
def __repr__(self):
return 'Item({!r})'.format(self._name)
if __name__ == '__main__':
pq = PriorityQueue()
pq.push(Item('foo'), 5)
pq.push(Item('bar'), 4)
pq.push(Item('baz1'), 1)
pq.push(Item('baz2'), 1)
print(pq.pop())
print(pq.pop())
print(pq.pop())
|
6c45a5124df05c886be7facf9123ab884b7757e4 | Python-Repository-Hub/the-art-of-coding | /Level.1/Step.02/2.2_FindBoth.1.py | 318 | 3.890625 | 4 | def find_both(S):
largest, smallest = S[0], S[0]
for i in range(1, len(S)):
if S[i] > largest:
largest = S[i]
if S[i] < smallest:
smallest = S[i]
return largest, smallest
S = list(map(int, input().split()))
largest, smallest = find_both(S)
print(largest, smallest)
|
742c7b4fdf539c152c819ef828ff4724a67c2e79 | e8johan/adventofcode2020 | /18/day18.py | 6,971 | 3.8125 | 4 | def tokenize(expr):
# list of tuples
#
# ('N', value) => integer value
# ('T', char) => token character
res = []
# Current number, might be a sequence of digits
number = ''
while True:
# Current token, if found
found_token = ''
# True if whitespace is found
found_whitespace = False
peek = expr[0]
if peek in '0123456789':
# part of number
number += peek
elif peek in '()+*':
# token
found_token = peek
elif peek in ' ':
# whitespace
found_whitespace = True
# If we have a token or whitespace, the number has ended
if found_token != '' or found_whitespace:
if number != '':
res.append(('N', int(number)))
number = ''
# Append any found tokens
if found_token != '':
res.append(('T', found_token))
# Check if we can continue
if len(expr) > 1:
expr = expr[1:]
else:
break
# Append any left-over number
if number != '':
res.append(('N', int(number)))
return res
def a_expression(tokens, ind=0):
# ind is used to indent prints
# I left the prints I used for debugging commented out below
#
# this solution uses a flat while loop to multiply and add, and recursion
# only for parenthesises
res_value = 0
res_consumed = 0
if tokens[0] == ('T', '('):
v, c = a_expression(tokens[1:], ind+2)
res_value = v
res_consumed = 2+c
assert tokens[1+c] == ('T', ')')
elif tokens[0][0] == 'N':
res_value = tokens[0][1]
res_consumed = 1
#print(' '*ind + "VALUE %d" % (res_value))
while True:
#print(' '*ind + "loop %d, %d" % (res_value, res_consumed))
if len(tokens) == res_consumed:
#print(' '*ind + "ENDEXPR")
break
elif tokens[res_consumed] == ('T', ')'):
#print(' '*ind + "ENDPAREN")
break
elif tokens[res_consumed] == ('T', '+'):
#print(' '*ind + "ADD")
res_consumed += 1
if tokens[res_consumed][0] == 'N':
#print(' '*ind + "NUM %d" % (tokens[res_consumed][1]))
res_value += tokens[res_consumed][1]
res_consumed += 1
elif tokens[res_consumed] == ('T', '('):
res_consumed += 1
v, c = a_expression(tokens[res_consumed:], ind+2)
res_value += v
res_consumed += c
assert tokens[res_consumed] == ('T', ')')
res_consumed += 1
else:
assert False
elif tokens[res_consumed] == ('T', '*'):
#print(' '*ind + "MUL")
res_consumed += 1
if tokens[res_consumed][0] == 'N':
#print(' '*ind + "NUM %d" % (tokens[res_consumed][1]))
res_value *= tokens[res_consumed][1]
res_consumed += 1
elif tokens[res_consumed] == ('T', '('):
res_consumed += 1
v, c = a_expression(tokens[res_consumed:], ind+2)
res_value *= v
res_consumed += c
assert tokens[res_consumed] == ('T', ')')
res_consumed += 1
else:
assert False
else:
assert False
else:
assert False
#print(' '*ind + "=> %d, %d" % (res_value, res_consumed))
return (res_value, res_consumed)
def b_value(tokens):
res_value = 0
res_consumed = 0
if tokens[0] == ('T', '('):
res_consumed += 1
v, c = b_mul_expression(tokens[1:])
res_value = v
res_consumed += c
assert tokens[res_consumed] == ('T', ')')
res_consumed += 1
elif tokens[0][0] == 'N':
res_value = tokens[0][1]
res_consumed += 1
return (res_value, res_consumed)
def b_mul_expression(tokens):
res_value, res_consumed = b_add_expression(tokens)
while res_consumed < len(tokens) and tokens[res_consumed] == ('T', '*'):
res_consumed += 1
v, c = b_add_expression(tokens[res_consumed:])
res_value *= v
res_consumed += c
return (res_value, res_consumed)
def b_add_expression(tokens):
res_value, res_consumed = b_value(tokens)
while res_consumed < len(tokens) and tokens[res_consumed] == ('T', '+'):
res_consumed += 1
v, c = b_value(tokens[res_consumed:])
res_value += v
res_consumed += c
return (res_value, res_consumed)
def b_expression(tokens):
# as we have operator precedence, this solution uses recursion to encode
# this. The outer function (this one), is more or less a wrapper, just to
# avoid having to show that the mul is the outer evalution.
#
# the hierarcy is:
#
# mul <---- evaluated last
# add
# value <--- evaluated first
#
# the value can be either an integer, or a sub-expression, i.e.
# '(' + mul + ')'
#
# mul and add will act as a pass-through for the value if no '*' or '+'
# operator is encountered.
res_value = 0
res_consumed = 0
v, c = b_mul_expression(tokens)
res_value += v
res_consumed += c
return (res_value, res_consumed)
def inner_a(expr):
tokens = tokenize(expr)
value, consumed = a_expression(tokens)
assert consumed == len(tokens)
return value
def a(values):
res = 0
for v in values:
res += inner_a(v)
return res
def inner_b(expr):
tokens = tokenize(expr)
value, consumed = b_expression(tokens)
assert consumed == len(tokens)
return value
def b(values):
res = 0
for v in values:
res += inner_b(v)
return res
def test_a():
assert inner_a('1 + 2 * 3 + 4 * 5 + 6') == 71
assert inner_a('1 + (2 * 3) + (4 * (5 + 6))') == 51
assert inner_a('2 * 3 + (4 * 5)') == 26
assert inner_a('5 + (8 * 3 + 9 + 3 * 4 * 3)') == 437
assert inner_a('5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))') == 12240
assert inner_a('((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2') == 13632
def test_b():
assert inner_b('1 + (2 * 3) + (4 * (5 + 6))') == 51
assert inner_b('2 * 3 + (4 * 5)') == 46
assert inner_b('5 + (8 * 3 + 9 + 3 * 4 * 3)') == 1445
assert inner_b('5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))') == 669060
assert inner_b('((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2') == 23340
if __name__ == '__main__':
# Input
values = []
# Read the input
with open("input.txt", "r") as f:
values = f.read().splitlines()
print("Result a: %d" % (a(values),))
print("Result b: %d" % (b(values),))
|
efff593c12b8867813d70c243edec233839d55d1 | yamaton/codeeval | /easy/multiples.py | 1,054 | 4.40625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
multiples.py
Created by Yamato Matsuoka on 2012-07-16.
Description: Given numbers x and n, where n is a power of 2, print out the smallest multiple of n which is greater than or equal to x. Do not use division or modulo operator.
Input sample:
The first argument will be a text file containing a comma separated list of two integers, one list per line. e.g.
13,8
17,16
Output sample:
Print to stdout, the smallest multiple of n which is greater than or equal to x, one per line.
e.g.
16
32
"""
import sys
import itertools
def smallest_multiple(x, n):
"""
x is an integer. n is a power of 2.
Return the smallest multiple of n which is greater than or equal to x.
"""
for i in itertools.count(1):
multiple = i * n
if multiple >= x:
return multiple
if __name__ == '__main__':
with open(sys.argv[1], "r") as f:
data = [[int(x) for x in line.rstrip().split(",")] for line in f]
for (x, n) in data:
print smallest_multiple(x,n)
|
0690cc739dba31d955bb61e42fb566dc912cf145 | apurva05/hello-world | /ex2.py | 289 | 3.890625 | 4 | print "i will count some numbers:"
print "hens ", 25+30/6
print "some more numbers", 100-50*3%4
print "is it true that 3+2<5-7"
print 3+2<5-7
print "is it true 3>2", 3>2
print "what about 3>=2", 3>=2
print "let's try some floating point numbers", 3.0/2
print 3/2.0
print 3/2
print 4.0/2.0
|
965bd10cd352d83d69873f4552aba50845e8ff8b | ltltlt/leetcode | /python/reverse_integer.py | 614 | 3.78125 | 4 | '''''''''''''''''''''''''''''''''''''''''''''''''''
> System: Ubuntu
> Author: ty-l6
> Mail: liuty196888@gmail.com
> File Name: reverse_integer.py
> Created Time: 2017-08-15 Tue 16:03
'''''''''''''''''''''''''''''''''''''''''''''''''''
def reverse(x):
result = 0
x = str(x)
if x[0] == '-':
neg = True
x = x[1:]
else: neg = False
for c in x[::-1]:
result *= 10
result += int(c)
if neg: result = -result
if not (-4294967296/2 < result < 4294967294/2):
return 0
return result
if __name__ == '__main__':
print(reverse(int(input().strip())))
|
56b352a55407ef1a08e6533e71be76c9fb44eb51 | ThrallOtaku/python3Test | /base/day8/str-func/2字符串常见函数(1).py | 657 | 3.984375 | 4 | mystr="hello python2 hello python3"
print(mystr.capitalize())#第一个字符转化为大写
print(mystr)
#mystr.title()
mystr="8888"
for i in range(6,40,2):
for j in range((40-i)//2,0,-1):
print(" ",end="")
print(mystr.center(i,'*'))
'''
center(width, fillchar)
返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
'''
mystr="hello python2 hello python3"
print(mystr.count('python')) #判断字符串出现的次数
print(mystr.count('python',10)) #判断字符串出现的次数,从10个到最后
print(mystr.count('python',10,15)) #判断字符串出现的次数,从10个到15个 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.