blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
e57b2a7e370f849ba15f0bd16c27639cdf209b04 | nzsnapshot/MyTimeLine | /1-2 Months/tutorial/Files/remember_me2.py | 455 | 4.09375 | 4 | import json
# Load username, if it has been stored previously,
# Otherwise, prompt for the username and store it.
filename = 'username2.txt'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input('What is your name? ')
with open(filename,'w') as f:
json.dump(username, f)
print(f"We'll remember your {username} for your return!")
else:
print(f"Welcome back! {username}") |
853ae8c416ba63740724685e4af6f0c47af21ea9 | nzsnapshot/MyTimeLine | /1-2 Months/tutorial/Files/Favourite_number.py | 739 | 3.640625 | 4 | import json
def check_fornumb():
"""File name"""
filename = 'fav_number.json'
try:
with open(filename) as f:
number = json.load(f)
except FileNotFoundError:
return None
else:
return number
def fav_numb():
filename = 'fav_number.json'
try:
number = int(input('Please enter your favourite number'))
with open(filename, 'w') as f:
json.dump(number, f)
except ValueError:
return None
else:
return number
def print_numb():
number = check_fornumb()
if number:
print(f"I know what your favourite number is: {number}")
else:
number = fav_numb()
print(number)
check_fornumb()
print_numb()
|
5ef341feb669c0cb2b2e0581de7bef9b2a6cdb7f | a44fdd/Begginer-_projects | /my_matplotlib.py | 4,017 | 3.734375 | 4 | import matplotlib.pyplot as plt
'''Temperature graphics'''
# nyc_temp_2000 = [31.3, 37.3, 47.2, 51.0, 63.5, 71.3, 72.3, 72.7, 66.0, 57.0, 45.3, 31.1]
# nyc_temp_2006 = [40.9, 35.7, 43.1, 55.7, 63.1, 71.0, 77.9, 75.8, 66.6, 56.2, 51.9, 43.6]
# nyc_temp_2012 = [37.3, 40.9, 50.9, 54.8, 65.1, 71.0, 78.8, 76.7, 68.8, 58.0, 43.9, 41.5]
# months = range(1,13)
# plt.title("Temprature NYC")
# plt.xlabel("months")
# plt.ylabel("Temperature")
# plt.plot(months,nyc_temp_2000,months,nyc_temp_2006,months,nyc_temp_2012)
# plt.legend([2000,2006,2012])
# plt.axis(ymin = 30)
# plt.axis(xmin = 1)
# plt.show()
'''Graphic'''
# def create_graph():
# x_numbers = [1,2,3]
# y_numbers = [2,4,6]
# plt.plot(x_numbers, y_numbers)
# plt.show()
# if __name__ == "__main__":
# create_graph()
'''Newton Universal Gravitation Law'''
def draw_graph(x,y):
plt.plot(x,y,marker="o")
plt.xlabel("Distance in meters")
plt.ylabel("Gravitational force in newtons")
plt.title("Gravitational force and distance")
plt.show()
# def generate_F_r():
#Range r
# r = range(100,1001,50)
#List that save the values of F
# F = []
'''Constants and values'''
'''Gravity constant'''
# G = 6.674 * (10**-11)
'''Mass'''
# m1 = 0.5
# m2 = 1.5
'''Calculate with the formula and add tho the list'''
# for distance in r:
# N = (G*m1*m2)/(distance**2)
# F.append(N)
# draw_graph(r,F)
# if __name__ == "__main__":
# generate_F_r()
'''Use the data to create two lists in your program and to create a
graph with the time of day on the x-axis and the corresponding temperature
on the y-axis. The graph should tell you how the temperature varies
with the time of day. Try a different city and see how the two cities compare
by plotting both lines on the same graph
'''
#Values
hours = range(10,23,3)# x-axis is determined by the next 12 hours, the will creatde at 11:00 a.m
toluca_tempt = [18,21,21,13,9]
querétaro_tempt = [22,26,27,22,17]
# #Graph
plt.title('Temperature in Toluca and Queretaro')
plt.xlabel('Hours since 11 am')
plt.ylabel('Temperature')
plt.axis(xmin=11)
plt.axis(xmax=23)
plt.axis(ymin=4)
plt.axis(ymax=30)
plt.plot(hours,toluca_tempt,hours,querétaro_tempt)
plt.legend(['Toluca','Queretaro'])
plt.show()
'''
You’ll write a program that creates a bar chart for
easy comparison of weekly expenditures. The program should first ask for
the number of categories for the expenditures and the weekly total expenditure
in each category, and then it should create the bar chart showing
these expenditures.
'''
'''Categories'''
# num_categories = int(input('How categories you want to create?'))
# categories_list = []
# expenditure_list = []
# for i in range(num_categories):
# name_categorie = input('Enter category:')
# categories_list += [name_categorie]
# expenditure = int(input('Expenditure:'))
# expenditure_list += [expenditure]
# plt.title('Expenditure in a month')
# plt.xlabel('Category')
# plt.ylabel('Expend')
# plt.bar(categories_list,expenditure_list)
# plt.show()
'''
Finding the median
'''
# def calculate_median(numbers):
# N = len(numbers)
# numbers.sort()
# # Find the median
# if N % 2 == 0:
# # if N is even
# m1 = N/2
# m2 = (N/2) + 1
# # Convert to integer, match position
# m1 = int(m1) - 1
# m2 = int(m2) - 1
# median = (numbers[m1] + numbers[m2])/2
# else:
# m = (N+1)/2
# # Convert to integer, match position
# m = int(m) - 1
# median = numbers[m]
# return median
# if __name__ == '__main__':
# donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
# median = calculate_median(donations)
# N = len(donations)
# print('Median donation over the last {0} days is {1}'.format(N, median))
|
6bcde8d63e43875011070ad27b19fd3f90bbec08 | anna2506/nn-limbo | /Task3/anna2506/model.py | 4,262 | 3.640625 | 4 | import numpy as np
from layers import (
FullyConnectedLayer, ReLULayer,
ConvolutionalLayer, MaxPoolingLayer, Flattener,
softmax_with_cross_entropy, l2_regularization
)
class ConvNet:
"""
Implements a very simple conv net
Input -> Conv[3x3] -> Relu -> Maxpool[4x4] ->
Conv[3x3] -> Relu -> MaxPool[4x4] ->
Flatten -> FC -> Softmax
"""
def __init__(self, input_shape, n_output_classes, conv1_channels, conv2_channels):
"""
Initializes the neural network
Arguments:
input_shape, tuple of 3 ints - image_width, image_height, n_channels
Will be equal to (32, 32, 3)
n_output_classes, int - number of classes to predict
conv1_channels, int - number of filters in the 1st conv layer
conv2_channels, int - number of filters in the 2nd conv layer
"""
image_width, image_height, n_channels = input_shape
self.conv_1 = ConvolutionalLayer(n_channels, conv1_channels, 3, 1)
self.relu_1 = ReLULayer()
self.max_pool_1 = MaxPoolingLayer(4, 4)
self.conv_2 = ConvolutionalLayer(conv1_channels, conv2_channels, 3, 1)
self.relu_2 = ReLULayer()
self.max_pool_2 = MaxPoolingLayer(4, 4)
self.flatten = Flattener()
self.fully_connected = FullyConnectedLayer(4 * conv2_channels, n_output_classes)
def compute_loss_and_gradients(self, X, y):
"""
Computes total loss and updates parameter gradients
on a batch of training examples
Arguments:
X, np array (batch_size, height, width, input_features) - input data
y, np array of int (batch_size) - classes
"""
# Before running forward and backward pass through the model,
# clear parameter gradients aggregated from the previous pass
# TODO Compute loss and fill param gradients
# Don't worry about implementing L2 regularization, we will not
# need it in this assignment
params = self.params()
params['Wconv1'].grad = np.zeros_like(params['Wconv1'].value)
params['Wconv2'].grad = np.zeros_like(params['Wconv2'].value)
params['Wfc'].grad = np.zeros_like(params['Wfc'].value)
params['Bconv1'].grad = np.zeros_like(params['Bconv1'].value)
params['Bconv2'].grad = np.zeros_like(params['Bconv2'].value)
params['Bfc'].grad = np.zeros_like(params['Bfc'].value)
res1 = self.conv_1.forward(X)
res2 = self.relu_1.forward(res1)
res3 = self.max_pool_1.forward(res2)
res4 = self.conv_2.forward(res3)
res5 = self.relu_2.forward(res4)
res6 = self.max_pool_2.forward(res5)
res7 = self.flatten.forward(res6)
res8 = self.fully_connected.forward(res7)
loss, d_preds = softmax_with_cross_entropy(res8, y)
dres1 = self.fully_connected.backward(d_preds)
dres2 = self.flatten.backward(dres1)
dres3 = self.max_pool_2.backward(dres2)
dres4 = self.relu_2.backward(dres3)
dres5 = self.conv_2.backward(dres4)
dres6 = self.max_pool_1.backward(dres5)
dres7 = self.relu_1.backward(dres6)
dres8 = self.conv_1.backward(dres7)
return loss
def predict(self, X):
# You can probably copy the code from previous assignment
pred = np.zeros(X.shape[0], np.int)
res1 = self.conv_1.forward(X)
res2 = self.relu_1.forward(res1)
res3 = self.max_pool_1.forward(res2)
res4 = self.conv_2.forward(res3)
res5 = self.relu_2.forward(res4)
res6 = self.max_pool_2.forward(res5)
res7 = self.flatten.forward(res6)
res8 = self.fully_connected.forward(res7)
pred = np.argmax(res8, axis = 1)
return pred
def params(self):
result = {}
# TODO: Aggregate all the params from all the layers
# which have parameters
result['Wconv1'] = self.conv_1.W
result['Wconv2'] = self.conv_2.W
result['Wfc'] = self.fully_connected.W
result['Bconv1'] = self.conv_1.B
result['Bconv2'] = self.conv_2.B
result['Bfc'] = self.fully_connected.B
return result
|
20f0b3f6a835c4038b9accf1be833849ccb76019 | anna2506/nn-limbo | /Task3/SkymeFactor/model.py | 3,990 | 3.609375 | 4 | import numpy as np
from layers import (
FullyConnectedLayer, ReLULayer,
ConvolutionalLayer, MaxPoolingLayer, Flattener,
softmax_with_cross_entropy, l2_regularization
)
class ConvNet:
"""
Implements a very simple conv net
Input -> Conv[3x3] -> Relu -> Maxpool[4x4] ->
Conv[3x3] -> Relu -> MaxPool[4x4] ->
Flatten -> FC -> Softmax
"""
def __init__(self, input_shape, n_output_classes, conv1_channels, conv2_channels):
"""
Initializes the neural network
Arguments:
input_shape, tuple of 3 ints - image_width, image_height, n_channels
Will be equal to (32, 32, 3)
n_output_classes, int - number of classes to predict
conv1_channels, int - number of filters in the 1st conv layer
conv2_channels, int - number of filters in the 2nd conv layer
"""
# TODO Create necessary layers
#raise Exception("Not implemented!")
self.l_conv1 = ConvolutionalLayer(input_shape[2], conv1_channels, 3, 1)
self.l_Relu1 = ReLULayer()
self.l_MxPl1 = MaxPoolingLayer(4, 4)
self.l_conv2 = ConvolutionalLayer(conv1_channels, conv2_channels, 3, 1)
self.l_Relu2 = ReLULayer()
self.l_MxPl2 = MaxPoolingLayer(4, 4)
self.l_flat = Flattener()
self.l_FC = FullyConnectedLayer(4 * conv2_channels, n_output_classes)
def compute_loss_and_gradients(self, X, y):
"""
Computes total loss and updates parameter gradients
on a batch of training examples
Arguments:
X, np array (batch_size, height, width, input_features) - input data
y, np array of int (batch_size) - classes
"""
# Before running forward and backward pass through the model,
# clear parameter gradients aggregated from the previous pass
for param in self.params().values():
param.grad = np.zeros_like(param.value)
# TODO Compute loss and fill param gradients
# Don't worry about implementing L2 regularization, we will not
# need it in this assignment
#raise Exception("Not implemented!")
pred = self.l_conv1.forward(X)
pred = self.l_Relu1.forward(pred)
pred = self.l_MxPl1.forward(pred)
pred = self.l_conv2.forward(pred)
pred = self.l_Relu2.forward(pred)
pred = self.l_MxPl2.forward(pred)
pred = self.l_flat.forward(pred)
pred = self.l_FC.forward(pred)
loss, loss_grad = softmax_with_cross_entropy(pred, y)
grad = self.l_FC.backward(loss_grad)
grad = self.l_flat.backward(grad)
grad = self.l_MxPl2.backward(grad)
grad = self.l_Relu2.backward(grad)
grad = self.l_conv2.backward(grad)
grad = self.l_MxPl1.backward(grad)
grad = self.l_Relu1.backward(grad)
grad = self.l_conv1.backward(grad)
return loss
def predict(self, X):
# You can probably copy the code from previous assignment
#raise Exception("Not implemented!")
pred = self.l_conv1.forward(X)
pred = self.l_Relu1.forward(pred)
pred = self.l_MxPl1.forward(pred)
pred = self.l_conv2.forward(pred)
pred = self.l_Relu2.forward(pred)
pred = self.l_MxPl2.forward(pred)
pred = self.l_flat.forward(pred)
pred = self.l_FC.forward(pred)
pred = np.argmax(pred, axis=1)
return pred
def params(self):
result = {}
# TODO: Aggregate all the params from all the layers
# which have parameters
#raise Exception("Not implemented!")
result['Conv1W'] = self.l_conv1.params()['W']
result['Conv2W'] = self.l_conv2.params()['W']
result['FC_W'] = self.l_FC.params()['W']
result['Conv1B'] = self.l_conv1.params()['B']
result['Conv2B'] = self.l_conv2.params()['B']
result['FC_B'] = self.l_FC.params()['B']
return result
|
1ab6d1a35e9e898431e2a6bd1563579a4c8df14f | sundaygeek/book-python-data-minning | /code/4/4-3.py | 823 | 3.578125 | 4 | # -*- coding:utf-8 -*-
# 自定义类2
class Charmander:
def __init__(self,name,gender,level):
self.type = ('fire',None)
self.gender = gender
self.name = name
self.level = level
self.status = [10+2*level,5+1*level,5+1*level,5+1*level,5+1*level,5+1*level]
# 最大HP,攻击,防御,特攻,特防,速度
def getName(self):
return self.name
def getGender(self):
return self.gender
def getType(self):
return self.type
def getStatus(self):
return self.status
if __name__ == '__main__':
pokemon1 = Charmander('Bang','male',5)
pokemon2 = Charmander('Loop','female',6)
print(pokemon1.getName(),pokemon1.getGender(),pokemon1.getStatus())
print(pokemon2.getName(),pokemon2.getGender(),pokemon2.getStatus())
|
1c2b046b5f4cab19886ac32c85eced74b54bbdf7 | sundaygeek/book-python-data-minning | /code/4/4-5.py | 2,106 | 3.921875 | 4 | # -*- coding:utf-8 -*-
print('''自定义类5''')
class pokemon:
def __init__(self,name,gender,level,type,status):
self.__type = type
self.__gender = gender
self.__name = name
self.__level = level
self.__status = status
self.__info = [self.__name,self.__type,self.__gender,self.__level,self.__status]
self.__index = -1
def getName(self):
return self.__name
def getGender(self):
return self.__gender
def getType(self):
return self.__type
def getStatus(self):
return self.__status
def level_up(self):
self.__status = [s+1 for s in self.__status]
self.__status[0]+=1 # HP每级增加2点,其余1点
def __iter__(self):
print('名字 属性 性别 等级 能力')
return self
def __next__(self):
if self.__index ==len(self.__info)-1:
raise StopIteration
self.__index += 1
return self.__info[self.__index]
class Charmander(pokemon):
def __init__(self,name,gender,level):
self.__type = ('fire',None)
self.__gender = gender
self.__name = name
self.__level = level
# 最大HP,攻击,防御,特攻,特防,速度
self.__status = [10+2*level,5+1*level,5+1*level,5+1*level,5+1*level,5+1*level]
pokemon.__init__(self,self.__name,self.__gender,self.__level,self.__type,self.__status)
pokemon1 = Charmander('Bang','male',5)
print(pokemon1.getGender())
for info in pokemon1: # 输出对象全部信息
print(info, end=' ')
print('-'*70)
print('''私有成员无法继承''')
class animal:
def __init__(self,age):
self.__age = age
def print2(self):
print(self.__age)
class dog(animal):
def __init__(self,age):
animal.__init__(self,age)
def print2(self):
print(self.__age)
a_animal = animal(10)
a_animal.print2()
# result: 10
a_dog = dog(10)
a_dog.print2()
# 程序报错,AttributeError: dog instance has no attribute '_dog__age'
# 如果把self.__age改为self.age,则程序可通过
|
7da73a6879390b306e1040bcbb5b1c2d5a8dd1ba | sundaygeek/book-python-data-minning | /code/2/2-4-5.py | 180 | 3.671875 | 4 | # -*- coding:utf-8 -*-
print('''创建集合''')
set1 = {1,2,3} # 直接创建集合
set2 = set([2,3,4]) # set()创建
print(set1,set2)
# result: set([1, 2, 3]) set([2, 3, 4])
|
77ab370c4da7b6f592355efbd2c7f4b0f058fd40 | anisssoudki/intro-to-python | /tip-calculator.py | 405 | 4.09375 | 4 | print('welcome to the tip calculator')
totalBill = input('what was the total bill? $')
numOfPeople = input('how many people to split the bill?')
tipPercentage = input('what percentage tip would you like to give? 10, 12 or 15?')
result = (float(totalBill) / float(numOfPeople))+ float(totalBill)/float(numOfPeople)*(float(tipPercentage)/100.00)
print("You're Total bill is " + str(round(result, 2)))
|
cd0d6e283e5344733864d6eb79113d6552e02d5f | AlpacaMoon/python_practices | /Check_if_Sudoku_is_valid_1.0.py | 1,323 | 3.921875 | 4 |
sudoku = ['', '', '', '', '', '', '', '', '']
for i in range(len(sudoku)):
sudoku[i] = input("Enter row " + str(i + 1) + ':')
def validSudoku(sudoku):
#Check for rows
for row in sudoku:
if ''.join(sorted(row)) != '123456789':
print('a')
return False
#Check for columns
for i in range(9):
substr = ''
for row in sudoku:
substr += row[i]
if ''.join(sorted(row)) != '123456789':
print('b')
return False
#Check for 3x3
for i in range(3):
for j in range(3):
substr = ''
for k in range(3):
substr += sudoku[(i*3) + k][(j*3) : (j*3)+3]
if ''.join(sorted(row)) != '123456789':
print('c')
return False
return True
print(validSudoku(sudoku))
# sudoku[0][0:3] + sudoku[1][0:3] + sudoku[2][0:3]
# sudoku[0][3:6] + sudoku[1][3:6] + sudoku[2][3:6]
# sudoku[0][6:9] + sudoku[1][6:9] + sudoku[2][6:9]
# sudoku[3][0:3] + sudoku[4][0:3] + sudoku[5][0:3]
# sudoku[3][3:6] + sudoku[4][3:6] + sudoku[5][3:6]
# sudoku[3][6:9] + sudoku[4][6:9] + sudoku[5][6:9]
# sudoku[6][0:3] + sudoku[7][0:3] + sudoku[8][0:3]
# sudoku[6][3:6] + sudoku[7][3:6] + sudoku[8][3:6]
# sudoku[6][6:9] + sudoku[7][6:9] + sudoku[8][6:9] |
05ff1135c9e3ce6ac64f4d8fbf1abf7dad730253 | NatalijaGucevska/DataVisualization | /Project_k/server/flask/helper/timer.py | 336 | 3.59375 | 4 | import threading
def set_interval(func, sec):
"""Automatic function caller.
Keyword arguments:
func -- the function to call repeatedly
sec -- time interval to call func
"""
def func_wrapper():
set_interval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start()
return t
|
227bfbed621544f32bbddd18299c8fd0ea29fe0a | daisy-carolin/pyquiz | /python_test.py | 989 | 4.125 | 4 | x = [100,110,120,130,140,150]
multiplied_list=[element*5 for element in x]
print(multiplied_list)
def divisible_by_three():
x=range(10,100)
for y in x:
if y%3==0:
print(y)
x = [[1,2],[3,4],[5,6]],
flat_list = []
for sublist in x:
for num in sublist:
flat_list.append(num)
print(flat_list)
def smallest():
list1=[2,7,3,9,10]
list1.sort()
print("Smallest element is:",(list1))
def mylist():
x = ['a','b','a','e','d','b','c','e','f','g','h']
mylist = list(dict.fromkeys(mylist))
print(mylist)
def divisible_by_seven():
x=range(100,200)
for y in x:
if y%7==0:
print(y)
def Students():
year_of_birth=2021-"age"
for student in Students:
[{"age": 19, "name": "Eunice"},
{"age": 21, "name": "Agnes"},
{"age": 18, "name": "Teresa"},
{"age": 22, "name": "Asha"} ]
print("Hello {} you were born in year {}".format("name","year"))
|
439358dd20567d8743de84ec3935031ac4e76d3c | surya810/Numerical-method-notes | /Numerical method_practical_problems/Taylor.py | 716 | 3.890625 | 4 | #Taylor Series (Upto 3rd Order Derivative)
#Name: Rejoy Chakraborty
#Sem: V Subject: Computer Science
#Subject: Numerical Methods (DSE-I)
#Roll No: 717
import math as m
def func_d1(x,y):
return x+y+(x*y)
def func_d2(x,y):
return ((1+x)*func_d1(x,y)) + y + 1
def func_d3(x,y):
return ((x+1)*func_d2(x,y)) + (2*func_d1(x,y))
def main():
x0 = float(input("Enter x_0: "))
y0 = float(input("Enter y_0 i.e y(x_0): "))
xn = float(input("Enter estimating point x_n: "))
yn = y0 + ((xn - x0)*func_d1(x0,y0)) + ((((xn - x0)**2)*func_d2(x0,y0))/m.factorial(2)) + ((((xn - x0)**3)*func_d3(x0,y0))/m.factorial(3))
print("\ny(",xn,"): ", yn)
if __name__ == '__main__':
main()
|
941420c2b36b1491d5e8671ddf462160f80b6841 | dbuscaglia/leetcode_practice | /reverse_integer.py | 686 | 3.828125 | 4 | """
7. Reverse Integer
Easy
2476
3842
Favorite
Share
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = str(x)
if x < 0:
s = s[1:]
b = ''.join(reversed(s))
b = "-"+b
else:
b = ''.join(reversed(s))
r = int(b)
if r > 2147483647 or r < -2147483648:
return 0
return r
assert Solution().reverse(-123) == -321
assert Solution().reverse(1234) == 4321
|
8e72d35419e25bfe11fd1d554927346ccf405a7c | tlholo34/Projects- | /task_manager.py | 12,846 | 4.15625 | 4 | import datetime
from datetime import date
#we open our users.txt
file1 = open('user.txt','r')
users = {}
#for all the lines in users.txt
for lines in file1:
#we strip the new line
lines = lines.strip('\n')
#make a list of all the items in the file
userls = lines.split(', ')
#add items into the dictionary
users[userls[0]] = userls[1]
#ask the user to enter a name
user_name1 = input("enter your User name here: ")
#while the answer is not in the users dictionary
while not user_name1 in users:
#we print this statment
print("This is an invalid user name")
#and ask for the users user name
user_name1 = input("enter your User name here: ")
#here we get the value of the user name they used
x = users.get(user_name1)
#we ask the user to give us the password
password = input("enter your password here: ")
#while the password is not equal to the value of the user name
while password != x:
#we print this
print("this is an invalid password.")
#and ask the user to enter a password
password = input("enter your password here: ")
file1.close()
def task_overview():
file1 = open('tasks.txt','r')
number_of_tasks = 0
completed_tasks = 0
uncomplete_task = 0
over_dueTask = 0
current_date = date.today()
#for item in file1
for i in file1:
#we increment the number of tasks
number_of_tasks += 1
i = i.strip('\n')
#make a list of all the lines in the file
taskls = i.split(', ')
#convert the date in the list bake to a date format
date_object = datetime.datetime.strptime(taskls[3], '%d %b %Y').date()
#if the task is completed
if taskls[-1].upper() == "YES":
# we increment the number of tasks
completed_tasks += 1
else:
#otherwise we increament the number of uncomplete tasks
uncomplete_task += 1
# if the task is uncomplete
if taskls[-1].upper() =="NO":
#if the the task is over due
if date_object < current_date:
#we increment the over_due tasks
over_dueTask += 1
#we calculate the percantage here
total_per = uncomplete_task/number_of_tasks*100
total_over = over_dueTask/number_of_tasks*100
#we write the output here
file3 = open('task_overview.txt','w')
file3.write("the number of tasks: "+str(number_of_tasks)+'\n'+
"Number of completed tasks: "+str(completed_tasks)+'\n'+
'Number of incomplete tasks: '+str(uncomplete_task)+'\n'+
"Number of over due tasks: "+str(over_dueTask)+
"\n"+str(round(total_per,2))+"%"+" of the work are uncomplete"
+"\n"+str(round(total_over,2))+"%"+" of the work are over due")
file1.close()
def user_overview(user_name):
file1 = open('tasks.txt','r')
file2 = open('user.txt','r')
total_users = 0
#for all the users in file2(user.txt)
for i in file2:
#we increment the total users
total_users += 1
number_of_tasks = 0
total_tasks = 0
uncomplete_tasks = 0
current_date = date.today()
over_dueTask = 0
completed_tasks = 0
#for items in file1 (tasks.txt)
for i in file1:
i = i.strip('\n')
#make a list of all the items
taskls = i.split(', ')
#we increment the number of total_tasks
total_tasks += 1
#we convert the string date back to the date format
date_object = datetime.datetime.strptime(taskls[3], '%d %b %Y').date()
#if the user name is the same as the one in file
if user_name.upper() == taskls[0].upper():
#we increment the number of tasks for the user
number_of_tasks += 1
# if the users task is not complete
if taskls[-1].upper() == "NO":
#we increment the the uncomplete tasks
uncomplete_tasks += 1
#if the task is over due
if date_object < current_date:
#we increment the overs due tasks
over_dueTask += 1
else:
#otherwise we increment the completed tasks
completed_tasks += 1
#we calculating the percentage here
user_task=number_of_tasks/total_tasks*100
uncom_per = 0.0
over_per = 0.0
over_per = 0.0
#this only runs when the number of tasks are 0
if number_of_tasks > 0:
com_per = completed_tasks/number_of_tasks*100
uncom_per = uncomplete_tasks/number_of_tasks*100
#this only runs when the number of uncompleted tasks are 0
if uncomplete_tasks > 0:
over_per = over_dueTask/uncomplete_tasks*100
file1.close()
file2.close()
#we return the output here
return ("\n==============="+"\nDetails for username: "+ user_name +
"\nYour total number of tasks: "+str(number_of_tasks)+
"\n"+str(round(user_task,2))+"%"+" of the tasks are assigned to you"+
"\n"+str(round(com_per,2))+"%"+" of your work has been completed."+
"\n"+str(round(uncom_per,2))+"%"+" of your work still needs to be completed."+
"\n"+str(round(over_per,2))+"%"+" of your work is overdue and uncomplete.\n")
def gerate_reports():
file1 = open('tasks.txt','r')
file2 = open('user.txt','r')
total_users = 0
#for all the users in file2(user.txt)
for i in file2:
i = i.split()
#we increment the total users
total_users += 1
total_tasks = 0
for i in file1:
#we increment the number of total tasks
total_tasks += 1
file1.close()
file2.close()
file3 = open('user_overview.txt','w')
usoverview = ""
for key in users.keys():
#we add to the empty string
usoverview += user_overview(key)
#we write the output into the file here
file3.write("total number of users: "+str(total_users)+
"\ntotal number of tasks: "+str(total_tasks)+ usoverview)
task_overview()
def reg_user():
file1 = open('user.txt','r+')
#we ask the admin to enter a new user name
user_name1 = input("enter your new user name here: ")
#while user name is not in dictionary user
while user_name1 in users:
#we print this
print("this user already exists!")
#we ask the user to enter a new user name
user_name1 = input("enter a new user name here: ")
#we ask the admin to enter a password
password = input ("enter your new password here: ")
#we ask admin to enter the password again
re_enter = input("re-enter your password here: ")
#while the password is not the same as the first password
while re_enter != password:
#we print this
print("your passwords dont match.")
#and ask the admin to re-enter the password
re_enter = input("re-enter password here.")
file1.read()
#we write the new user name and password into the user.txt
file1.write('\n'+user_name1+", "+password)
file1.close()
print("done!")
def add_task():
#we ask for the user name that the task is assigned to
user_name1 = input("Enter your user name the task is assigned to: ")
#we ask for the title of the task
title_task = input("Enter the title of the task: ")
#we ask for the description of the task
description = input("Enter the description of the task here: ")
#we ask for the due date
due_date = input("Enter the due date of the task here eg.30 Jul 2020: ")
#we assign todays date to d
d =datetime.datetime.today().__format__("%d %b %Y")
#we assign end_date to no
end_date = 'No'
file1 = open('tasks.txt','r+')
file1.read()
#we write all the information into the tasks.txt file
file1.write('\n'+user_name1+', '+title_task+', '+description+', '+due_date+', '+str(d)+', '+end_date)
file1.close()
print('done!')
def view_all():
file1 = open('tasks.txt','r')
#for items in taske.txt
for i in file1:
#we split all the items
taskls = i.split(', ')
#we print all the information in this format
print("User name: "+taskls[0]+"\n"
+"Title of the task: "+taskls[1]+"\n"
+"Due date: "+taskls[3]+"\n"
+"Date assigned: "+taskls[4]+"\n"
+"Task complete?: "+taskls[5]
+"Description of the task: "+taskls[2]+"\n")
file1.close()
def veiw_mine():
file1 = open('tasks.txt','r')
count = 0
all_tasks = []
#for all the items in task.txt
for i in file1:
#we split the information
taskls = i.split(', ')
#we add it to a file which will hold all the taks
all_tasks.append(taskls)
#if the user name is equel to the user name of the list
if user_name1 == taskls[0]:
#we print the information form the list in this format
print("\n"+str(count)+" - Title of the task: "+taskls[1])
count = count + 1
while True:
print("enter -1 to exit.")
#we ask the user which task they would like to edit
option2 = int(input("which task would you like to edit: "))
if option2 <= count and option2 >= 0:
#we ask the user what they would like to do
option3 = input("s - mark as complete\n"+
"c - change the user name the task is assigned to\n"+
"d - change the due date of the task\n"+
"here -->")
#we assign the users option to usersOP
userOp = all_tasks[option2]
#if the user enters s
if option3 == 's':
#if the task is complete
if userOp[-1].upper() == "YES\n":
#we print this
print("this task has alredy been completed")
else:
#else we replace the no to yes
userOp[-1] = "Yes\n"
print("Done!")
#if the user enters c
if option3 == 'c':
#we ask the user to enter the user name
new_user = input("enter user name here: ")
#while the user is not in the task
while not new_user in users:
#we print this
print("this user does not exist!")
#we ask the user to enter a user name
new_user = input("enter user name here: ")
#we replace the the user in the list with the new user the admin has added
userOp[0] = new_user
print("Done!")
#if the user enters d
if option3 == 'd':
#we ask the user to enter a new date in this format
new_date = input("Enter the new due date e.g 23 Apr 2020: ")
userOp[3] = new_date
# we print this
print("Done! your new date is now: "+str(new_date))
all_tasks[option2] = userOp
#if the option is -1 we exit the loop
elif option2 == -1:
break
#else we print this
else:
print ("This is an invalid option.")
file2= open('tasks.txt','w')
file2.flush()
#we write into the file
for i in all_tasks:
file2.write(", ".join(i))
file2.close()
file1.close()
def displayStats():
gerate_reports()
file1 = open('task_overview.txt','r')
file2 = open('user_overview.txt','r')
#we print each line
for i in file1:
print(i)
for i in file2:
print(i)
file1.close()
file2.close()
while True:
#if the user name is admin
if user_name1 == 'admin':
#we show them this menu
options = str(input("Please enter one of the following options:\n"+
"a - add task\n"+
"r - register user\n"+
"va- veiw all tasks\n"+
"vm- veiw my tasks\n"+
"gr- generate reports\n"+
"ds- display stastistics\n"+
"e - exit\n"+
"here--> "))
else:
#else we show them this menu
options = str(input("please enter one of the following options: \n"+
"a - add task\n"+
"va- veiw all tasks\n"+
"vm- veiw my tasks\n"+
"e - exit\n"
"here--> "))
#if user/admin enters vm
if options == 'vm':
veiw_mine()
#if user/admin enters va
if options == 'va':
view_all()
#if user/admin enters a
if options == 'a':
add_task()
#if the admin enters r from the menu
if options == 'r':
reg_user()
#if the admin enters ds
if options == 'ds':
displayStats()
#if the admin enters gr
if options == 'gr':
gerate_reports()
#if the admin/user enters e
if options == 'e':
break
|
996da01a75f050ffcdb755c5c5f2b16fb1ec8f1c | Shmuco/PY4E | /PY4E/ex_05_02/ex_05_02.py | 839 | 4.15625 | 4 | ##### 5.2 Write a program that repeatedly prompts a user for integer numbers until
#the user enters 'done'. Once 'done' is entered, print out the largest and
#smallest of the numbers. If the user enters anything other than a valid number
#catch it with a try/except and put out an appropriate message and ignore the
#number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
fnum =float(num)
except:
print ("Invalid input")
continue
if largest is None:
largest = fnum
elif fnum > largest:
largest = fnum
if smallest is None:
smallest = fnum
elif smallest > fnum:
smallest = fnum
print("Maximum", largest, "Minumum", smallest)
|
d5e151283d98121eeeadb57157acab2355ad3afa | bmbueno/pesquisa | /tratamento dados.py | 4,104 | 3.90625 | 4 | import csv
import sqlite3
with open('Pesquisa500.csv') as file:
fileReader = csv.reader(file, delimiter=',')
dbConec = sqlite3.connect("pesquisa500.db")
db = dbConec.cursor()
# db.execute('CREATE TABLE perfilSocioEconomico( id INTEGER PRIMARY KEY AUTOINCREMENT, resposta VARCHAR(100) NOT NULL);')
# db.execute("""INSERT INTO perfilSocioEconomico (resposta) VALUES ('De R$ 522,50 a R$ 1045,00;');""")
# db.execute("""INSERT INTO perfilSocioEconomico (resposta) VALUES ('Ate R$ 522,50;');""")
# db.execute("""INSERT INTO perfilSocioEconomico (resposta) VALUES ('De R$ 1045,00 a R$ 3135,00;');""")
# db.execute("""INSERT INTO perfilSocioEconomico (resposta) VALUES ('Acima de R$ 3135,00;');""")
db.execute('CREATE TABLE questao( id INTEGER PRIMARY KEY AUTOINCREMENT, descricao VARCHAR(100) );')
db.execute('CREATE TABLE entrevistado(id INTEGER PRIMARY KEY AUTOINCREMENT, data VARCHAR(100) NOT NULL, idade INTEGER NOT NULL, ocupacao VARCHAR(100) NOT NULL, trabalhoEssencial VARCHAR(3) NOT NULL, perfilSocioEconomico VARCHAR(50) NOT NULL);')
#db.execute('CREATE TABLE entrevistado(id INTEGER PRIMARY KEY AUTOINCREMENT, data VARCHAR(100) NOT NULL, idade VARCHAR(2) NOT NULL, ocupacao VARCHAR(100) NOT NULL, trabalhoEssencial VARCHAR(3) NOT NULL, perfilSocioEconomicoID INTEGER, FOREIGN KEY (perfilSocioEconomicoID) REFERENCES perfilSocioEconomico(id));')
db.execute('CREATE TABLE resposta(id INTEGER PRIMARY KEY AUTOINCREMENT, questaoID INTEGER, entrevistadoID INTEGER, resposta VARCHAR(100) NOT NULL, FOREIGN KEY (questaoID) REFERENCES questao(id), FOREIGN KEY (entrevistadoID) REFERENCES entrevistado(id));')
db.execute("""INSERT INTO questao (descricao) VALUES ('Qual sua idade?');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('Qual o seu meio principal de informação?');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('Como está sua rotina? ');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('Tem usado quais utensílios de prevenção indicados contra o coronavírus?');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('É a favor do isolamento social para contenção do vírus ? ');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('Como você está se sentindo neste momento de pandemia?');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('Qual(is) sua(s) ocupação(ões)? ');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('É/São em um serviço considerado essencial?');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('Qual sua renda mensal per capita antes da pandemia do Coronavírus?');""")
db.execute("""INSERT INTO questao (descricao) VALUES ('Você teve a redução desta renda durante a pandemia? ');""")
dbConec.commit()
print( db.lastrowid)
next(fileReader)
for row in fileReader:
try:
int(row[1]) # para validacao da idade
db.execute("""INSERT INTO entrevistado (data, idade, ocupacao, trabalhoEssencial, perfilSocioEconomico) VALUES (?,?,?,?,?);""", (row[0], row[1], row[7], row[8], row[9]))
idEntrevistado = db.lastrowid
db.execute("""INSERT INTO resposta (questaoID, entrevistadoID, resposta) VALUES (?,?,?);""", (2, idEntrevistado, row[2]))
db.execute("""INSERT INTO resposta (questaoID, entrevistadoID, resposta) VALUES (?,?,?);""", (3, idEntrevistado, row[3]))
db.execute("""INSERT INTO resposta (questaoID, entrevistadoID, resposta) VALUES (?,?,?);""", (4, idEntrevistado, row[4]))
db.execute("""INSERT INTO resposta (questaoID, entrevistadoID, resposta) VALUES (?,?,?);""", (5, idEntrevistado, row[5]))
db.execute("""INSERT INTO resposta (questaoID, entrevistadoID, resposta) VALUES (?,?,?);""", (6, idEntrevistado, row[6]))
db.execute("""INSERT INTO resposta (questaoID, entrevistadoID, resposta) VALUES (?,?,?);""", (10, idEntrevistado, row[10]))
dbConec.commit()
except:
continue
dbConec.close()
|
48f85e68fcdd06ca468437c536ac7e27fd20ef77 | endreujhelyi/zerda-exam-python | /first.py | 431 | 4.28125 | 4 | # Create a function that takes a list as a parameter,
# and returns a new list with every second element from the original list.
# It should raise an error if the parameter is not a list.
# Example: with the input [1, 2, 3, 4, 5] it should return [2, 4].
def even_elements(input_list):
if type(input_list) == list:
return [input_list[i] for i in range(len(input_list)) if i % 2 == 1]
else:
raise TypeError
|
d23251d361e76538cdac028a51835bf691414163 | mallegrini/katas | /tests/test_fizzbuzz.py | 717 | 3.640625 | 4 | import unittest
from src.fizzbuzz import FizzBuzzer, Checker
class FizzBuzzerTest(unittest.TestCase):
def setUp(self):
self.m = FizzBuzzer((Checker(3, 'Fizz'), Checker(5, 'Buzz'), Checker(7, 'Bang')))
def test_one_two(self):
assert self.m.say(1) == "1"
assert self.m.say(2) == "2"
def test_fizz(self):
assert self.m.say(3) == "Fizz"
assert self.m.say(9) == "Fizz"
def test_buzz(self):
assert self.m.say(5) == "Buzz"
assert self.m.say(10) == "Buzz"
def test_fizzbuzz(self):
assert self.m.say(15) == "FizzBuzz"
assert self.m.say(30) == "FizzBuzz"
def test_buzz(self):
assert self.m.say(21) == "FizzBang"
assert self.m.say(35) == "BuzzBang"
assert self.m.say(21*5) == 'FizzBuzzBang'
|
fed2d8b58677306755301073a22e88088f9ce6de | Matthew-Inman/calculator-pygame | /dist/pygame_calculator.app/Contents/Resources/Screen.py | 3,707 | 3.515625 | 4 | import pygame
import math
from Calculator import Calculator
from globals import *
class Screen:
init_text = '0'
error = False
def __init__(self):
self.text = '0'
self.x = 100
self.y = 80
self.width = 390
self.height = 80
self.calc = Calculator()
def draw_screen(self):
pygame.draw.rect(window, screen_color, (self.x, self.y, self.width, self.height))
smallText = pygame.font.Font(font_style, font_size)
textSurf, textRect = text_objects(self.text, smallText)
textRect.center = ( (self.x+(self.width/2)), (self.y+(self.height/2)) )
window.blit(textSurf, textRect)
def update_value(self):
if self.calc.get_button_value() == 'AC':
self.text = self.init_text
return
elif self.text == '0' and self.calc.get_button_value() != None or self.error and self.calc.get_button_value() != None:
if self.error:
self.error = False
self.text = ''
if self.calc.get_button_value() != '=':
if self.calc.get_button_value() != None:
self.text += self.calc.get_button_value()
def print_result(self):
if self.calc.get_button_value() != '=':
return
if 'tan' in self.text:
self.text = self.text.replace('tan', '')
self.text = self.text.replace('(', '')
self.text = self.text.replace(')', '')
try:
self.text = math.tan(eval(self.text))
except TypeError as err:
print(err)
self.text = self.init_text
elif 'cos' in self.text:
self.text = self.text.replace('cos', '')
self.text = self.text.replace('(', '')
self.text = self.text.replace(')', '')
try:
self.text = math.cos(eval(self.text))
except TypeError as err:
print (err)
self.text = self.init_text
elif 'sin' in self.text:
self.text = self.text.replace('sin', '')
self.text = self.text.replace('(', '')
self.text = self.text.replace(')', '')
try:
self.text = math.sin(eval(self.text))
except TypeError as err:
print(err)
self.text = self.init_text
elif '^' in self.text:
try:
integers = self.text.split('^')
self.text = str(math.pow(int(integers[0]), int(integers[1])))
except ValueError as err:
print(err)
self.text = self.init_text
elif '!' in self.text:
try:
if self.text[0] == '!':
self.text = self.text.replace('!', '')
self.text = self.text.replace('(', '')
self.text = self.text.replace(')', '')
self.text = str(math.factorial(int(self.text)))
else:
self.error = True
self.text = 'Use factorial as follows: !(x)'
except ValueError as err:
print(err)
self.text = self.init_text
else:
try:
self.text = eval(self.text)
except ZeroDivisionError as err:
print(err)
self.error = True
self.text = 'You cannot divide a number by 0'
except SyntaxError as err:
print(err)
self.error = True
self.text = 'There was a syntax error'
self.text = str(self.text)
|
6caa36efec61cd233576a4dcb9b3e925ab259fae | briangfang/COGS-18 | /functions.py | 9,522 | 3.8125 | 4 | """Collection of functions used in my project"""
from datetime import date
import pandas as pd
def create_food(food, quant, exp, categ):
"""Creates dictionary of preset keys paired with input parameters
as corresponding values.
Parameters
----------
food : string
String of food name.
quant : integer or float or string
Quantity of food in inventory.
exp : datetime.date
Expiration date of food.
Format is `date(year, month, day)`.
categ : string
String of food category.
Returns
-------
output_dict : dictionary
Dictionary of preset keys paired with input parameters
as corresponding values.
"""
output_dict = {}
# create keys for food information
output_dict['food'] = food
output_dict['quant'] = quant
output_dict['exp'] = exp
output_dict['categ'] = categ
return output_dict
def init_df(food, quant, exp, categ):
"""Creates a dataframe with labeled columns for corresponding
input parameters.
Parameters
----------
food : string
String of food name.
quant : integer or float or string
Quantity of food in inventory.
exp : datetime.date
Expiration date of food.
Format is `date(year, month, day)`.
categ : string
String of food category.
Returns
-------
df : pandas.core.frame.DataFrame
Dataframe with labeled columns for corresponding
input parameters.
"""
# make a df from dict in create_food function
dict_1 = create_food(food, quant, exp, categ)
df = pd.DataFrame([dict_1])
return df
def add_food(df, food, quant, exp, categ):
"""Adds input parameters as a new row to an existing dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe to which the input parameters below are added.
food : string
String of food name.
quant : integer or float or string
Quantity of food in inventory.
exp : datetime.date
Expiration date of food.
Format is `date(year, month, day)`.
categ : string
String of food category.
Returns
-------
df : pandas.core.frame.DataFrame
Input dataframe updated with a new row of other input parameters.
"""
# add to existing df from dict in create_food function
# ignore_index = True parameter continues numerical row indexing
# of input df
df = df.append(create_food(food, quant, exp, categ), ignore_index = True)
return df
def in_inventory(df, food):
"""Checks if input food is in the 'food' column of input dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe in which input food will be searched for.
food : string
String of food name to be searched.
Returns
-------
output : boolean
Returns False if input food not in 'food' column of input dataframe.
Returns True if input food is in 'food' column of input dataframe.
"""
# turns df 'food' column into str and searches for
# input str food in 'food' column
if food not in str(df['food']):
print('Food not found. Inventory unchanged.')
output = False
else:
output = True
return output
def remove_food(df, food):
"""Removes row of input food from input dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe in which input food is to be removed.
food : string
String of food name to be removed.
Returns
-------
output : NoneType or pandas.core.frame.DataFrame
Returns NoneType if input food not in 'food' column of input dataframe.
Otherwise returns input dataframe with input food row removed.
"""
if in_inventory(df, food) == False:
output = None
return output
else:
# turns tuple into list and extracts the
# first element of list which is the number
# of rows in df and stores in var `rows`
rows = list(df.shape)[0]
counter = 0
# loop set to run for the same number of
# times as there are rows in the input df.
# each row is turned into a str and
# searched for a match with input str food.
# a successful match will drop that row
# and reset the row indexing to prevent
# an error in future usage of this function
while counter < rows:
if food in str(df.loc[counter]):
df = df.drop([counter])
df = df.reset_index(drop = True)
break
else:
counter += 1
output = df
return output
def edit_quant(df, food, new_quant):
"""Changes corresponding quantity of input food in input dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe in which input food quantity will be changed.
food : string
String of food name to change quantity.
new_quant : integer or float or string
New quantity of input food to be changed to.
Returns
-------
output : NoneType or pandas.core.frame.DataFrame
Returns NoneType if either input food is not in 'food' column
of input dataframe or new_quant is equal to the existing quantity
stored in the input dataframe. Else returns input dataframe with
updated input food quantity.
"""
if in_inventory(df, food) == False:
output = None
return output
else:
# turns tuple into list and extracts the
# first element of list which is the number
# of rows in df and stores in var `rows`
rows = list(df.shape)[0]
counter = 0
# loop set to run for the same number of
# times as there are rows in the input df.
# each row is turned into a str and
# searched for a match with input str food.
# a successful match will replace the original
# food quantity with the input quantity after
# the original quantity is stored in a var
while counter < rows:
if food in str(df.loc[counter]):
old_quant = df.at[counter, 'quant']
df.at[counter, 'quant'] = new_quant
break
else:
counter += 1
# confirms to user that food quantity has been changed
if new_quant != old_quant:
print(str(food) + ' quantity changed from ' + \
str(old_quant) + ' to ' + str(new_quant) + '.')
output = df
# alerts user input quantity == original quantity so
# the df has not been updated
else:
print('The new ' + food + ' quantity is the' + \
' same as the old one. Inventory unchanged.')
output = None
return output
def is_expired(df, food):
"""Checks if input food in input dataframe is expired.
Also prints out how many days the input food has until
expiration or has been expired accordingly.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe in which input food will be checked for expiration.
food : string
String of food name to be checked for expiration.
Returns
-------
output : NoneType or boolean
Returns NoneType if input food is not in 'food' column
of input dataframe. Else returns boolean. Boolean will
be False if input food expires on or after the current
date. Boolean will be True if input food expires before
current date.
"""
if in_inventory(df, food) == False:
output = None
return output
else:
rows = list(df.shape)[0]
counter = 0
# loop set to run for the same number of
# times as there are rows in the input df.
# each row is turned into a str and
# searched for a match with input str food.
# a successful match will then check if the input
# food has expired and print the appropriate response
while counter < rows:
if food in str(df.loc[counter]):
if df.at[counter, 'exp'] > date.today():
output = False
days_til_exp = df.at[counter, 'exp'] - date.today()
print('This food has not yet expired. It will ' + \
'expire in ' + str(days_til_exp.days) + ' days.')
elif df.at[counter, 'exp'] == date.today():
output = False
print('This food expires today!')
elif df.at[counter, 'exp'] < date.today():
output = True
days_exp = date.today() - df.at[counter, 'exp']
print('This food has expired. It expired ' + \
str(days_exp.days) + ' days ago.')
return output
break
else:
counter += 1 |
c6745d3dde458a86ed000e6877f1291bafe1c489 | alapa/Training | /phonebook.py | 3,321 | 3.65625 | 4 | import pickle
import sys
class PhoneBookError(Exception):
pass
class Contact():
def __init__(self, name, number):
self.name = name
self.number = number
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
"""def __setattr__(self, attrname, value):
if attrname == 'name':
raise AttributeError("Name can't be changed")"""
def __repr__(self):
return "{} - {}".format(self.name,self.number)
class PhoneBook():
def __init__(self):
self._contacts = set()
def __repr__(self):
return '\n'.join(cont.__repr__() for cont in self._contacts)
def load_data(self, file):
with open(file, 'r+b') as phonebook_file:
self._contacts = pickle.load(phonebook_file)._contacts
def enter_contact_info(f):
def wrapper(self, **kwargs):
n = input("Enter name:")
num = input("Enter number:")
res = f(self, Contact(n,num), **kwargs)
return res
return wrapper
def enter_contact_name(f):
def wrapper(self, **kwargs):
n = input("Enter name:")
res = f(self, Contact(n,0), **kwargs)
return res
return wrapper
@enter_contact_info
def add_con(self,cont):
if cont in (self._contacts):
raise PhoneBookError('Contact already exist in phonebook.')
self._contacts.add(cont)
@enter_contact_name
def get_con(self, cont):
for c in self._contacts:
if c == cont:
return c
raise PhoneBookError('Contact not found.')
@enter_contact_info
def upd_con(self, cont):
if cont not in (self._contacts):
raise PhoneBookError('Contact not found.')
self._contacts.add(cont)
@enter_contact_name
def del_con(self, cont):
try:
self._contacts.remove(cont)
except KeyError:
raise PhoneBookError('Contact not found.')
def write_change():
with open(file_name, 'w+b') as phonebook_file:
pickle.dump(book, phonebook_file)
def autosave(f):
def wrapper(**kwargs):
res = f(**kwargs)
write_change()
return res
return wrapper
@autosave
def add_num():
book.add_con()
def search_num():
print(book.get_con())
@autosave
def upd_num():
book.upd_con()
@autosave
def del_num():
book.del_con()
def show_all():
print(book)
def exec_action(action):
actions.get(action, wrong_action)()
def wrong_action():
print("Incorrect action!")
def quit():
sys.exit()
def main_func():
while True:
action = input("Choose action: a, s, u, d, all, q:")
try:
exec_action(action)
except PhoneBookError as e:
print(e)
actions = {'a': add_num, 's': search_num, 'u': upd_num, 'd': del_num, 'all': show_all, 'q': quit}
file_name = 'phonebook.pickle'
book = PhoneBook()
book.load_data(file_name)
main_func()
|
8fe7e9ee5da57e056d279168bc8c34789779109a | cainiaosun/study | /测试/UI自动化/测试工具__Selenium/selenium/Phy/class.py | 1,134 | 4.3125 | 4 | class Person:
'''Represents a person.'''
population = 0
def __init__(self,name,age):
'''Initializes the person's data.'''
self.name = name
self.age = age
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' %Person.population
def sayhi(self):
print "Hi,my name is %s %s"% (self.name,self.age)
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' %Person.population
print Person.population
test1=Person("sunhongbin","28")
test1.sayhi()
test1.howMany()
test2=Person("lihua","30")
test2.sayhi()
test2.howMany()
test1.sayhi()
test1.howMany()
del test1
del test2
|
8d5f5d635bcba612042b6e94c12292f92ecf6630 | Ankita-2331/PythonTurtlePrograms | /Design2.py | 241 | 3.71875 | 4 | import turtle
colors=['red','yellow','blue','green','orange','pink']
screen=turtle.Screen()
t=turtle.Turtle()
t.speed(0)
screen.bgcolor('black')
for x in range(300):
t.pencolor(colors[x%6])
t.width(3)
t.forward(x)
t.left(20)
|
1eaa0f74dbf499832727a4ed3c642cdc20cce795 | DoranLyong/CSE-python-tutorial | /Coding-Test/CodeUp/Python/055_Logical.py | 304 | 3.8125 | 4 | """
[ref] https://codeup.kr/problem.php?id=1055
Question:
1. take two true(1) or false(0)
2. print true when any of them is True at least
"""
import sys
x, y = map(int, sys.stdin.readline().rstrip().split())
x, y = map(bool, [x, y])
OrGate = lambda x, y: x or y
print(int(OrGate(x, y)))
|
3bf12dd6c33cc03a1d21b50ac6758b69a8785db2 | DoranLyong/CSE-python-tutorial | /Coding-Test/CodeUp/Python/029_InputOutput.py | 203 | 3.5 | 4 | """
[ref] https://codeup.kr/problem.php?id=1029
Question:
1. get one real number in range 0 ~ 4,294,967,295
2. print it up to 11 decimal places
"""
data = float(input())
print("%.11f" %data) |
40eb347ec2a99811529a9af3aa536a16618d0ad3 | DoranLyong/CSE-python-tutorial | /Coding-Test/CodeUp/Python/036_number.py | 345 | 4.375 | 4 | """
[ref] https://codeup.kr/problem.php?id=1036
Question:
1. take one English letter
2. print it out as the decimal value of the ASCII code table.
"""
letter = input()
print(ord(letter))
"""
Program to find the ASCII value of a character:
https://beginnersbook.com/2019/03/python-program-to-find-ascii-value-of-a-character/
""" |
b1e4dbd8b361e4a4b91d4f5b1e021e225c5f4cf2 | DoranLyong/CSE-python-tutorial | /Coding-Test/CodeUp/Python/069_if_statement.py | 490 | 3.90625 | 4 | # coding=<utf-8>
"""
[ref] https://codeup.kr/problem.php?id=1069
Question:
1. receive evaluation as letters (A, B, C, D ...)
2. print it as comment
평가 내용
평가 : 내용
A : best!!!
B : good!!
C : run!
D : slowly~
others : what?
"""
eval = input()
comment = {"A":"best!!!", "B":"good!!", "C":"run!", "D":"slowly~"}
if eval in comment.keys():
print("%s" %comment[eval])
else:
print("%s" %"what?") |
cfbda90651469ee446bbb28c69b0d33bedfb980b | DoranLyong/CSE-python-tutorial | /Coding-Test/CodeUp/Python/026_InputOutput.py | 177 | 3.5625 | 4 | """
[ref] https://codeup.kr/problem.php?id=1026
Question:
1. get hour:minute:second
2. print only 'minute' part
"""
h, m, s = input().split(":")
print("%d" %(int(m))) |
be18912e38faf01a46bc0c740a5044d71bbc615d | DoranLyong/CSE-python-tutorial | /Coding-Test/CodeUp/Python/013_InputOutput.py | 179 | 3.65625 | 4 | """
[ref] https://codeup.kr/problem.php?id=1013
Question:
1. get two integers
2. print them
"""
import sys
a, b = map(int, sys.stdin.readline().split())
print(a, b)
|
58dce475f4c94e14c6d58a4ee3c1836e34c82f21 | DoranLyong/CSE-python-tutorial | /Coding-Test/CodeUp/Python/037_number.py | 319 | 4.125 | 4 | """
[ref] https://codeup.kr/problem.php?id=1037
Question:
1. take one decimal ineger
2. print it out in ASCII characters
"""
num = int(input())
print(chr(num))
"""
Program to find the ASCII value of a character:
https://beginnersbook.com/2019/03/python-program-to-find-ascii-value-of-a-character/
""" |
173631da2b89f158a22cde74defe44465acce1b6 | wuhuabushijie/sample | /chapter04/4_1.py | 488 | 4.125 | 4 | '''鸭子类型,多态'''
class Cat:
def say(self):
print("I am a cat")
class Dog:
def say(self):
print("I am a dog")
def __getitem__(self):
return "bob8"
class Duck:
def say(self):
print("I am a duck")
animal_list = [Cat,Dog,Duck]
for animal in animal_list:
animal().say()
a = ["bob1","bob2"]
b = ["bob2","bob3"]
name_tuple=("bob4","bob5")
name_set=set()
name_set.add("bob6")
name_set.add("bob7")
a.extend(name_tuple)
print(a)
|
fd7e0913e3563e7df5bbb860e23d2bc91046a501 | wuhuabushijie/sample | /chapter08/metaclass_test.py | 700 | 3.71875 | 4 | from collections.abc import *
from _collections_abc import __all__
class Base:
def answer(self):
print("This is base class")
def say(self):
print("hello " + self.name)
class MetaClass(type):
def __new__(cls, *args, **kwargs):
print("This is MetaClass")
return super().__new__(cls,*args,**kwargs)
class User2(metaclass=MetaClass):
def __init__(self,name):
self.name = name
def __str__(self):
return "User2"
if __name__ == "__main__":
# type 也可以创建类
User = type("User",(Base,),{"name":"bob","say":say})
user = User()
print(user.name)
user.say()
user.answer()
user2=User2("bob")
print(user2)
|
3c442143a21e9a16b2d595ab0e867791effa2f13 | wuhuabushijie/sample | /chapter07/ags_fault.py | 762 | 3.984375 | 4 | class Company:
def __init__(self, name, staffs=[]):
self.name=name
self.staffs=staffs
def add(self,staff):
self.staffs.append(staff)
com1 = Company("com1")
com2 = Company("com2")
com1.add("bob1")
com2.add("bob2")
print(com1.staffs)
print(com2.staffs)
print(com1.staffs is com2.staffs)
# 不要将函数默认参数设置为可变数据类型
# 如果在调用方法时,不对可变类型的默认参数赋值,那么所有的调用都是用同一个参数,一处更改就会影响到其他调用
def add(a,b=[]):
b.append(a)
return b
c = add(2)
d = add(3)
print(c)
print(d)
# def add(a, b):
# c = a + b
# return c
#
#
# d = [1, 2]
# e = [3, 4]
#
# c1 = add(d, e)
#
# print(c1)
# print(d)
# print(e) |
0c5c047faa0c42dc7471edc4e627718f0e6a444b | pri-nitta/firstProject | /CAP4/funcao.py | 506 | 3.96875 | 4 | def somar():
a = float(input("Digite o primeiro número: "))
b = float(input("Digite o segundo número: "))
print(a + b)
somar()
#Usando parâmetros
def somar2(c, d):
total = c + d
print(total)
v1 = float(input("Digite o 1º num: "))
v2 = float(input("Digite o 2º num: "))
somar2(v1, v2)
#passando diretamente parâmetros na função
somar2(54,96)
#usando return
def soma3(x,y):
total2 = x + y
return (total2)
print("==============================")
print(soma3(159,753)) |
2d77ec4e8a640d28a657fd2dd581c3fe013e7703 | pri-nitta/firstProject | /CAP2/bonus.py | 656 | 3.8125 | 4 | var = input("Qual o tipo da sua assinatura? ")
assinatura = var.upper()
faturamento = float(input("Quanto foi seu faturamento anual? "))
if assinatura == "BASIC":
bonus = faturamento * 0.3
print(f"O valor que deverá ser pago é de R${bonus}")
elif assinatura == "SILVER":
bonus = faturamento * 0.2
print(f"O valor que deverá ser pago é de R${bonus}")
elif assinatura == "GOLD":
bonus = faturamento * 0.1
print(f"O valor que deverá ser pago é de R${bonus}")
elif assinatura == "PLATINUM":
bonus = faturamento * 0.05
print(f"O valor que deverá ser pago é de R${bonus}")
else:
print("Digite um plano válido")
|
4fcabbe7be3110a9ee278b5321eaa30319c9d7a7 | pri-nitta/firstProject | /CAP3/calorias.py | 1,093 | 4.21875 | 4 | #1 – O projeto HealthTrack está tomando forma e podemos pensar em algoritmos que possam ser reaproveitados
# quando estivermos implementando o front e o back do nosso sistema.
# Uma das funções mais procuradas por usuários de aplicativos de saúde é o de controle de calorias ingeridas em um dia.
# Por essa razão, você deve elaborar um algoritmo implementado em Python em que o usuário informe quantos
# alimentos consumiu naquele dia e depois possa informar o número de calorias de cada um dos alimentos.
# Como não estudamos listas nesse capítulo você não deve se preocupar em armazenar todas as calorias digitadas,
# mas deve exibir o total de calorias no final.
alimentos = int(input("Digite quantos alimentos você consumiu hoje: "))
i = 1
total = int(0)
print("==============================================")
while i <= alimentos:
calorias = int(input(f"Digite a quantidade de calorias do {i}º alimento: "))
i = i + 1
total = calorias + total
print("==============================================")
print(f"O total de calorias ingerido hoje é: {total}") |
c5bb97e87faa1dc65fff8faf36b50e4a66f2cc3f | luigirivera/PE4-Sentiment-Classification | /sentiment_classification.py | 9,094 | 3.5625 | 4 | import nltk
import os
import csv
import pandas as pd
nltk.download('punkt')
dataset = pd.read_csv('dataset/Virgin America and US Airways Tweets.csv', sep='\t')
import numpy as np
dataset = np.array(dataset)
sentiments = dataset.T[0]
airline = dataset.T[1]
text = dataset.T[2]
print(sentiments[:5]) #Y in example
print(airline[:5])
print(text[:5]) #X in example
"""# 2. Understanding the Corpus
So now that we've loaded our data and separated the word sense tag (*class label*) from the actual context (*document*), let's look at some statisctics. **Exercise: But as a quick exercise, kindly extract the following information**:
* Number of documents in the dataset
* Number of living_sense labels
* Number of factory_sense labels
* Also calculate the distribution of each class
* Lastly, get the total number of words (no punctuations) for each class (*this one is a little hard*)
"""
# Write your code here! Feel free to search up NumPy tutorials
N = len(sentiments)
labels, counts = np.unique(sentiments, return_counts=True)
negative_indexes, dump = np.where(dataset == 'negative')
positive_indexes, dump = np.where(dataset == 'positive')
neutral_indexes, dump = np.where(dataset == 'neutral')
from nltk import word_tokenize
import string
def count_words(nArray):
punct = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{}~'
transtab = str.maketrans(dict.fromkeys(punct, ''))
word_count = 0
for sentence in nArray:
tokens = word_tokenize(sentence.translate(transtab))
# the translate portion just removed the punctuation
word_count += len(tokens)
return word_count
negative_count = count_words(text[negative_indexes])
positive_count = count_words(text[positive_indexes])
neutral_count = count_words(text[neutral_indexes])
print("Total document count: %s" % N)
for label, count, word_count in zip(labels, counts, [negative_count, positive_count, neutral_count]):
print("%s: %s (%.4f); Word count: %s (%.4f)" % (label, count, count/N, word_count, word_count/np.sum([negative_count, positive_count, neutral_count])))
punct = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{}~'
transtab = str.maketrans(dict.fromkeys(punct, ''))
print(text[6])
i = 0
while i < len(text):
text[i] = text[i].translate(transtab)
i += 1
print(text[6])
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(
text, # Features
sentiments, # Labels
test_size = 0.3, # The defined test size; Training size is just 1 minus the test size
random_state = 17 # So we can shuffle the elements, but with some consistency
)
print("=====\nTraining Data")
print("Document count: %s" % len(Y_train))
labels, counts = np.unique(Y_train, return_counts=True)
for label, count in zip(labels, counts):
print("%s: %s (%.4f)" % (label, count, count/len(Y_train)))
print("=====\nTesting Data")
print("Document count: %s" % len(Y_test))
labels, counts = np.unique(Y_test, return_counts=True)
for label, count in zip(labels, counts):
print("%s: %s (%.4f)" % (label, count, count/len(Y_test)))
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
x = vectorizer.fit_transform(X_train)
count_vect_df = pd.DataFrame(x.todense(), columns=vectorizer.get_feature_names())
print(count_vect_df.head())
"""Before anything else, this is **Pandas**, easy-to-use data structures and data analysis tools for the Python. Think of it as an abstraction over NumPy and instead of treating your datasets as arrays, we can think of them as dataframes.
So in the code above, we used our count vectorizer and passed our training data on it. Fit transform just means, fit the vectorizer based on the vocab of the training data, so we can use a simple transform on the testing data later.
From the output data frame, we can tell that there are 4155 features (since there are 4155 columns). Each column is a feature and each row is a document. There are only 5 rows in the output because we printed only the head of the DataFrame.
**Question: Looking at our data, what is an issue here?**
(some) Answer:
* **Number of features** - We have a load of features! 4k plus with only 130 training instances! This may be generalizable because we're account for many possible features, but we're seeing a lot of information. What happens if we expand out training samples, will out feature size grow? Yup!
* **Sparcity** - Because we have a lot of features, we're to expect a lot of zeros as well. And if there is only one entry for a specific feature, it might not be super useful.
Let's look at how different configurations can affect the dataset.
"""
print("Default:", CountVectorizer().fit_transform(X_train).shape)
print("Min df set to 1%:", CountVectorizer(min_df=.01).fit_transform(X_train).shape)
print("Min df set to 5%:", CountVectorizer(min_df=.05).fit_transform(X_train).shape)
print("Min df (1%), Max df (90%):", CountVectorizer(max_df=.9, min_df=.01).fit_transform(X_train).shape)
print("Using max features (50):", CountVectorizer(max_features=50).fit_transform(X_train).shape)
print("Using 1,2,3-grams:", CountVectorizer(ngram_range=(1,3)).fit_transform(X_train).shape)
print("Using 1,2,3-grams, Min df (1%), Max df (90%):", CountVectorizer(max_df=.9, min_df=.01, ngram_range=(1,3)).fit_transform(X_train).shape)
print("Using a defined vocabulary:", CountVectorizer(vocabulary=['meme', 'of', 'the', 'week']).fit_transform(X_train).shape)
print("Lowercase off:", CountVectorizer(lowercase=False).fit_transform(X_train).shape)
"""See how the configurations affect the number of features we can learn from? There can be many ways to create representations that our algorithms can learn from. We just need to be smart and justify why our configurations should be considered.
Just note that extracting features is key! Instead of just counts, you can consider:
* Term Frequency (TF)
* Term Frequency Inverse Document Frequency (TFIDF)
* Binary counts
* POS counts
* Lexicon counts
Explore the different levels of information we can extract from text. Some might not be as useful, while others will be fit for the problem.
# 6. Learning based on the features / Training a model / Testing a model
Now that we're able to extract information, let's start with our models. We won't go into detail with the models, but we'll consider the following:
* Naive Bayes (NB)
* k-Nearest Neighbors (kNN)
* Support Vector Machines (SVM)
All ML algorithms have their own strentghs (training time, algorithmic complexicty, etc), so its yet another factor to consider when dealing with classification. So let's formalize our feature set as follows
"""
X_train, X_test, Y_train, Y_test = train_test_split(
text, # Our training set
sentiments, # Our test set
test_size = 0.3, # The defined test size; Training size is just 1 minus the test size
random_state = 12 # So we can shuffle the elements, but with some consistency
)
# We'll just use simple counts
# BRIAN'S NOTE - This is what we are going to be changing. We can experiment
# using TF, TFIDF, POS counts, etc. This is what sir wants us to do. He want
# s us to experiment with different feature extractors and their different
# configurations and determine which of those configurations leads to the
# most accurate training and test set for our data.
vectorizer = CountVectorizer(
max_df=.9,
min_df=.01,
ngram_range=(1,1),
binary=True
)
X_train = vectorizer.fit_transform(X_train)
X_test = vectorizer.transform(X_test)
"""Let's look at the following lines of code:
* `vectorizer.fit_transform(X_train)` - This function fits and transforms the data. Fit means to understand the data passed in. We passed `X_train`, so its like a "oh this is what the training data looks like, let's get its vocab!" Transform means, whatever the data was that was passed in, transform it based on the fit. This returns a fitted count matrix. By context, that also means you can peform a `vectorizer.fit(X_train)` which just fits the data.
* `vectorizer.transform(X_test)` - This function just transforms based on the fit and since our vectorizer was already fitted with the `X_train`, we now just fit the `X_test` to the `X_train` vocab.
Now let's get to actual classification!
"""
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
# The three classifiers that we'll use
# clfs = [
# KNeighborsClassifier(n_neighbors=5),
# MultinomialNB(),
# svm.SVC(kernel='linear')
# ]
# for clf in clfs:
# clf.fit(X_train, Y_train)
# y_pred = clf.predict(X_test)
# acc = accuracy_score(Y_test, y_pred)
# f1 = f1_score(Y_test, y_pred, average=None)
# print("%s\nAccuracy: %s\nF1 Score: %s\n=====" % (clf, acc, f1))
mnb = MultinomialNB()
mnb.fit(X_train, Y_train)
y_pred = mnb.predict(X_test)
acc = accuracy_score(Y_test, y_pred)
f1 = f1_score(Y_test, y_pred, average=None)
print("%s\nAccuracy: %s\nF1 Score: %s\n=====" % (mnb, acc, f1)) |
ae78936d1135929125080769c5fc815465e57728 | ALcot/-Python_6.26 | /script.py | 351 | 4.1875 | 4 | fruits = ['apple', 'banana', 'orange']
# リストの末尾に文字列「 grape 」を追加
fruits.append('grape')
# 変数 fruits に代入したリストを出力
print(fruits)
# インデックス番号が 0 の要素を文字列「 cherry 」に更新
fruits[0] = 'cherry'
# インデックス番号が 0 の要素を出力
print(fruits[0])
|
696a3bda867bf9bec089767c961f9f41c6d463bc | stemaan/isapyweb | /Day01/source code/osoba.py | 875 | 3.828125 | 4 | class Osoba(object):
'''Osoba'''
def __init__(self, imie, nazwisko, pesel):
'''Tworzy instancję klasy Osoba'''
self.imie = imie
self.nazwisko = nazwisko
self.pesel = pesel
self.wiek = None
def __str__(self):
'''Wlasna reprezentacja obiektu przy print() '''
return "{} {} ma pesel: {}".format(self.imie, self.nazwisko, self.pesel)
def __add__(self, other):
'''Własna implementacja zachowania dla operatora "+"
Dzięki temu możemy "dodawać" osoby
'''
return self.wiek + other.wiek
czlowiek1 = Osoba('jan', 'kowalski', 9898978778)
czlowiek1.wiek = 30
czlowiek2 = Osoba('Mateusz', 'Nowak', 98987878778)
czlowiek2.wiek = 34
# print(czlowiek1.imie)
# print(czlowiek1.nazwisko)
# print(czlowiek1.pesel)
print(czlowiek1)
# dodajemy osoby
print(czlowiek1 + czlowiek2)
|
62fd79a0a86093b3014dec48a61b9ebb7b405b11 | dalanmendonca/Coding-Practice | /happy_numbers.py | 417 | 3.5625 | 4 | SQUARE = dict([(c, int(c)**2) for c in "0123456789"])
def is_happy(n):
s = set()
while (n > 1) and (n not in s):
s.add(n)
n = sum(SQUARE[d] for d in str(n))
return n == 1
print "1", is_happy(1)
print "7", is_happy(7)
print "9", is_happy(9)
print "32", is_happy(32)
print "56", is_happy(56)
print "921", is_happy(921)
"""
References:
1. Copied blatanly from http://en.wikipedia.org/wiki/Happy_number
"""
|
916ff25f6d15f94f3ed4d81d31250c14c1f9d220 | bitforbyte/Scripts | /sleepTime.py | 1,497 | 3.9375 | 4 | #!/usr/bin/python3
import argparse
import sys
import re
def calcSleepTime(argc, argv):
match = re.match(r'(\d+):(\d\d)', argv)
if match is None:
match = re.match(r'(\d*)', argv)
hour = int(match.group(1))
# Make sure input is greater than 12
if (hour > 12):
print("Must be between (1-12)")
exit(1)
count = 8
# Loop through the 8 hours until 0 is reached and loop time
while (count > 0):
#print("hour %d" % hour)
hour -= 1
if hour == 0:
hour = 12
count -= 1
# If the match is more than just a number
if len(match.group()) > 2:
print("%d:%s" % (hour, match.group(2)))
else:
print("%d:00" % (hour))
if __name__ == "__main__":
# If the arguments aren't 2 print message
if (len(sys.argv) != 2):
print("Description: Program will calculate the best time to sleep to get 8 hours of sleep for an alarm\n")
print("Usage:")
print(" sleepTime {1-12}")
print(" sleepTime {1-12}:{00-59}")
print(" sleepTime {1-12}:{00-59}{am/pm}")
elif (sys.argv[1] == '0'):
print("0 not an argument")
else:
input = sys.argv[1]
try:
val = int(input)
except ValueError:
match = re.match(r'(^\d*):(\d\d([ap]m)?$)', input)
if match is None:
print("Error Wrong input")
exit(1)
calcSleepTime(len(sys.argv), str(sys.argv[1]))
|
75dcd1daebf33f1d58bc9a1b313223288bddecc5 | Pallavidighe2/python_201901 | /class_02.py | 1,686 | 3.96875 | 4 | """"
this is class 02 file
1 Varibale
2 Data type: integer, string,boolean,none
3 Data structure : We can store multiple data type and their relationship in string
"""
integer_variable =3
print(integer_variable,id(integer_variable),)
# string
string_variable ="This is my sinle line string"
string_variable_2= "This is my" \
"multi line string 01"
string_variable_03="""
afs
vgd
ajhdgh
"""
#
# print(string_variable)
# print(string_variable_2)
# print(string_variable_03)
#
#boolean
true_flag=True
false_flag=False
##None
none_variable=None
#
# print("string_variable_03 ",type(string_variable_03))
# print("true_flag",type(true_flag))
# print("none_variable",type(none_variable),id(none_variable))
a=""
print("a",type(a))
# Data Structure
# 1 List
# list_variable= [ 'Pallavi' ,'Jayshree',215445,325.125, 'Pallavi']
# print(list_variable)
#
# print(type(list_variable[0]),type(list_variable[1]), type(list_variable[2]),type(list_variable[3]))
#
# print(list_variable.index('Jayshree')) # showing index value of jayshree in list
#
# print(len(list_variable))
# print(list_variable.count('Pallavi'))
integer_list=[5,2,7,3,9,8]
print(sorted(integer_list))
integer_list.sort(reverse=True)
print(integer_list)
list_nested=[
"Pallavi",["samarthtech","certview",[25512,2884]]
]
print(list_nested[1][2][0])
list_nested_02=[
['test1',['test2','test3',['test4']],'test5',['test6','test7'],'test8',['test9',['test10']]]
]
print(list_nested_02)
print(list_nested_02[0][4])
print(list_nested_02[0][5][1][0])
"""
Assignment
1 create 5 variable for each data type
2 create 5 list variable with 3 elements like name,address,contact number
"""
|
03bd4e50ba2c18977599d5b012c04547ef2d2eb1 | Pallavidighe2/python_201901 | /Income_Tax_Calculator.py | 4,055 | 4.0625 | 4 | def income_tax_calculaor():
global Total_Income
Total_Income = input("Enter your Total Annual income : ")
Total_Income = int(Total_Income)
investment()
def investment():
investment = input("user have investment then 'S' or 'N': ")
if investment == "N":
tax_calculate_without_deduction()
elif investment == "S":
tax_calculate_with_deduction()
def tax_calculate_without_deduction():
if Total_Income <= 250000:
print("You don't pay any tax ")
elif 250001 <= Total_Income <= 500000:
A = Total_Income - 250000
Tax1 = A * 0.05
print("you have to pay Tax1 {}".format(Tax1))
elif 500001 <= Total_Income <= 1000000:
A = Total_Income - 250000
B = A - 250000
Tax2 = (B * 0.2) + 12500
print("you have to pay Tax1 {}".format(Tax2))
elif Total_Income >= 1000000:
A = Total_Income - 250000
B = A - 250000
C = B - 500000
Tax3 = (C * 0.3) + 100000 + 12500
print("you have to pay Tax1 {}".format(Tax3))
def tax_calculate_with_deduction():
deduction()
taxable_income = Total_Income-Total_Deduction
taxable_income=int(taxable_income)
print(taxable_income)
if taxable_income <= 250000:
print("You don't pay any tax ")
elif 250001 <= taxable_income <= 500000:
A = taxable_income - 250000
Tax1 = A * 0.05
print("you have to pay Tax1 {}".format(Tax1))
elif 500001 <= taxable_income <= 1000000:
A = taxable_income - 250000
B = A - 250000
Tax2 = (B * 0.2) + 12500
print("you have to pay Tax1 {}".format(Tax2))
elif taxable_income >= 1000000:
A = taxable_income - 250000
B = A - 250000
C = B - 500000
Tax3 = (C * 0.3) + 100000 + 12500
print("you have to pay Tax1 {}".format(Tax3))
def deduction():
global Total_Deduction
Deduction_Under_80CCD()
Deduction_Under_80C()
Deduction_for_medicalim()
Total_Deduction = x + NPS + mediclaim
print(Total_Deduction)
def Deduction_Under_80C():
print("YOur Deduction under 80C max 1,50,000")
# Enter your dedection
LIC = input("Enter the amount you invest for LIC : ")
National_Saving_Certificate = input(
"Enter the amount you invest for National_Saving_Certificate : ")
Invetsment_In_PF = input(
"Enter the amount you invest for Invetsment_In_PF : ")
Tuition_Fee = input("Enter the amount you invest for Tuition_Fee : ")
Mutual_Fund = input("Enter the amount you invest for Mutual_Fund : ")
Bank_FD = input("Enter the amount you invest for Mutual_Fund : ")
House_Loan_Repayment = input(
"Enter the amount you invest for House_Loan_Repayment : ")
Employee_PF = input("Enter the amount you invest for Employee_PF : ")
Stamp_Duty = input("Enter the amount you invest for Stamp_Duty : ")
Residential_Housing_Loan = input(
"Enter the amount you invest for Residential_Housing_Loan : ")
Sukanya_Samrudhhi_Scheme = input(
"Enter the amount you invest for Sukanya_Samrudhhi_Scheme : ")
list = [LIC, National_Saving_Certificate, Invetsment_In_PF, Bank_FD,
House_Loan_Repayment, Employee_PF, Stamp_Duty,
Residential_Housing_Loan, Sukanya_Samrudhhi_Scheme]
print(list)
global x
x = 0
for num in list:
x = x + int(num)
print("x = ", x)
if x <=150000:
print(x)
else:
x=150000
print(x)
def Deduction_Under_80CCD():
global NPS
print("Additional deduction under 80CCD 50,000")
NPS = int(input("Enter amount investment for NPS: "))
if NPS <= 50000:
print(NPS)
else:
NPS = 50000
print(NPS)
def Deduction_for_medicalim():
global mediclaim
print("investment under section 80 D max 15,000")
mediclaim = int(input("Enter your mediclaim amount: "))
if mediclaim <= 15000:
print(mediclaim)
else:
mediclaim = 15000
print(mediclaim)
income_tax_calculaor() |
0c90ee44f054f4c81f0d4afb9773c387328dafe6 | FIH-Engineering/FLIR-Lepton | /button/button.py | 621 | 3.6875 | 4 | import RPi.GPIO as GPIO
import time
import os
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# ISR: if our button is pressed, we will have a falling edge on pin 31
# this will trigger this interrupt:
def Int_shutdown(channel):
# shutdown our Raspberry Pi
os.system("sudo shutdown -h now")
# Now we are programming pin 18 as an interrupt input
# it will react on a falling edge and call our interrupt routine "Int_shutdown"
GPIO.add_event_detect(18, GPIO.FALLING, callback = Int_shutdown, bouncetime = 2000)
while 1:
time.sleep(1) |
a416493250bfa568f349a4e4278d8cc293fcc7de | xaadu/uri-solves | /Python/1002.py | 55 | 3.578125 | 4 | a = float(input())
print("A=%.4f" % ((a**2)*3.14159))
|
8464f1fa7547f86074e796a694ed4d87822e2983 | itothep/Project_Euler | /Q2.py | 230 | 3.75 | 4 | def Fibonacci(n):
if(n==2):
return 2;
elif(n==1):
return 1;
return Fibonacci(n-1)+Fibonacci(n-2)
def Find():
i=1;
sum=0;
while(Fibonacci(i)<=4000000):
if(Fibonacci(i)%2==0):
sum+=Fibonacci(i)
i+=1
print(sum)
|
b5d7ea09ea024245a2a2221a5c1b314fb47f19a1 | dukexl/code | /python/day210901/python3_3.py | 1,562 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 25 19:51:00 2019
@author: Administrator
"""
from pandas import Series;
#定义,可以混合定义
x = Series(['a', True, 1], index=['first', 'second', 'third'])
x = Series(['a', True, 1]);
#访问
print(x[1]);
#根据index访问
#x['first'] ????
#不能越界访问
x[2]
"""
#不能追加单个元素
x.append('2')
#追加一个序列
n = Series(['2'])
x.append(n)
#需要使用一个变量来承载变化
x = x.append(n)
'2' in x
#判断值是否存在
'2' in x.values
#切片
x[1:3]
#定位获取,这个方法经常用于随机抽样
x[[0, 2, 1]]
#根据index删除
x.drop(0)
x.drop('first')
#根据位置删除
x.drop(x.index[3])
#根据值删除
x['2'!=x.values]
"""
from pandas import DataFrame;
df = DataFrame({
'age': [21, 22, 23],
'name': ['KEN', 'John', 'JIMI']
});
df = DataFrame(data={
'age': [21, 22, 23],
'name': ['KEN', 'John', 'JIMI']
}, index=['first', 'second', 'third']);
df
#按列访问
print(df['age'])
#按行访问
df[1:2]
"""
#按行列号访问
df.iloc[0:1, 0:1]
#按行索引,列名访问
df.at[0, 'name']
#修改列名
df.columns
df.columns=['age2', 'name2']
#修改行索引
df.index
df.index = range(1,4)
df.index
#根据行索引删除
df.drop(1, axis=0)
#默认参数axis=0
#根据列名进行删除
df.drop('age2', axis=1)
#第二种删除列的方法
del df['age2']
#增加行,注意,这种方法,效率非常低,不应该用于遍历中
df.loc[len(df)] = [24, "KENKEN"];
#增加列
df['newColumn'] = [2, 4, 6, 8];
""" |
0653a961dfdf6df6d69b35ae469934e0f274cfd0 | ters81/Texas-Hold-em-Poker | /tests/validators/test_flush_validator.py | 1,522 | 3.65625 | 4 | import unittest
from poker.card import Card
from poker.validators import FlushValidator
class FlushValidatorTest(unittest.TestCase):
def setUp(self):
self.two_of_diamonds = Card(rank='2', suit='Diamonds')
self.three_of_diamonds = Card(rank='3', suit='Diamonds')
self.five_of_diamonds = Card(rank='5', suit='Diamonds')
self.seven_of_diamonds = Card(rank='7', suit='Diamonds')
self.eight_of_diamonds = Card(rank='8', suit='Diamonds')
self.queen_of_diamonds = Card(rank='Queen', suit='Diamonds')
self.cards = [
self.two_of_diamonds,
self.three_of_diamonds,
self.five_of_diamonds,
self.seven_of_diamonds,
self.eight_of_diamonds,
Card(rank='Jack', suit='Hearts'),
self.queen_of_diamonds
]
def test_validates_that_five_cards_of_same_suit_exist_in_collections(self):
validator = FlushValidator(cards=self.cards)
self.assertEqual(
validator.is_valid(),
True
)
def test_returns_the_five_highest_cards_with_the_same_suit(self):
validator = FlushValidator(cards=self.cards)
self.assertEqual(
validator.valid_cards(),
[
self.three_of_diamonds,
self.five_of_diamonds,
self.seven_of_diamonds,
self.eight_of_diamonds,
self.queen_of_diamonds
]
) |
0c2e3e32a1f985c543ec4330f5e2a06eb7e1bdb7 | johnsonge/eulerSolutions | /sol06.py | 494 | 3.65625 | 4 | #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
tempSquares = []
tempSum = []
n = 100
for i in range(1,n+1):
tempSum.append(i)
i = i ** 2
tempSquares.append(i)
squareOfSums = sum(tempSum) ** 2
sumOfSquares = sum(tempSquares)
print ("Sum of squares: " + str(sumOfSquares))
print ("Square of sums: " + str(squareOfSums))
print (str(squareOfSums) + " - " + str(sumOfSquares) + " = " + str(squareOfSums - sumOfSquares)) |
73f9180b49009c4a52be068f633f177124ec4c97 | parthu12/DataScience | /daily practise/try.py | 206 | 3.890625 | 4 | a=int(input('enter a num'))
try:
if a>4:
print('>4')
else:
print('<4')
except valueerror:
print('value in digit')
finally:
print('success')
|
69a6dafd185ec6aa955a7bc1e99fada17c9f1341 | parthu12/DataScience | /daily practise/simple intrest.py | 367 | 3.578125 | 4 | p=float(input("input princple"))
t=float(input("time"))
r=float(input("rate of intresst"))
def simpleIntrest(p,t,r):
si=0
si=p*t*r/100
print("simple intrest is"+str(si))
simpleIntrest(p,t,r)
def compoundIntrest(p,t,r):
amount=0
amount=p*((1+(r/100))**t)
ci=amount-p
print("compound intrest"+str(ci))
compoundIntrest(p,t,r)
|
6ab7d0c612cb6e62aae83d747b9b1c450185f28b | doshik101/Laby | /Laba2/10.6.py | 236 | 3.890625 | 4 | sum=0
while a!='стоп' or a!='Стоп':
a=input('Введите число; Чтобы остановить работу программы введите слово Стоп ')
if a.isdigit():
sum=sum+int(a)
print(c)
|
40a44fdb0b2e70f0c8e182a5f8611daf261e1861 | doshik101/Laby | /clc/calc.py | 2,520 | 3.890625 | 4 | import tkinter
from tkinter import *
window=tkinter.Tk()
window.title('Calculator')
window.geometry('200x190+300+200')
ch=StringVar()
pole = Entry(window, width = 35, font = 'Arial 8', textvariable=ch)
pole.grid(column = 0)
pole.place(x=0, y=1)
pole.pack()
def enter(c):
return ch.set(ch.get() + c)
def result(c):
return ch.set(ch.get() + c)
knopka1=Button(window, text='%', width=6, height=1, command=enter('%'))
knopka1.place(x=0,y=20)
knopka2=Button(window, text='СЕ', width=6, height=1)
knopka2.place(x=47,y=20)
knopka3=Button(window, text='C', width=6, height=1)
knopka3.place(x=94,y=20)
knopka19=Button(window, text='<--', width=6, height=1)
knopka19.place(x=141,y=20)
knopka4=Button(window, text='1/x', width=6, height=1)
knopka4.place(x=0,y=47)
knopka5=Button(window, text='x*x', width=6, height=1)
knopka5.place(x=47,y=47)
knopka6=Button(window, text='sqrt(x)', width=6, height=1)
knopka6.place(x=94,y=47)
knopka20=Button(window, text='/', width=6, height=1)
knopka20.place(x=141,y=47)
knopka7=Button(window, text='7', width=6, height=1, command=enter('7'))
knopka7.place(x=0,y=74)
knopka8=Button(window, text='8', width=6, height=1, command=enter('8'))
knopka8.place(x=47,y=74)
knopka9=Button(window, text='9', width=6, height=1, command=enter('9'))
knopka9.place(x=94,y=74)
knopka21=Button(window, text='X', width=6, height=1)
knopka21.place(x=141,y=74)
knopka10=Button(window, text='4', width=6, height=1, command=enter('4'))
knopka10.place(x=0,y=101)
knopka11=Button(window, text='5', width=6, height=1, command=enter('5'))
knopka11.place(x=47,y=101)
knopka12=Button(window, text='6', width=6, height=1, command=enter('6'))
knopka12.place(x=94,y=101)
knopka22=Button(window, text='-', width=6, height=1)
knopka22.place(x=141,y=101)
knopka13=Button(window, text='1', width=6, height=1, command=enter('1'))
knopka13.place(x=0,y=128)
knopka14=Button(window, text='2', width=6, height=1, command=enter('2'))
knopka14.place(x=47,y=128)
knopka15=Button(window, text='3', width=6, height=1, command=enter('3'))
knopka15.place(x=94,y=128)
knopka23=Button(window, text='+', width=6, height=1)
knopka23.place(x=141,y=128)
knopka16=Button(window, text='+/-', width=6, height=1)
knopka16.place(x=0,y=155)
knopka17=Button(window, text='0', width=6, height=1, command=enter('0'))
knopka17.place(x=47,y=155)
knopka18=Button(window, text='.', width=6, height=1)
knopka18.place(x=94,y=155)
knopka24=Button(window, text='=', width=6, height=1, command=enter('='))
knopka24.place(x=141,y=155)
window.mainloop()
|
3f3e22f6e0c3211ba64c0b0fe58c37f22ec556c1 | doshik101/Laby | /Laba2/7.py | 1,280 | 3.625 | 4 | import math
import random
n=int(input('Введите номер задачи: '))
if n == 7.1:
a,b,c=map(int,input('Введите a,b,c').split())
p=(a+b+c)/2
s=math.sqrt(p*(p-a)*(p-b)*(p-c))
print(s)
elif n == 7.2:
print(round (math.pi,2))
elif n == 7.3:
x=int(input('Введите x'))
print(math.sqrt(1-(pow(math.sin(x), 2))))
elif n == 7.4:
a=random.randint(1,5)
x=int(input('Угадайте число от 1 до 5'))
if x==a:
print('Вы угадали')
else:
print('Вы не угадали')
elif n == 7.5:
x=int(input('Введите x'))
def f(x):
return x**4 + 4**x
print(f(x))
elif n == 7.6:
x,y=map(int,input('Введите x,y').split())
z=(x+((2+y)/x**2))/(y + 1/math.sqrt(x**2+10))
q=2.8*math.sin(x)+math.fabs(y)
print (z,q)
elif n == 7.7:
x=float(input('Введите x'))
if 0.2 <= x <= 0.9:
print(math.sin(x))
else:
print(1)
elif n == 7.8:
x=random.randint(1,6)
y=random.randint(1,6)
print('У первого игрока',x)
print('У второго игрока',y)
if x>y:
print('У первого игрока больше')
else:
print('У второго игрока больше')
|
0c2e80554a16683a033dcfbfb4744840bbb81066 | prasankarthik/Numpy_package | /Main.py | 1,938 | 4.09375 | 4 |
# coding: utf-8
# In[1]:
#Advantages of usning numpy's universal function
import numpy as np
# In[26]:
#Without using numpy the speed of the loop is 90microsec
list1 = list(range(1000))
get_ipython().magic('timeit newlist = [i + 2 for i in list1]')
# In[27]:
#Now converting the list into numpy
#The same loop now takes 3 microsec
arr1 = np.array(list1)
get_ipython().magic('timeit newlist = arr1 + 2')
# In[4]:
#Advantages of Using numpy's aggreagations
# In[23]:
#Making a list of 10000 random numbers
from random import random
list2 = [random() for i in range(10000)]
# In[24]:
#Calculating the minimum of the list
get_ipython().magic('timeit min(list2)')
# In[25]:
#Now converting list2 to numpy2 array
numpy2 = np.array(list2)
get_ipython().magic('timeit numpy2.min()')
# In[30]:
#Usage in multidimensional arrays
numpy3 = np.random.randint(0,10,(3,5))
numpy3
# In[36]:
numpy3.mean()
# In[43]:
numpy3.argmax(axis=1)
# In[35]:
#Printing the sum column wise and row wise
numpy3.sum(axis=0)
# In[34]:
numpy3.sum(axis=1)
# In[44]:
#Numpy for broadcasting
#Broadcasting is stretching one matrix to equal to the dimension of the other matrix
#The general matrix functionality applies in broadcasting - when a 3*1 matrix is added to 1*3 matrix a 3*3 matrix is formed
np.ones(3) + 5
# In[47]:
np.arange(3).reshape(3,1) + np.arange(3)
# In[ ]:
#Using numpy's slicing, masking, and fancy indexing
# In[48]:
#Using masking in indexing
numpyar = np.array(range(6))
# In[51]:
mask = [True, False, True, False, False, True]
# In[52]:
numpyar[mask]
# In[62]:
mask = (numpyar>3) & (numpyar<5)
mask
# In[63]:
numpyar[mask]
# In[64]:
#Using fancy indexing
ind = [1,3,4]
# In[65]:
numpyar[ind]
# In[66]:
#Using masking and slice in a multidimensional array
narray = np.arange(3).reshape(3,1) + np.arange(3)
# In[74]:
narray[narray.sum(axis = 1) > 4, :2]
|
cf34d21380953104cca0b9aa4444dded3c763e63 | MohdTabish008/PYTHON | /Guess_the_Code.py | 1,061 | 4.0625 | 4 | #!/usr/bin/env python
import random
def get_guess():
return list(input('Enter 3 Digit Code'))
#Generate Random Code
def code_generator():
digits = [str(num) for num in range(10)]
#shuffling the digits
random.shuffle(digits)
#grab first three digits
return digits[:3]
#Generate The Clues
def generate_clues(code,user_guess):
if user_guess == code:
return 'Attaboy! Code Cracked'
clues = []
for index,num in enumerate(user_guess):
if num == code[index]:
clues.append('Match')
elif (num in code):
clues.append('Close')
if clues == []:
return ['Try Hard']
else:
return clues
#Run Game Logic
print('Welcome Spy,Guess the Code')
secret_code = code_generator()
clue_report = []
while clue_report != 'Attaboy! Code Cracked':
guess = get_guess()
clue_report = generate_clues(secret_code,guess)
print('result of 1st num , result of 2nd num , result of 3rd num')
print(*clue_report)
|
a6a8f31e4b96a57b49e7123769768049717fc115 | evbeda/games3 | /uno/const.py | 756 | 3.84375 | 4 | from .card import NumberCard
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
YELLOW = 'yellow'
DRAW_CARD_INPUT = ''
EXIT = 'exit'
ASK_FOR_INPUT = \
"Please select index of card to play! \n" + \
"Or just press enter to draw a card \n" + \
"(Type exit to quit) \n"
UNO_FINAL_LAST_PLAYED_CARD = NumberCard('red', 7)
UNO_FINAL_PLAYER_CARD = NumberCard('red', 9)
UNO_FINAL_COMPUTER_CARD = [NumberCard('red', 9), NumberCard('green', 8)]
UNO_ALMOST_FINISHED_BOARD = '''Your cards are:
1: 9 - red
Computer remaining cards: 2
The last card played is:
7 - red'''
UNO_FINISHED_BOARD = '''Your cards are:
Computer remaining cards: 2
The last card played is:
9 - red'''
EXIT_MESSAGE = 'Bye!'
INVALID_CARD_MESSAGE = "Invalid card."
FINISHED_PLAY_MESSAGE = ""
|
3442780fcf656417aa119190f13137e61db8d005 | jamessandy/Pycon-Ng-Refactoring- | /refcator.py | 527 | 4.21875 | 4 | #Example 1
num1 = 4
num2 = 4
result = num1 + num2
print(result)
#Example 2
num1 = int(input('enter the firExamst number:'))
num2 = int(input('enter the second number:'))
result = num1 + num2
print('your answer is:', result)
#Example 3
num1 = int(input('Enter number 1:'))
num2 = int(input('Enter number 2:'))
result = num1 + num2
print(result)
#Example 4
def add (x, y):
return x + y
num1 = int(input('Enter number 1:'))
num2 = int(input('Enter number 2:'))
result = add(num1, num2)
print('your answer is:', result)
|
b9859dfaf7618cd28253a941374f1cbfcaa560c4 | nicolas43000/MHWorldData | /mhdata/util/orderedset.py | 631 | 3.828125 | 4 | import collections.abc
class OrderedSet(collections.abc.MutableSet):
"A set that maintains insertion order"
def __init__(self):
# use a dict to hold data.
# In python 2.6 and up, dicts maintain insertion order
self._data = {}
def add(self, item):
if item not in self:
self._data[item] = 1
def discard(self, item):
if item in self:
del self._data[item]
def __contains__(self, item):
return item in self._data
def __iter__(self):
return self._data.keys().__iter__()
def __len__(self):
return len(self._data)
|
4d9729e57e5e19855bd13b71df3b21ed4d00d98b | Tuhgtuhgtuhg/PythonLabs | /lab01/Task_1.py | 651 | 4.21875 | 4 | from math import sqrt
while True:
m = input("Введіть число \"m\" для обчислення формули z=sqrt((m+3)/(m-3)): ")
if ( m.isdigit()):
m = float(m)
if (m<=-3 or m > 3):
break
else:
print("""Нажаль число "m" повинно лежати у такому проміжку: m ∈ (-∞;-3]U(3;∞) !!!
Спробуйте ще раз!""")
else:
print("""Нажаль введена інформація не є числом!\nСпробуйте ще раз!""")
z = sqrt((m+3)/(m-3))
if (z == -0.0 or z == 0.0 ):
z = 0
print( "z = " + str(z))
|
ab57db61ddf1747446f7a8d568222ab23f7584ac | Tuhgtuhgtuhg/PythonLabs | /lab05/lab5_6.py | 2,614 | 3.84375 | 4 | class Transport:
def __init__(self):
self.value = 0
self.speed = 0
self.year = 0
self.coord = ""
def setVal(self, input):
self.value = input
def setSpeed(self, input):
self.speed = input
def setYear(self, input):
self.year = input
def setCoord(self, input):
self.coord = input
class Car (Transport):
def __init__(self):
self.value = 0
self.speed = 0
self.year = 0
self.coord = ""
def getCarCharacteristics(self):
print("\nХарактеристики автомобіля\n"
+ "Ціна: " + str(self.value)
+ "\nШвидкість: " + str(self.speed)
+ "\nРік: " + str(self.year)
+ "\nКоординати: " + self.coord)
class Plane (Transport):
def __init__(self):
self.value = 0
self.speed = 0
self.passengers = 0
self.coord = ""
self.year = 0
self.height = 0
def setHeight(self, input):
self.height = input
def setPassengers(self, input):
self.passengers = input
def getPlaneCharacteristics(self):
print("\nХарактеристика Літака\n"
+ "Ціна: " + str(self.value)
+ "\nШвидкість: " + str(self.speed)
+ "\nРік: " + str(self.year)
+ "\nКоординати: " + self.coord
+ "\nВисота: " + str(self.height)
+ "\nКількість пасажирів: " + str(self.passengers))
class Ship (Plane):
def __init__(self):
self.value = 0
self.speed = 0
self.year = 0
self.port = 0
self.coord = ""
self.passangers = 0
def setPort(self, input):
if isinstance(input, str):
self.port = input
def getShipCharacteristics(self):
print("\nХарактеристика корабля\n"
+ "Ціна: " + str(self.value)
+ "\nШвидкість: " + str(self.speed)
+ "\nРік: " + str(self.year)
+ "\nКоординати: " + self.coord
+ "\nПорт: " + self.port
+ "\nКількість пасажирів: " + str(self.passengers))
if __name__ == '__main__':
ship = Ship()
ship.setVal(250000)
ship.setSpeed(200)
ship.setYear(1956)
ship.setCoord("18:30:245")
ship.setPassengers(56)
ship.setPort("Одеський морський порт")
ship.getShipCharacteristics()
|
e130159211e4dc6092a9943fa6a1c9422d058f68 | mclark116/techdegree-project | /guessing_game2.py | 2,321 | 4.125 | 4 | import random
history = []
def welcome():
print(
"""
____________________________________
Welcome to the Number Guessing Game!
____________________________________
""")
def start_game():
another = "y"
solution = random.randint(1,10)
value = "Oh no! That's not a valid value. Please chose a number between 1 and 10."
attempt = 0
while another == "y":
try:
prompt = int(input("Pick a number between 1 and 10: "))
except ValueError:
print(value)
else:
if prompt > solution:
if prompt > 10:
print(value)
else:
print("It's lower!")
attempt +=1
elif prompt < solution:
if prompt < 1:
print(value)
else:
print("It's higher!")
attempt +=1
elif prompt == solution:
attempt +=1
if attempt == 1:
print("\nGot it! It took you {} try!".format(attempt))
else:
print("\nGot it! It took you {} tries!".format(attempt))
print("Game Over!")
history.append(attempt)
solution = random.randint(1,10)
attempt = 0
another = input("Would you like to play again? y/n ")
if another.lower()=="y":
print("\nHigh Score: {}".format(min(history)))
elif another.lower()!="y":
if another.lower()=="n":
print("\nGame Over! Thanks for playing.")
break
else:
while another.lower !="y" or "n":
print("Please choose y or n")
another = input("Would you like to play again? y/n ")
if another.lower()=="y":
print("\nHigh Score: {}".format(min(history)))
break
elif another.lower()!="y":
if another.lower()=="n":
break
welcome()
start_game() |
ff6b31dbab81384f18190e0129bcf48ef88b7eda | kuarchi-programming-2018/181025assignment-a0176177 | /recursion-practice/rose.py | 946 | 3.609375 | 4 | # -*- coding: utf-8 -*-
from turtle import *
def rectangle(points):
[[x0,y0],[x1,y1],[x2,y2],[x3,y3]] = points
up()
setpos(x0,y0)
down()
setpos(x1,y1)
setpos(x2,y2)
setpos(x3,y3)
setpos(x0,y0)
def deviding_point(p0,p1,ratio):
[x0,y0] = p0
[x1,y1] = p1
xr = deviding(x0,x1,ratio)
yr = deviding(y0,y1,ratio)
return [xr,yr]
def deviding_points(points,ratio):
[p0,p1,p2,p3] = points
pr0 = deviding_point(p0,p1,ratio)
pr1 = deviding_point(p1,p2,ratio)
pr2 = deviding_point(p2,p3,ratio)
pr3 = deviding_point(p3,p0,ratio)
return [pr0,pr1,pr2,pr3]
def rose_window_recursion(points,ratio,depth):
rectangle(points)
new_points = deviding_points(points,ratio)
if depth == 0:
up()
setpos(-200,-200)
else:
rose_window_recursion(new_points,ratio,depth -1)
def deviding(p0,p1,r):
return p0*(1-r)+p1*r
|
31af3d59a193c172200018bff9f02fdd888e98ba | GaryDoooo/Khan_A_JS | /Libby workspace root/Libby1.py | 326 | 4.03125 | 4 | print ("Libby's Calculator!")
a=input("Please input A:")
b=input("Please input B:")
a=int(a)
b=int(b)
print("A+B=",a+b)
print("A*B=",a*b)
print("A/B=",a/b)
print("A-B=",a-b)
print("A**B=",a**b)
if a>b:
print("A is larger than B.")
if a<b:
print("A is smaller t```han B.")
if a==b:
print("A is equal to B.")
|
b2cf77213839d3fc4ddc8ece7d5c44636e5d201b | PhillyVanilly9119/LearnPythonFromScratch | /Python_Practice_Code_1_random.py | 4,748 | 4.125 | 4 |
# The following functions were coded from the "practice!"- exercise on Codeacademy(c)
# Note that some (the majority) are the solutions from Codeacademy(c)
def is_even(x):
# This function return whether or not a number a even
if x % 2 == 0:
return True
else:
return False
# print is_even(33)
def is_int(number):
# This function returns whether or not a input (number) is an interger
absolute_count = abs(number)
type_count = type(number)
round_count = round(absolute_count)
if type_count and absolute_count - round_count == 0:
return True
else:
return False
# print is_int(45.5)
def digit_sum(x):
# This function returns the cross sum of a number (sum of all digits)
total = 0
while x > 0:
total += x % 10
x = x // 10
print x
return total
# print digit_sum(12345)
def factorial(number):
# This function returns the factorial of any number it is fed
total = 1
while number > 1:
total *= number
number -= 1
return total
# print factorial(5.0)
def is_prime(number):
# This function returns whether or not a number is prime
if number < 2:
return False
else:
for n in range(2, number - 1):
if number % n == 0:
return False
return True
# print is_prime(237846)
def reverse(reversable_text):
# This function reverses the order of letters in a string
word = ""
l = len(reversable_text) - 1
while l >= 0:
word = word + reversable_text[l]
l -= 1
return word
# print reverse("Take Caps Aswell As Spaces ?")
def anti_vowel(text):
# This function only returns only the consonants of a string
t = ""
for c in text:
for i in "aeiouAEIOU":
if c == i:
c = ""
else:
c = c
t = t + c
return t
# print anti_vowel("Was soll das denn sein?!")
def scrabble_score(word):
# This function adds the values of a letter within a string, kinda like a simplified scrabble-game would work
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
word = word.lower()
total = 0
for letter in word:
for leter in score:
if letter == leter:
total = total + score[leter]
return total
# print scrabble_score('Matthias')
def censor(text, word):
# This function censors a word/ letter/ sentence within a given word/ letter/ sentence
words = text.split()
result = ''
stars = '*' * len(word)
count = 0
for i in words:
if i == word:
words[count] = stars
count += 1
result =' '.join(words)
return result
# print censor("This is shit", "shit")
def count(sequence, item):
# This function counts a certain item in a list and returns the sum of the item within the list
count = 0
for i in sequence:
if i == item:
count += 1
return count
# print count([1, 2, 312, 2, 3, 32, 2312, 1, 312, 3, 2, 1, 1], 1)
def purify(list):
# This function only prints even numbers within a given list of numbers
new_list = []
for i in list:
if i % 2 == 0:
new_list.append(i)
return new_list
# print purify([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
def product(int_list):
# This function returns the product of all the intergers within a given list
total = 1
for num in int_list:
total = total * num
return total
# print product([1, 2, 3, 4, 5])
def remove_duplicates(doupl_list):
# This function removes all the duplicates from a given list of numbers
if doupl_list == []:
return []
doupl_list = sorted(doupl_list)
output_list = [doupl_list[0]]
for i in doupl_list:
if i > output_list[-1]:
output_list.append(i)
return output_list
# print remove_duplicates([1, 1, 2, 2, 3, 3, 3])
def median(lst):
# This function returns the median (middle- most element) of a list after sorting it
sorted_list = sorted(lst)
if len(sorted_list) % 2 != 0:
index = len(sorted_list)//2
return sorted_list[index]
elif len(sorted_list) % 2 == 0:
index_1 = len(sorted_list)/2 - 1
index_2 = len(sorted_list)/2
mean = (sorted_list[index_1] + sorted_list[index_2]) / 2.0
return mean
# print median([1, 5, 6, 4])
|
0457106e33cc1878c120bf7712cac80bb8aff331 | mhaco/tkinter | /tkinter_01.py | 456 | 3.5625 | 4 | from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(topFrame, text="Button 1", fg="red", command="hello")
button2 = Button(topFrame, text="Button 2", fg="blue")
button3 = Button(topFrame, text="Button 3", fg="green")
button4 = Button(bottomFrame, text="Button 4", fg="purple")
button1.pack()
button2.pack()
button3.pack()
button4.pack()
root.mainloop()
|
1271c6b2b6d3c37badf55124c38c37b331415365 | ayushmittal02/Python-Basics | /Intro_to_Matplotlib.ipynb | 2,029 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import matplotlib.pyplot as plt
import numpy as np
get_ipython().run_line_magic('matplotlib', 'inline')
# # Basic function plot
# In[ ]:
x=np.linspace(0,2*np.pi,360) #Creating functions to be plotted
y1=np.sin(x)
y2=np.sin(x**2)
# In[ ]:
plt.plot(x,y1,label='sin(x)') #Basics commands to plot a function
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine-Wave!')
# In[ ]:
# In[ ]:
f, ax=plt.subplots() #Creates a workspace as 'f' and axes as 'ax'
ax.plot(x,y1)
ax.plot(x,y2)
ax.set_title("Waves!")
ax.set_xlabel("No. of hats")
ax.set_ylabel("Coolness factor")
ax.grid()
ax.set_xlim(0,6.5) #Sets limit of x-axis
ax.set_xticks([0,np.pi,2*np.pi])
# In[ ]:
#Creating figure/workspace and multiple axes separately
f=plt.figure()
ax1=plt.axes([0,1,0.1,0.1]) #First 2 numbers are relative x,y positions in the figure and
ax2=plt.axes([0.4,0.6,0.3,0.3]) #last 2 numbers are relative length,width of the axes
ax3=plt.axes([0.3,0.4,0.2,0.8])
# In[ ]:
f=plt.figure()
#plt.subplot2grid(shape, loc, rowspan=1, colspan=1)
#shape: Shape of grid in which to place axis. First entry is number of rows, second entry is number of columns.
#loc: Location to place axis within grid. First entry is row number, second entry is column number.
ax1=plt.subplot2grid((3,3), (0,0), colspan=3)
ax2=plt.subplot2grid((3,3), (1,0), colspan=2)
ax3=plt.subplot2grid((3,3), (1,2), rowspan=2)
ax4=plt.subplot2grid((3,3), (2,0))
ax5=plt.subplot2grid((3,3), (2,1))
ax1.plot(x,y1)
ax2.hist(y1)
ax3.scatter(x,y1)
ax4.boxplot(y1)
ax5.loglog(x,y1)
# # Sharing axis
# In[ ]:
x=np.linspace(0,2*np.pi,400)
y=np.sin(x**2)
# In[ ]:
#Sharex=True means x- axis will be shared among all subplots.
f, ax=plt.subplots(2,sharex=True)
ax[0].plot(x,y)
ax[1].plot(x+4,y*0.4)
# # Customizing a plot's appearance
# In[ ]:
f,ax=plt.subplots()
ax.plot([1,2,3], linestyle='--', color='red')
#Second method
line, =ax.plot([1,3,6])
line.set(lw=2,ls='-.',c='g') #lw:linewidth
|
ff21a6db36168a88f168290b880917c9633f8c65 | rohinro/Basic_Shopping | /Appending_Values.py | 1,001 | 3.9375 | 4 | class Compute:
def __init__(self):
self.l = []
def add(self,a=0):
if a == 0:
a = self.get_val()
self.l.append(a)
print('List : ',self.l)
def remove(self,a=0):
print('List : ',self.l)
if a == 0:
a = self.get_val()
self.l.remove(a)
print('List : ',self.l)
def disp(self):
print('List : ', self.l)
@staticmethod
def get_val():
return int(input('Enter the Integer data : '))
obj1 = Compute()
while True:
print('Enter 1 to ADD value inside the list')
print('Enter 2 to REMOVE values from the list')
print('Enter 3 to DISPLAY value of list')
print('Enter 4 to STOP EXECUTION')
choice = int(input('Enter your choice : '))
if choice == 1:
obj1.add()
elif choice == 2:
obj1.remove()
elif choice == 3:
obj1.disp()
elif choice == 4:
break
else:
print('Invalid choice') |
d4a5c92bad4b857244fe1ed1e9fdbabc44ccacdf | bibhore/CodingProblems | /Code/Problem7.py | 407 | 3.5 | 4 | import random
import time
class Problem7:
def printrandom(self):
for i in range(10):
print(random.randint(1,100))
time.sleep(random.randint(0,1))
def problem7(self):
starttime = time.time()
self.printrandom()
endtime = time.time()
print('Total elapsed time : '+str(endtime - starttime))
# problem7 = Problem7 ()
# problem7.problem7() |
b9f4cc226b76a68867de37727920a989c2b35280 | kars96/code | /py/pconcat.py | 1,412 | 4.09375 | 4 | from math import sqrt,floor
def SieveOfEratosthenes(prime,n):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
p=2
x=[]
while(p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
x.append(p)
# Update all multiples of p
for i in range(p * 2, n+1, p):
prime[i] = False
p+=1
lis =[]
# print(prime)
return prime
# Print all prime numbers
def isPrime(x):
for i in range(2,floor(sqrt(x))+1):
if(x%i == 0):
return False
return True
# driver program
if __name__=='__main__':
n = int(input())
# n=53
prime = [True for i in range(n+1)]
s=SieveOfEratosthenes(prime,n)
# print(s)
c=[]
count=0
q=list()
for i in range(2,len(prime)):
if prime[i]:
c.append(i)
# print(c)
for i in range(len(c)):
for j in range(len(c)):
if(isPrime(int(str(c[i])+str(c[j])))):
# print(int(str(c[i])+str(c[j])))
count+=1
q.append(int(str(c[i])+str(c[j])))
print(len(set(q)))
# print "Following are the prime numbers smaller",
# print "than or equal to", n
# SieveOfEratosthenes(n) |
53d8311ea0ed3e07ae18a4ed192a473f0ff24dbb | kars96/code | /py/nlp/stop_words.py | 273 | 3.5 | 4 | from nltk import word_tokenize
from nltk.corpus import stopwords
import string
s = []
while True:
sent = input()
if sent is None:
break
stop = stopwords.words('english') + list(string.punctuation)
s+=[i for i in word_tokenize(sent.lower()) if i not in stop]
print(s) |
cf7554340e039e9c317243a1aae5e5f9e52810f9 | IraPara08/raspberrypi | /meghapalindrom.py | 412 | 4.3125 | 4 | #Ask user for word
wordinput = input("Please Type In A Word: ")
#Define reverse palindrome
reverseword = ''
#For loop
for x in range(len(wordinput)-1, -1, -1):
reverseword = reverseword + wordinput[x]
#Print reverse word
print(reverseword)
#Compare
if wordinput == reverseword:
print("This is a palindrome!")
else:
print("This is not a palindrome:(")
#TA-DA
print("Ta-Da!")
|
c2b1be4c40a53648e5c2fe1f79b614b63b2287d0 | IraPara08/raspberrypi | /printfunction.py | 165 | 3.578125 | 4 | if __name__ == '__main__':
n = int(input())
outputstring = ''
for x in range(1, n + 1):
outputstring = outputstring + str(x)
print(outputstring)
|
951ce38c0f118938df7368aa1332a21bafc719f7 | pinkyba/NLP_Lab | /eng-upper-fsm/word.py | 120 | 3.53125 | 4 | string = "abcdefghijklmnopqrstuvwxyz"
print("-"+"\t"+"0")
for i in range(len(string)):
print(string[i]+"\t"+str(i+1))
|
c38bd5408534cfc084fbb40f956fca146f6834b5 | pinkyba/NLP_Lab | /word-segment-checker/word-seg-check1.py | 2,253 | 3.921875 | 4 | # How to run: python word-seg-check1.py ./test-data-for-word-segment-checker.txt > out
import sys
fileName = sys.argv[1]
f = open(fileName, "r")
fline = f.readlines()
for i in range(len(fline)):
# split words with space for first line
line1 = fline[i].split(" ")
# go to next line loop that is checked with line by line with first line
if i < len(fline) - 1:
start = i + 1
# loop one by one next line and split words with space
for j in range(start,len(fline)):
line2 = fline[j].split(" ")
for k in range(len(line1)):
for m in range(len(line2)):
# compare 1-gram and 2-gram between the two lines
if m < len(line2) - 1 and line1[k] == line2[m]+line2[m+1]:
print(line1[k]+" ======> "+line2[m]+" "+line2[m+1])
# compare 1-gram and 3-gram between the two lines
if m < len(line2) - 2 and line1[k] == line2[m]+line2[m+1]+line2[m+2]:
print(line1[k]+" ======> "+line2[m]+" "+line2[m+1]+" "+line2[m+2])
# compare 2-gram and 1-gram between the two lines
if k < len(line1) - 1 and line1[k]+line1[k+1] == line2[m]:
print(line1[k]+" "+line1[k+1]+" =====> "+line2[m])
# compare 2-gram and 2-gram between the two lines
if k < len(line1) - 1 and m < len(line2) - 1 and line1[k]+line1[k+1] == line2[m]+line2[m+1]:
print(line1[k]+" "+line1[k+1]+" =====> "+line2[m]+" "+line2[m+1])
# compare 2-gram and 3-gram between the two lines
if k < len(line1) - 1 and m < len(line2) - 2 and line1[k]+line1[k+1] == line2[m]+line2[m+1]+line2[m+2]:
print(line1[k]+" "+line1[k+1]+" =====> "+line2[m]+" "+line2[m+1]+" "+line2[m+2])
# compare with 3-gram/1-gram, 3-gram/2-gram, and 3-gram/3-gram
if k < len(line1) - 2 and line1[k]+line1[k+1]+line1[k+2] == line2[m]:
print(line1[k]+" "+line1[k+1]+" "+line1[k+2]+" =====> "+line2[m])
if k < len(line1) - 2 and m < len(line2) - 1 and line1[k]+line1[k+1]+line1[k+2] == line2[m]+line2[m+1]:
print(line1[k]+" "+line1[k+1]+" "+line1[k+2]+" =====> "+line2[m]+" "+line2[m+1])
if k < len(line1) - 2 and m < len(line2) - 2 and line1[k]+line1[k+1]+line1[k+2] == line2[m]+line2[m+1]+line2[m+2]:
print(line1[k]+" "+line1[k+1]+" "+line1[k+2]+" =====> "+line2[m]+" "+line2[m+1]+" "+line2[m+2])
|
4d78460a2561b60c3dd5261b52a30876fd0bac6e | ruchibaheti86/NumPy | /Filter NumPy.py | 500 | 3.796875 | 4 | import numpy as np
#Filter the array
arr = np.array([2,4,2,9,2])
print("Array: ",arr)
x = [False, False, True, False, True]
newarr = arr[x]
print("Filtered new array : ",newarr)
#Filteration of array in for and if command as well.
arr = np.array([100, 110, 120, 150, 180])
filterarr = []
for e in arr:
if e < 150:
filterarr.append(True)
else:
filterarr.append(False)
newarr = arr[filterarr]
print("Filter Array: ", filterarr)
print("New Array: ", newarr)
|
aa588a7dc6e82568306a9bb683ed685458c3c445 | stephengushue/Resplendent_Tiger | /guessanumber.py | 235 | 4.09375 | 4 | x = int(input('Pick a number between 2 and 10'))
if x == 1 or x > 10:
print('That is not what I asked.')
else:
print('Please hold while I calculate...')
while x < 10:
x += 1
print (str(x) + ' ...')
|
0db9f3ca1c2093216f167bb5aad6c57f57f09ae2 | PhysCdr/MobileRobotics2019 | /Solutions/HW1/solution/p1d.py | 347 | 3.5625 | 4 | import numpy as np
def ortho(m):
identity_m = np.identity(m.shape[0])
return np.allclose(np.matmul(m, m.T).flatten(), identity_m.flatten())
def main():
d = np.array([[2, 2, -1], [2, -1, 2], [-1, 2, 2]])/3
if ortho(d):
print('matrix', d, 'is orthogonal')
else:
print('matrix', d, 'is not orthogonal')
if __name__ == '__main__':
main() |
fa3fe1fcf7983483d2d0258097c0c8ef5716c0ef | domlockett/pythoncourse2018 | /homeworks/hw3/HW3_DL.py | 2,787 | 3.625 | 4 | ## pick a search criteria for groups, such as a zip code or a search term, like in class. Then answer the following with the returned results:
## 1. Which group is the most popular (i.e., has the most members)?
## 2. For this group, which member is the most active (i.e., belongs to the most groups)?
## 3. Considering only the most active user’s groups, which group is the most popular?
z
## *Functionalize your code. *Write succinct, informative comments
import imp
import os
import meetup.api
import operator
import time
#define a space **Do i HAVE to do this outside function
#in order to have it save into the local environment?
group_info = {}
names = []
stlgroups = []
size = []
ppl = []
active = []
orig = []
ids = []
groups = []
pop_groups= []
actguys_groups = []
cwd = os.getcwd()
cwd
client.RateLimit
## basic setup
client = meetup.api.Client("c263c01e0c15052545d6537316b")
meetup = imp.load_source('C:\Python27.14', 'C:\Python27.14\KEYS\meetup_KEY.py')
api = meetup.client
stlgroups = api.GetFindGroups({"zip" : "63116"})
##get the the names and sizes of both groups
def grab(groupList):
for group in groupList:
temp = group.urlname.encode('utf-8') # extract names to string
temp2 = group.members
names.append(temp)
size.append(temp2)
##Make a dictionary
grab(stlgroups)
grab(actguys_groups)
def genPop():#Most popular group on a general level from search
group_info = dict(zip(names, size))# make a disctionary
sorted_gi = sorted(group_info.items(), key=operator.itemgetter(1)) # use operator module to store key alongside value
top_group = api.GetMembers({"group_urlname": sorted_gi[-1][0]})#in ascending orders so grab 0 index-name from the last item in list
ppl.extend(top_group.__dict__["results"])##which member has most groups
print sorted_gi[-1][0]# return the most popular group
genPop()
def getGroups(membList):#grab all the people grab all their groups
for i in ppl:
ids.append(i['id'])
timebreak=True
while timebreak:#Rate limits on getgroups so
for i in ids:##collect the number of groups each member has
try:
groups.append((i,api.GetGroups({'member_id':str(i)}).meta['total_count'] ))
timebreak=False
except:
time.sleep(8)
continue
if len(groups)==200: break
getGroups(ppl)
def popular():
actguys_groups = api.GetGroups({'member_id' : max(groups,key=operator.itemgetter(1))[0]})# #get the most active member from the most popular group
for g in actguys_groups.results:
pop_groups.append((g['name'], g['members']))
print max(pop_groups,key=operator.itemgetter(1))#Group with most members in most popular guy of most popular groups
|
fed78ccbb8a565e936cacbac817485c26ab84383 | domlockett/pythoncourse2018 | /day03/exercise03_dl.py | 458 | 4.28125 | 4 | ## Write a function that counts how many vowels are in a word
## Raise a TypeError with an informative message if 'word' is passed as an integer
## When done, run the test file in the terminal and see your results.
def count_vowels(word):
vowels=('a','e','i','o','u')
count= 0
for i in word:
if type(word)!=str:
raise TypeError, "Make sure your input is a string."
if i in vowels:
count+=1
return count |
ec8a300f12f6fa3d081ec9b3831dcee4e23cf426 | rwbogl/n-queens | /queens.py | 5,184 | 4.09375 | 4 | import itertools
def n_queens(n):
"""Return a solution to the n-queens problem for an nxn board.
This uses E. Pauls' explicit solution, which solves n > 3.
A solution is possible for all n > 3 and n = 1.
Pauls' solution gives back 1-based indices, and we want 0-based, so all
points have an extra -1 from the original.
:n: A nonnegative integer.
:returns: A list of solutions, where the solutions are a list of 2-tuples
representing points, where the origin is in the upper-left of the
board, the positive x-axis to the right, and the positive y-axis
below.
[[(x0, y0), (x1, y1), ...], [(x'0, y'0), ...]]
"""
if n < 0:
raise ValueError("cannot place negative queens on a board")
if n == 0 or n == 2 or n == 3:
return []
fix = lambda x, y: (x - 1, y - 1)
mod = n % 6
if mod == 0 or mod == 4:
# n is even, so we may integer divide by 2.
A1 = [(2*k, k) for k in range(1, n//2+1)]
A2 = [(2*k - 1, n//2 + k) for k in range(1, n//2+1)]
return [fix(x, y) for (x, y) in A1 + A2]
elif mod == 1 or mod == 5:
# n is odd, so we may integer divide n - 1 by 2.
B1 = [(n, 1)]
B2 = [(2*k, k + 1) for k in range(1, (n-1)//2 + 1)]
B3 = [(2*k - 1, (n+1)//2 + k) for k in range(1, (n-1)//2 + 1)]
return [fix(x, y) for (x, y) in B1 + B2 + B3]
elif mod == 2:
# n is even, so we may integer divide by 2.
C1 = [(4, 1)]
C2 = [(n, n//2 - 1)]
C3 = [(2, n//2)]
C4 = [(n-1, n//2 + 1)]
C5 = [(1, n//2 + 2)]
C6 = [(n - 3, n)]
C7 = [(n - 2*k, k + 1) for k in range(1, n//2 - 2)]
C8 = [(n - 2*k - 3, n//2 + k + 2) for k in range(1, n//2 - 2)]
return [fix(x, y) for (x, y) in C1 + C2 + C3 + C4 + C5 + C6 + C7 + C8]
elif mod == 3:
return [fix(x, y) for (x, y) in [(n, n)] + n_queens(n - 1)]
return []
def n_queens_comb(n):
"""Return a solution to the n-queens problem for an nxn board.
This uses the combinatoric brute force solution.
:n: Nonnegative integer.
:returns: See n_queens().
"""
board = itertools.product(range(n), repeat=2)
is_good = True
for queens in itertools.combinations(board, n):
is_good = True
for point in queens:
effective = [q for q in queens if q != point]
if is_guarded(point, effective, n):
is_good = False
break
if is_good:
return queens
return []
def n_queens_bt(n):
"""Return a solution to the n-queens problem for an nxn board.
This uses the naive backtracking solution.
:n: A nonnegative integer.
:returns: See n_queens() for a description.
"""
queens = []
row, col = 0, 0
while len(queens) != n:
if not is_guarded((row, col), queens, n):
# This point is safe, so place a queen and start at the beginning
# of the next row.
queens.append((row, col))
row += 1
col = 0
else:
while col == n - 1:
# At the end of the current row; have to backtrack until we can
# place a new queen.
if row == 0:
# We went back to the first row and were at the end, so
# there are no solutions possible.
return []
row, col = queens.pop()
# We aren't at the end, so move to the next point.
col += 1
return queens
def is_guarded(point, queens, n):
"""Check if a given point is guarded by any queens in a given list.
A point is guarded iff there are any queens in `queens` that are on the
same row or column, or are on the same sum or difference diagonals.
:queens: A list of (row, col) points where queens are on the board.
:point: A (row, col) point to check.
:n: A nonnegative integer denoting the size of the board.
"""
# There are probably a couple different ways to do this.
#
# For now, this is the naive "look if any points that could attack us are
# in the list" method.
row, col = point
for queen in queens:
queen_row, queen_col = queen
# Check the rows and columns.
if queen_row == row or queen_col == col:
return True
# Check the sum and difference diagonals.
if (queen_row + queen_col == row + col or
queen_row - queen_col == row - col):
return True
return False
def check_solution(queens, n):
if (n == 2 or n == 3) and len(queens) == 0:
# n = 2, 3 has no solution.
return True
if len(queens) != n:
return False
for queen in queens:
split = [x for x in queens if x != queen]
if is_guarded(queen, split, n):
return False
return True
def print_solution(queens, n):
print("--"*n + "-")
for row in range(n):
for col in range(n):
print("|{}".format("Q" if (row, col) in queens else " "),
end="")
print("|\n" + "--"*n + "-")
|
b885e635046f49474bedc697135121f2e315e65c | cbppg/ML-NeuralNetwork | /main.py | 2,406 | 3.921875 | 4 | # -*- coding: utf-8 -*-
""" Qiu Zihao's homework of ML
Student ID: 141130077
Neural Network
"""
import numpy as np
# input layer -- 400 (d in book)
input_num = 400
# hidden layer -- 100 (q in book)
hidden_num = 100
# output layer -- 10 (l in book)
output_num = 10
# connection weights from input layer to hidden layer(v in book)
v = (np.random.random(size=(input_num, hidden_num))-0.5)/10
# connection weights from hidden layer to output layer(w in book)
w = (np.random.random(size=(hidden_num, output_num))-0.5)/10
# threshold of hidden layer(gama in book)
gama = np.zeros([1, hidden_num])
# threshold of output layer(theta in book)
theta = np.zeros([1, output_num])
# read in data
def readInData(datafile, labelfile):
dataMat = np.genfromtxt(datafile, delimiter=',', dtype=np.float)
labelMat = np.genfromtxt(labelfile, dtype=np.int)
return dataMat, labelMat
# sigmoid function
def sigmoid(x):
return 1.0/(1+np.exp(-x))
# calculate output
def calOutput(indata):
# input of the hidden layer unit
alpha = np.dot(v.T, indata)
# output of the hidden layer unit
b = sigmoid(alpha - gama)
# input of the output layer unit
beta = np.dot(b, w)
# output of the output layer unit
y = sigmoid(beta - theta)
return b, y
# calculate the gradient item g(in book)
def calG(output ,label):
return output*(1-output)*(label-output)
# calculate the gradient item e(in book)
def calE(b, g):
return b*(1-b)*sum(np.dot(g, w.T))
dataMat, labelMat = readInData('train_data.csv', 'train_targets.csv')
# return the i th label vector
def labelVector(i):
vec = np.zeros(10)
vec[labelMat[i]] = 1
return vec
# train the NN model
times = 16
step = 0.2
while (times > 0):
if times<8:
step = 0.1
print(times)
for i in range(dataMat.shape[0]):
data = dataMat[i]
b, y = calOutput(data)
g = calG(y, labelVector(i))
e = calE(b, g)
# renew the connection weights and threshold
w += step*(np.dot(b.T, g))
v += step*(np.dot(np.array([data]).T, e))
gama += -step*e;
theta += -step*g;
times -= 1
# get answer from the result vector
def getAnswer(result):
return np.argmax(result)
# start to test
testDataMat = np.genfromtxt('test_data.csv', delimiter=',', dtype=np.float)
outfile = open('test_predictions.csv', 'w')
for i in range(testDataMat.shape[0]):
no_use, result=calOutput(testDataMat[i])
ans = getAnswer(result[0])
outfile.write(str(ans)+'\n')
outfile.close()
|
9d49f2cc8e67a064ee7bc802a619794a7164a922 | hsj00/Python | /python 200/075.py | 1,662 | 3.609375 | 4 | # 075 char extract from specific position in string
# 076 string extract from specific range in string
# 077 oddth char extract from string
# 078 string reversing
# 079 string sum
# 080 string repeating
txt1 = 'A tale that was not right'
txt2 = '이것 또한 지나가리라'
# 075
print(txt1[5]) # 4번째 문자, 5 미만에서의 위치
print(txt2[-2]) # 뒤에서 두 번째 문자
# 076
print(txt1[3:7]) # 3 이상, 7 미만
print(txt1[:6]) # 처음부터 6 미만까지
print(txt2[-4:]) # 뒤에서 네 번째 문자부터 끝까지
# text print loop
txt = 'python'
for i in range(len(txt)): # 문자열 길이만큼 for문 반복
# 문자열 길이 +1을 해서 범위를 지정하여 문자열 출력 -> [a:b:c], a 이상 b 미만까지 c의 간격으로
print(txt[:i+1])
# 077 oddth char extracting
txt = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'
o_ret = txt[::2] # 0번째 문자부터 1칸 건너띄기
e_ret = txt[1::2] # 1번째 문자부터 1칸 건너띄기
print(o_ret)
print(e_ret)
# 078 reversing
ret01 = txt[::-1] # 처음부터 끝까지, 뒤에서부터
ret02 = txt[::-2] # 처음부터 끝까지, 뒤에서부터 1칸 건너띄며
ret03 = txt[-2::-2] # 뒤에서 두번째부터, 뒤에서부터 1칸 건너띄며
print(ret01)
print(ret02)
print(ret03)
# 079
filename = input('What is the file name?: ')
filename = filename + '.jpg'
display_msg = "That file name is <" + filename + ">."
print(display_msg)
# 080
msg01 = "Hey everyone!"
msg02 = "Hurry up!"
display_msg = msg01 + " " + (msg02 + " ")*3 + "!!"
print(display_msg)
|
5d1269355b68717992f38971bedb74877ab668ee | scientific-coder/josephus | /element-recursion/josephus.py | 728 | 3.578125 | 4 | from collections import deque
def find(chainlength = 40, kill = 3):
return findlast(deque(range(1,chainlength+1)),3,1)
def findlast(chain,nth,counter) :
if len(chain) == 1 :
return chain[0]
elif counter == 1 :
#print chain.popleft(), " dies"
chain.popleft()
return findlast(chain,nth,counter+1)
else :
head = chain.popleft()
#print head, " survives"
chain.append(head)
return findlast(chain,nth,1 if counter == nth else counter + 1)
print find()
import time
ITER = 100000
start = time.time()
for i in range(ITER):
find()
end = time.time()
print 'Time per iteration = %s microseconds (element recursive)' % ((end - start) * 1000000 / ITER)
|
ddbffa79e219713e4054839a07392898edf94e7a | Emiya2098212383/csy_try | /main.py | 938 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
# Filename : 01-string.py
# author by : Emiya
import csv
import os
# Global: Define file name & path
filename = 'test_write.csv'
csv_path = os.getcwd() + '\\csv_files\\' + filename
# Practice 1 - write
# write a row once
header_data = ["1行号", "2列名1", "3列名2"]
row_data = [1, '第1列数据', '第2列数据'] # data of a row
with open(csv_path, "w", encoding='utf8', newline='') as csvfile:
writer = csv.writer(csvfile)
#writer.writerow(header_data)
writer.writerow(row_data)
for i in range(10):
#writer.writerow(row_data)
writer.writerow(header_data)
# Practice 3 - get filed(cell)
with open(csv_path, "r", encoding='utf8') as csvfile:
reader = csv.reader(csvfile)
row_cnt = 0
for line in reader:
row_cnt += 1
print('第 %d 行, 行号是 %s, 第一列是 %s, 第二列是 %s' %
(row_cnt, line[0], line[1], line[2]))
|
85196830fe29ba9aabcfcd1712bbde6d3dd822e4 | ChingLingYeung/honoursProject | /test2.py | 1,912 | 3.796875 | 4 | # taken from https://codereview.stackexchange.com/questions/203319/greedy-graph-coloring-in-python
def color_nodes(graph):
# Order nodes in descending degree
nodes = sorted(list(graph.keys()), key=lambda x: len(graph[x]), reverse=True)
color_map = {}
for node in nodes:
available_colors = [True] * len(nodes)
for neighbor in graph[node]:
if neighbor in color_map:
color = color_map[neighbor]
available_colors[color] = False
for color, available in enumerate(available_colors):
if available:
color_map[node] = color
break
return color_map
def color_nodes_2(graph):
color_map = {}
# Consider nodes in descending degree
for node in sorted(graph, key=lambda x: len(graph[x]), reverse=True):
neighbor_colors = set(color_map.get(neigh) for neigh in graph[node])
color_map[node] = next(
color for color in range(len(graph)) if color not in neighbor_colors
)
return color_map
if __name__ == '__main__':
graph = {
'a': list('cefghi'),
'b': list('cefghi'),
'c': list('abefg'),
'd': list(''),
'e': list('abc'),
'f': list('abc'),
'g': list('abc'),
'h': list('ab'),
'i': list('ab')
}
print(color_nodes(graph))
# {'c': 0, 'a': 1, 'd': 2, 'e': 1, 'b': 2, 'f': 2}
# a messageTypes['FwdGetS'] = ['DirData0', 'DirData', "OwnData", "InvAck", "LastInvAck", "Inv"]
# b messageTypes['FwdGetM'] = ['DirData0', 'DirData', "OwnData", "InvAck", "LastInvAck", "Inv"]
# c messageTypes['Inv'] = ['DirData0', 'DirData', "OwnData", "FwdGetS", 'FwdGetM']
# d messageTypes['PutAck'] = []
# e messageTypes['DirData0'] = ['Inv', 'FwdGetS', 'FwdGetM']
# f messageTypes['DirData'] = ['Inv', 'FwdGetS', 'FwdGetM']
# g messageTypes['OwnData'] = ['Inv', 'FwdGetS', 'FwdGetM']
# h messageTypes['InvAck'] = ['FwdGetS', 'FwdGetM']
# i messageTypes['LastInvAck'] = ['FwdGetS', 'FwdGetM'] |
a295f7530513cc1fe389cb0026afac25c30e38c0 | ruvvet/texas-hold-em-python | /src/utils.py | 714 | 3.875 | 4 | INPUT_ERROR_INT = 'Must be an integer. Try again.'
INPUT_ERROR_STR = 'Must be either K, C, R, F. Try again.'
# Input validation
def input_num(message):
while True:
try:
user_input = int(input(message))
except ValueError:
print(INPUT_ERROR_INT)
continue
else:
return user_input
break
def input_str(message):
while True:
try:
user_input = str(input(message).upper())
if user_input not in ['K', 'C', 'R', 'F']:
raise ValueError
except ValueError:
print(INPUT_ERROR_STR)
continue
else:
return user_input
break
|
2074006981e41d2e7f0db760986ea31f6173d181 | ladas74/pyneng-ver2 | /exercises/06_control_structures/task_6_2a.py | 1,282 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Task 6.2a
Make a copy of the code from the task 6.2.
Add verification of the entered IP address.
An IP address is considered correct if it:
- consists of 4 numbers (not letters or other symbols)
- numbers are separated by a dot
- every number in the range from 0 to 255
If the IP address is incorrect, print the message: 'Invalid IP address'
The message "Invalid IP address" should be printed only once,
even if several points above are not met.
Restriction: All tasks must be done using the topics covered in this and previous chapters.
"""
ip = input('Введите IP адрес: ')
#ip = '10.1.16.50'
ip_list = ip.split('.')
correct_ip = False
if len(ip_list) == 4:
for oct in ip_list:
if oct.isdigit() and 0 <= int(oct) <= 255: #in range(256) вместо 0 <= int(oct) <= 255
correct_ip = True
else:
correct_ip = False
break
if correct_ip:
oct1 = ip_list[0]
if 1 <= int(oct1) <= 223:
print("unicast")
elif 224 <= int(oct1) <= 239:
print("multicast")
elif ip == '255.255.255.255':
print("local broadcast")
elif ip == '0.0.0.0':
print("unassigned")
else:
print("unused")
else:
print('Invalid IP address')
|
27cc3bbaffff82dfb22f83be1bcbd163ff4c77f1 | ladas74/pyneng-ver2 | /exercises/05_basic_scripts/task_5_1.py | 1,340 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Task 5.1
The task contains a dictionary with information about different devices.
In the task you need: ask the user to enter the device name (r1, r2 or sw1).
Print information about the corresponding device to standard output
(information will be in the form of a dictionary).
An example of script execution:
$ python task_5_1.py
Enter device name: r1
{'location': '21 New Globe Walk', 'vendor': 'Cisco', 'model': '4451', 'ios': '15.4', 'ip': '10.255.0.1'}
Restriction: You cannot modify the london_co dictionary.
All tasks must be completed using only the topics covered. That is, this task can be
solved without using the if condition.
"""
name_switch = input('Введите имя устройства: ')
london_co = {
"r1": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "4451",
"ios": "15.4",
"ip": "10.255.0.1",
},
"r2": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "4451",
"ios": "15.4",
"ip": "10.255.0.2",
},
"sw1": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "3850",
"ios": "3.6.XE",
"ip": "10.255.0.101",
"vlans": "10,20,30",
"routing": True,
},
}
print(london_co[name_switch]) |
b25fd7a616e2d5e6aa54f228f327f6f885af7b17 | dkushche/Crypto | /crypto_tools/math_tools.py | 1,292 | 3.671875 | 4 | """ Math Tools
Some general math tools that can help with numbers)
"""
import math
import random
def EGCD(a, b):
"""
Extended Euclidean algorithm
computes common divisor of integers a and b.
a * x + b * y = gcd(a, b)
returns gcd, x, y or gcd, y, x.
Sorry, I can't remember
"""
if a == 0:
return (b, 0, 1)
b_div_a, b_mod_a = divmod(b, a)
g, x, y = EGCD(b_mod_a, a)
return (g, y - b_div_a * x, x)
def inverse_modulo_numb(determ, modulo):
g, x, _ = EGCD(determ, modulo)
if g != 1:
return pow(determ, modulo - 2, modulo)
return x % modulo
def is_perfect_square(num):
if num <= 0:
return False
square = int(math.sqrt(num))
return square ** 2 == num
def is_prime(num):
if num < 0:
raise ValueError(f"Can't check is prime negative value {num}")
if num < 2 or num == 4:
return False
if num < 4:
return True
for i in range(2, num // 2):
if num % i == 0:
return False
return True
def get_coprime(value):
coprime = random.randint(2, value - 1)
gcd, _, _ = EGCD(value, coprime)
while gcd != 1:
coprime = random.randint(2, value - 1)
gcd, _, _ = EGCD(value, coprime)
return coprime
|
9fdb382bce23404a286b430d5c77edf4453af378 | Andreasdahlberg/advent-of-code-2018 | /day 9/marble.py | 1,290 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*
import re
from blist import blist
def get_answer(number_of_players, number_of_marbles):
scores = [0 for i in range(number_of_players)]
circle = blist([0])
current_marble_index = 0
marble_value = 1
while marble_value < number_of_marbles + 1:
if marble_value % 23 == 0:
player_index = marble_value % number_of_players
scores[player_index] += marble_value
tmp_i = (len(circle) + current_marble_index - 7) % len(circle)
scores[player_index] += circle[tmp_i]
del circle[tmp_i]
current_marble_index = tmp_i
else:
if len(circle) > 0:
if (current_marble_index + 2) == len(circle):
i = current_marble_index + 2
else:
i = (current_marble_index + 2) % (len(circle))
else:
i = 1
circle.insert(i, marble_value)
current_marble_index = i
marble_value += 1
scores.sort()
return scores[-1]
def _main():
print('Part 1 answer: {}'.format(get_answer(418, 71339)))
print('Part 2 answer: {}'.format(get_answer(418, 7133900)))
return 0
if __name__ == '__main__':
exit(_main())
|
53975d40690fcd19925011d4b527465a55d37806 | mendelson/neoway-challenge | /customLib/DataImputer.py | 6,961 | 3.578125 | 4 | import pandas as pd
import math
import numpy as np
from tqdm import tqdm
from sklearn.impute import KNNImputer
# DataImputer: performs Nearest Neighbor Imputation on
# the input_df variable.
class DataImputer():
def __init__(self, input_df):
"""
This constructor initializes the internal DataFrame performing the
necessary pre-processing.
Args:
input_df (DataFrame): the original DataFrame dataset.
"""
self.__batch_size = 10000
# Shuffling data
self.__df = input_df.sample(frac=1).copy()
self.__pre_proc_df()
# self.__n_neighbors = int(math.sqrt(self.__df.dropna(axis=0).shape[0]))
self.__n_neighbors = int(math.sqrt(self.__batch_size))
def impute(self):
"""
This method performs the Nearest Neighbor Imputation.
"""
batches = self.__get_batches()
# return batches
# The weight parameter was set to distance in order to increase the influence of closer elements
imputer = KNNImputer(n_neighbors=self.__n_neighbors, weights='distance')
df = pd.DataFrame(columns=list(self.__df.columns))
print('Performing imputations...')
for batch in tqdm(batches):
data = imputer.fit_transform(batch.drop(['name'], axis=1))
batch.iloc[:, 1:] = data
df = pd.concat([df, batch])
self.__update_df(df)
def get_data(self):
"""
This method transforms the full dataset back to the original
format as in the .csv files and returns the dataframe.
Returns:
DataFrame: the transformed DataFrame as in the .csv format
"""
self.__get_readable_df()
for col in self.__df:
if (self.__df[col].dtype != 'object' and col != 'IMC') or col == 'name':
self.__df[col] = self.__df[col].astype('int32')
return self.__df
# Private methods
def __pre_proc_df(self):
"""
This method performs the pre-processing steps on the dataset, i.e.,
normalization and categorical values manipulation.
"""
self.__norm_params = {}
self.__str_and_num = {}
self.__categorical_cols = []
for col in self.__df.columns:
if col != 'name':
if self.__df[col].dtype != 'object':
self.__col_minmax_norm(col)
else:
self.__categorical_cols.append(col)
self.__categorical_to_num(col)
self.__col_minmax_norm(col)
def __col_minmax_norm(self, col):
"""
This method performs the min-max normalization method.
Args:
col (str): the name of the column to be normalized in the
self.__df DataFrame
"""
maxim = self.__df[col].max()
minim = self.__df[col].min()
self.__norm_params[f'max_{col}'] = maxim
self.__norm_params[f'min_{col}'] = minim
self.__df[col] = (self.__df[col] - minim)/(maxim - minim)
def __categorical_to_num(self, col):
"""
This method converts categorical values to a numeric value (not fit for
predictions, only for imputation).
Args:
col (str): the name of the column to be processed in the
self.__df DataFrame
"""
original_values = list(self.__df[col].unique())
original_values.remove(np.nan)
for idx, original_value in enumerate(original_values):
self.__str_and_num[f'{col}_{original_value}'] = float(idx)
self.__str_and_num[f'{col}_{idx}.0'] = original_value
self.__str_and_num[f'{col}_{np.nan}'] = np.nan
self.__str_and_num[f'{col}_{np.nan}'] = np.nan
self.__df[col] = self.__df[col].apply(lambda x: self.__str_and_num[f'{col}_{x}'])
def __num_to_categorical(self, col):
"""
This method converts numeric values to its categorical value.
Args:
col (str): the name of the column to be processed in the
self.__df DataFrame
"""
self.__df[col] = self.__df[col].apply(lambda x: self.__str_and_num[f'{col}_{x}'])
def __get_readable_df(self):
"""
This method transforms the dataset back to human-readable values.
"""
for col in self.__df.columns:
if col != 'name':
if col not in self.__categorical_cols:
self.__denorm_data(col)
else:
self.__denorm_data(col, True)
self.__num_to_categorical(col)
def __denorm_data(self, col, round_values=False):
"""
This method reverts the min-max normalization process back to its original values.
Args:
col (str): the name of the column to be processed in the
self.__df DataFrame
round_values (bool): indicates if the reconstructed values should
be rounded (used for categorical columns)
"""
maxim = self.__norm_params[f'max_{col}']
minim = self.__norm_params[f'min_{col}']
if round_values:
self.__df[col] = (self.__df[col]*(maxim - minim) + minim).round()
else:
self.__df[col] = self.__df[col]*(maxim - minim) + minim
def __get_batches(self):
"""
This method splits the dataset into batches of max size self.__batch_size
in order to speed up the KNN Imputation process.
Returns:
list: the list of DataFrame batches
"""
train_df = self.__df.dropna(axis=0).copy()
missing_df = self.__df[self.__df.isna().any(axis=1)].copy()
batches = []
start = 0
end = int(start + self.__batch_size/2)
while start < missing_df.shape[0]:
batches.append(pd.concat([train_df[start:end].copy(), missing_df[start:end].copy()]))
start = end
end += int(self.__batch_size/2)
return batches
def __update_df(self, df):
"""
This method receives the imputed data frame and uses it to update self.__df. This is
necessary because not all the rows are used in the imputation process, so not all
original rows are present in the imputed DataFrame.
Args:
df (DataFrame): the imputed DataFrame.
"""
present = list(df['name'])
to_be_checked = list(self.__df['name'])
to_be_added = np.setdiff1d(to_be_checked, present)
to_add = self.__df[self.__df['name'].isin(to_be_added)]
df = pd.concat([df, to_add])
self.__df = df
|
82c2f3952589113e474b80916a2d5e1175da0403 | Bunnycakes62/Machine-Learning | /PopArt/PopArt.py | 2,321 | 3.734375 | 4 | # Task 1 (Creating a popart and compressible version of a colour image):
# Using either imageio or pillow to upload an image. read a colour image of your choosing or this default image (Links to an external site.).
# Please submit the image that you chose if not the default. Code could be:
# from imageio import imread
# im = imread(filename)
# from PIL import Image
# import numpy as np
# image = Image.open(filename)
# im = np.array(image)
# Each x and y pixel in the image should have 3 values corresponding to red green and blue values.
# Stack the pixels to create a dataset of shape (width*height, 3)
# Applying Kmeans to this dataset with k = 5, assigns each pixel to one of 5 centroids.
# Each of the five centroids corresponds to a colour.
# Plot the grayscale image of the indices of the pixel to centroid.
# Plot the colour image of the pixel mapped to their centroid.
# Plot the same images with k=10.
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
filename = 'supermarket.jpg'
image = Image.open(filename)
im = np.array(image)
reshaped = im.reshape(im.shape[0]*im.shape[1], 3)
plt.imshow(im)
plt.show()
# kmeans cluster for k = 5
kmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init=10, random_state=0)
# Plot clusters to pixel data
grayImage = np.array(Image.open(filename).convert('LA'))
labels = kmeans.fit(reshaped).labels_
popImage = kmeans.cluster_centers_[labels].astype(int)
plt.scatter(grayImage[:, 0], grayImage[:, 1])
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1])
plt.title('k = 5')
plt.show()
# show color-mapped image
mapped = popImage.reshape(im.shape[0], im.shape[1], 3)
plt.imshow(mapped)
plt.show()
# kmeans cluster for k = 10
kmeans10 = KMeans(n_clusters=10, init='k-means++', max_iter=300, n_init=10, random_state=0)
# Plot clusters to pixel data
labels = kmeans10.fit(reshaped).labels_
popImage = kmeans10.cluster_centers_[labels].astype(int)
plt.scatter(grayImage[:, 0], grayImage[:, 1])
plt.scatter(kmeans10.cluster_centers_[:, 0], kmeans10.cluster_centers_[:, 1])
plt.title('k = 10')
plt.show()
# show color-mapped image
mapped = popImage.reshape(im.shape[0], im.shape[1], 3)
plt.imshow(mapped)
plt.show()
|
ba34b9016a7fd98af0ac47527e73fd4d3671ae0f | eileen-b/example-code-2e | /10-dp-1class-func/strategy.py | 2,825 | 3.5625 | 4 | # strategy.py
# Strategy pattern -- function-based implementation
"""
# tag::STRATEGY_TESTS[]
>>> joe = Customer('John Doe', 0) # <1>
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermelon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo) # <2>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo) # <3>
<Order total: 30.00 due: 28.50>
>>> big_cart = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, big_cart, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# end::STRATEGY_TESTS[]
"""
# tag::STRATEGY[]
import typing
from typing import Sequence, Optional, Callable
class Customer(typing.NamedTuple):
name: str
fidelity: int
class LineItem:
def __init__(self, product: str, quantity: int, price: float):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
class Order: # the Context
def __init__(
self,
customer: Customer,
cart: Sequence[LineItem],
promotion: Optional[Callable[['Order'], float]] = None,
) -> None:
self.customer = customer
self.cart = list(cart)
self.promotion = promotion
def total(self) -> float:
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
return self.__total
def due(self) -> float:
if self.promotion is None:
discount = 0.0
else:
discount = self.promotion(self) # <1>
return self.total() - discount
def __repr__(self):
return f'<Order total: {self.total():.2f} due: {self.due():.2f}>'
# <2>
def fidelity_promo(order: Order) -> float: # <3>
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(order: Order):
"""10% discount for each LineItem with 20 or more units"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * 0.1
return discount
def large_order_promo(order: Order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0
# end::STRATEGY[]
|
d899082e889a05cfc8d4ed698086eb857e949162 | supriyaprasanth/test | /strings and lists/word_sorting.py | 122 | 3.890625 | 4 | str = raw_input("Enter some words seperated using , : ")
words = str.split(",")
words.sort()
for i in words:
print(i) |
518b6613fdaf2b43de899242f803a3340d86afd5 | supriyaprasanth/test | /Exam/binary_search.py | 788 | 4.0625 | 4 | # to do binary search
n=input("enter the number of elements : ") # to get the number of elements
item = []
for i in range(0,n): #to accept the elements of the list
a = input("enter the items : ")
item.append(a)
print item
ele = input("Enter the element to be searched :") # to accept the element to be searched
first = item[0]
last = item[n-1]
if n%2 == 0: #to find the middle element of the list
mid = n / 2
else:
mid = (n-1) / 2
if ele == item[mid]:
print "element found at index %d" %(mid+1)
elif ele < item[mid]:
for i in range(0,mid-1):
if ele == item[i]:
print "element found at index %d" %(i+1)
elif ele >item[mid]:
for i in range(mid,n):
if ele == item[i]:
print "element found at index %d" %(i+1)
|
44f9711729238bc3fc3e59cd7b85f09705ab3b18 | supriyaprasanth/test | /9_july/test1.py | 1,142 | 4.0625 | 4 | from Exam import random
words = ['kerala','karnataka','pune','delhi','punjab',]
word = random.choice(words)
leng = len(word)
count =0
chances = 9
l_guessed = []
x = ""
y= True
def word_update(x,word, l_guessed):
for letter in word:
if letter in l_guessed:
x += letter
else: x += " _ "
print "The word is :", x
return x
print "Guess the Indian State"
while(y):
letter = raw_input("Enter a letter : ").lower()
if letter in l_guessed:
print "you already entered the letter"
else:
l_guessed.append(letter)
chances-=1
count+=1
print " %d more tries left" % (chances)
if count == leng:
x = False
break
word_update(x, word, l_guessed)
'''while chances >= 0:
letter = raw_input("Enter a guess: ").lower()
if letter in l_guessed:
print "\nYou have already said that!!!\n"
else:
l_guessed.append(letter)
chances = chances - 1
if x == word:
print ("tries over")
break
print " %d more tries left" % (chances)
word_update(x,word, l_guessed)
'''
|
09db1390181a162563845f139d31f47127355021 | wuhuliang/leecode | /car.py | 213 | 3.546875 | 4 | class User(object):
def __init__(self,first_name,last_name):
self.FN = first_name
self.LN= last_name
def describe(self):
print ('The username is: ' + str(self.FN) + str(self.LN))
|
d17eb4bc9a1bb627e47b6025378ec33869652d55 | dorismoisuc/Programming-Fundamentals | /Assignment3-4/ui.py | 7,884 | 3.734375 | 4 | from model import *
from copy import *
from undo import *
#reads the real part and the imaginary part of the complex number
def readComplex():
realPart = int(input(" ⁂ real part:"))
complexPart = int(input(" ⁂ complex part:"))
return createComplex(realPart,complexPart)
#creates the list of the complex numbers
def createComplexList(listc):
inputString = ''
print(" ⋆ Insert a real part and a complex part:")
print(" ⋆ Type 'done' to finish inserting")
while inputString != 'done':
inputString = input("** ")
if inputString != 'done':
try:
listc.append(readComplex())
except ValueError:
print(" ✁ Invalid input. Retry")
#inserts a complex number at a certain position
def insertNumber(listc):
position = int(input(" ⋆ Enter the position "))
if position > len(listc):
raise Exception("The position is not in the list. Try again")
else:
position = position + 1
realPart = int(input(" ⁂ real part:"))
imaginaryPart = int(input(" ⁂ complex part:"))
complexInsert = createComplex(realPart,imaginaryPart)
listc.insert(position,complexInsert)
#removes a complex number from a certain single position
def removeSingle(listc):
position=int(input(" ⋆ The position you want to remove is: "))
if position > len(listc):
raise Exception("The position is not in the list. Try again")
else:
del listc[position]
#removes more than 1 complex number from given positions
def removeMore(listc):
startPosition = int(input(" ⋆ The start position for removal is: "))
endPosition = int(input(" ⋆ The end position for removal is: "))
if int(endPosition) > len(listc):
raise Exception(" ⋆ The end position doesn't exist in this list. Try again")
else:
endPosition = endPosition + 1
del listc[startPosition:endPosition]
#replaces a complex number
def replace(listc):
realOld = int(input(" ⋆ The real part of the complex number you want to replace is:"))
imaginaryOld = int(input(" ⋆ The imaginary part of the complex number you want to replace is: "))
realNew = int(input(" ⋆ The real part of the replacement is: "))
imaginaryNew = int(input(" ⋆ The imaginary part of the replacement is: "))
for it in range (0,len(listc)):
#print ("the real part is ",getReal(listc[it]))
#print ("the imaginary part is ",getImaginary(listc[it]))
#print ("realOld ",realOld)
#print ("imagOld ", imaginaryOld)
#print ("realNew ",realNew)
#print ("imaginaryNew ", imaginaryNew)
if getReal(listc[it]) == realOld and getImaginary(listc[it]) == imaginaryOld:
setReal(listc[it],realNew)
setImaginary(listc[it],imaginaryNew)
#lists the complex numbers with no imaginary part
#from a start position to an end position
def listReal(listc):
startPoz = int(input(" ⋆ List real numbers from: "))
endPoz = int(input("To: "))
if int(endPoz) > len(listc):
raise Exception(" ⋆ The end position doesn't exist in this list. Try again")
else:
endPoz = endPoz + 1
for it in range(startPoz,endPoz):
#print ("the imaginary part is ",getImaginary(listc[it]))
#print ("the real part is ",getReal(listc[it]))
if (getImaginary(listc[it]) == 0):
print (getReal(listc[it]))
#gets the modulus of the complex number
def getModulus(listc):
return (getReal(listc)**2 + getImaginary(listc)**2)**0.5
#prints the list of complex numbers which have the modulus equal to an input modulus
def listModuloEq(listc):
eqModulo = int(input(" ⋆ List complex numbers which have the mod equal to:"))
for it in range(0,len(listc)):
if getModulus(listc[it]) == eqModulo:
print (str(getReal(listc[it])) + '+' + str(getImaginary(listc[it])) + 'i')
#prints the list of complex numbers which have the modulus more little than an input modulus
def listModuloLittle(listc):
eqModulo = int(input(" ⋆ List complex numbers which have the mod more little than:"))
for it in range(0,len(listc)):
if getModulus(listc[it]) < eqModulo:
print (str(getReal(listc[it])) + '+' + str(getImaginary(listc[it])) + 'i')
#prints the list of complex numbers which have the modulus bigger than an input modulus
def listModuloBigger(listc):
eqModulo = int(input(" ⋆ List complex numbers which have the modulo bigger than:"))
for it in range(0,len(listc)):
if getModulus(listc[it]) > eqModulo:
print (str(getReal(listc[it])) + '+' + str(getImaginary(listc[it])) + 'i')
def suma(listc):
startPos = int(input("The start pos of the sum is: "))
endPos = int(input("The end pos: "))
sum = 0
if endPos > len(listc):
raise Exception("The end pos is not in the list")
else:
endPos = endPos + 1
for it in range(startPos,endPos):
sum = sum + getReal(listc[it]) + getImaginary(listc[it])
print ("The sum is: ",sum)
def product(listc):
startPos = int(input("The start pos of the product is: "))
endPos = int(input("The end pos: "))
prod = 1
if endPos > len(listc):
raise Exception("The end pos is not in the list")
else:
endPos = endPos + 1
for it in range(startPos,endPos):
prod = prod * getReal(listc[it]) * getImaginary(listc[it])
print ("The product is: ",prod)
def filterReal(listc):
if len(listc) ==0:
raise Exception("The list is empty")
for it in range(len(listc)-1, -1, -1):
if getImaginary(listc[it]) !=0:
del listc[it]
def filterModl(listc):
if len(listc) ==0:
raise Exception("The list is empty")
theVal = int(input("The value the modulus is < than: "))
for it in range(len(listc)-1,-1,-1):
if getModulus(listc[it]) > theVal:
del listc[it]
def filterMode(listc):
if len(listc) ==0:
raise Exception("The list is empty")
theVal = int(input("The value the modulus is equal to: "))
for it in range(len(listc)-1,-1,-1):
if getModulus(listc[it]) != theVal:
del listc[it]
def filterModg(listc):
if len(listc) ==0:
raise Exception("The list is empty")
theVal = int(input("The value the modulus is > than: "))
for it in range(len(listc)-1,-1,-1):
if getModulus(listc[it]) < theVal:
del listc[it]
def undoOp(listH):
listH.pop()
def run():
listc = [[1,2],[3,4],[5,6],[0,1],[1,0],[2,3],[4,5],[5,0],[1,1],[2,3],[5,6]]
listH=[]
copyL=[]
commands = {
"list": printThelist,
"add": createComplexList,
"insert": insertNumber,
"removeOne": removeSingle,
"removeMany": removeMore,
"replace": replace,
"listReal":listReal,
"listEqualMod":listModuloEq,
"listLittleMod":listModuloLittle,
"listBiggerMod":listModuloBigger,
"sum":suma,
"product":product,
"filterReal":filterReal,
"filterModL":filterModl,
"filterModE":filterMode,
"filterModG":filterModg,
"undo":undoOp
}
while True:
cmd = input("*")
if cmd == "exit":
return
if cmd in commands:
try:
commands[cmd](listc)
except Exception as ex:
print(str(ex))
else:
print ("non-existent command!")
|
Subsets and Splits