blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
022e48b480452645c386a294d061efbeea9dc027
|
pofin/Crypto-Final-Project
|
/final/crypto/mac.py
| 885 | 3.5625 | 4 |
class Mac:
""" Generic interface for all MAC algorithms. """
@classmethod
def get_name(self):
"""
Returns:
A unique name for this MAC algorithm. """
raise NotImplementedError("get_name() must be implemented by subclass.")
def get_length(self):
"""
Returns:
The length in characters of the MAC produced by this instance. """
raise NotImplementedError("get_length() must be implemented by subclass.")
def generate(self, data):
""" Generates a new MAC.
Args:
data: The message to generate the MAC for.
Returns:
The generated MAC, as a string. """
raise NotImplementedError("generate() must be implemented by subclass.")
def set_key(self, key):
""" Sets a new key to use for the MAC.
Args:
key: The new key to set. """
raise NotImplementedError("set_key() must be implemented by subclass.")
|
0300b703a046069d6f8ce39cf9e1f5f04683266a
|
lexraye/python_files
|
/fundamentals/fundamentals/for_loop_basic1.py
| 1,007 | 3.75 | 4 |
# print all integers from 0 to 150
for x in range(0, 151):
print(x)
# print all the multiples of 5 from 5 to 1,000
for x in range(5, 1001, 5):
print(x)
# print integers 1 to 100. if divisible by 5 print Coding if divisible by 10 print Dojo
for x in range(1, 101):
if x % 10 == 0:
print('Coding Dojo')
elif x % 5 == 0:
print('Coding')
else:
print(x)
# add odd integers from 0 to 500,000, and print the final sum
total = 0
for x in range(0, 500001):
if(not (x % 2) == 0):
total += x
print(total)
# print positive numbers starting at 2018, counting down by fours
for x in range(2018, 0, -4):
print(x)
# set three variables: lowNum, highNum, mult. Starting at lowNum and going through
# highNum, print only the integers that are a multiple of mult. For example, if
# lowNum=2, highNum=9, and mult=3, the loop should print 3, 6, 9
lowNum = 1
highNum = 100
mult = 3
for x in range(lowNum, highNum):
if(x % mult == 0):
print(x)
|
a7fdf346dba1559d16584e8dd222dd03eaeede5a
|
AustinPenner/ProjectEuler
|
/Problems 26-50/euler042.py
| 652 | 3.78125 | 4 |
def is_triangle(word):
alphabet = ['','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
letter_sum = 0
for letter in word:
letter_sum += alphabet.index(letter)
# Triangle numbers:
# n = x*(x+1)/2
# 2*n = x^2+x
# 0 = x^2+x-2*n
# Quadratic formula:
x = (-1+(1+4*2*letter_sum)**.5)/2
return x.is_integer()
with open("euler042_words.txt", "r") as file:
line = file.readline()
line = line.replace("\"","")
line = line.split(",")
# Loop through each word, add 1 if it's a triangle number
count = 0
for word in line:
if is_triangle(word):
count += 1
print count
# Answer is: 162
|
914351c70d36b23df2ac1811b16ff77bd02a1d51
|
CosmiX-6/Library-Management-System-CLI
|
/validator.py
| 3,134 | 3.6875 | 4 |
def checkstring(value):
restrict='1234567890!@#$%^&*()-_+=} {:][|\"\'\\|/?.><,'
for i in value:
flag=True
if i in restrict:
print('Invalid character used in name.')
flag=False
break
return flag
def checkpass(value):
restrict='-][,\)('
for i in value:
flag=True
if i in restrict:
print('Invalid character used in name.')
flag=False
break
return flag
def entry(title,vtype,ttype,size):
if vtype=='char':
value=input(title+' : ').strip()
if len(value)<3 or len(value)>size:
print('Invalid size, '+title+' must be 3 to '+str(size))
return None
elif checkstring(value):
return value.capitalize()
else:
return None
elif vtype=='string':
value=input(title+' : ').strip()
if len(value)<4 or len(value)>size:
print('Invalid size, '+title+' must be 4 to '+str(size))
return None
else:
return value.title().replace(' ','_')
elif vtype=='email':
value=input(title+' : ').strip()
if len(value)<10 or len(value)>size:
print('Invalid size, '+title+' must be 10 to '+str(size))
return None
elif '@' not in value:
print('Invalid '+title+' \'@\' missing.')
return None
else:
if value[value.find('@'):].count('.')==1:
if len(value[value.find('@'):][value[value.find('@'):].find('.'):]) >=3:
return value.lower()
else:
print('Invalid Domain.')
return None
elif vtype=='int' and ttype=='user':
value=int(input(title+' : '))
if len(str(value))==10:
return value
del title,vtype,ttype,size
else:
print('Invalid contact no.')
return None
elif vtype=='int' and ttype=='book':
if size==2:
value=int(input(title+' : '))
if value>0 and value<100:
return value
else:
print('Book limit exceed.')
return None
else:
value=int(input(title+' : '))
if len(str(value))>=9 and len(str(value))<=size:
return value
else:
print('ISBN error.')
return None
elif vtype=='select' and ttype=='user':
print('1 Student\n2 Staff')
choice=input('Enter a choice : ')
if choice=='1':
return 'Student'
elif choice=='2':
return 'Staff'
else:
return None
elif vtype=='select' and ttype=='book':
print('1 Reserved\n2 Non Reserved')
choice=input('Enter a choice : ')
if choice=='1':
return 'rserv'
elif choice=='2':
return 'nores'
else:
return None
else:
print('Invalid operation. Please restart ')
|
ae718cc60a1df4142f44e10e38ce7b7f48b6e0dc
|
j3nnn1/pyj3nnn1
|
/tarea02/exercise04.py
| 1,166 | 3.859375 | 4 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
4- Crear una clase que procese la edad de una persona
y a traves de metodos verifique, retornando booleanos,
si pertenece a estos grupos de edad y ademas, pueda ser
modificada y luego revisar otra vez
- 0 a 10
- 11 a 20
- 21 a 40
- 41 a 60
- Mayor de 60
"""
class age:
def __init__(self,edad=0):
self.edad=edad
def setedad(self,edad):
self.edad=edad
def getedad(self):
return self.edad
def verifyedad10(self):
if self.edad>=0 and self.edad<10:
result=True
else:
result=False
return result
def verifyedad20(self):
if self.edad>10 and self.edad<20:
result=True
else:
result=False
return result
def verifyedad40(self):
if self.edad>20 and self.edad<40:
result=True
else:
result=False
return result
def verifyedad60(self):
if self.edad>40 and self.edad<60:
result=True
else:
result=False
return result
def verifyedadmore60(self):
if self.edad>=60:
result=True
else:
result=False
return result
|
b96c1029e73b208079fc8d006eba187e956df9ca
|
DaminduSandaruwan/LearnPython
|
/Variables.py
| 495 | 3.828125 | 4 |
num = 5
print(id(num)) #print address of num
name ='Damindu'
print(id(name)) #print address of name
a = 10
b = a
print(id(a)) #1938475072
print(id(b)) #1938475072
# address are same because b = a; in python
print(id(10)) #1938475072 address is based on box it self
k = 10
print(id(k)) #1938475072
a=9
print(id(a)) #1938475056
print(id(b)) #1938475072
k = a
print(id(k)) #1938475056 same as address of (a)
b = 8
print(id(b)) #1938475040
PI= 3.14
print(type(PI)) #<class 'float'>
|
b93c5aebcac957b210e675856e97bf2ef14590d5
|
daniel-reich/ubiquitous-fiesta
|
/7Y2C8g3fXXyK2R9Bn_3.py
| 1,364 | 3.578125 | 4 |
def keyword_cipher(key, message):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z']
value_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12,
'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23,
'x': 24, 'y': 25, 'z': 26}
removed_keys = []
dupe_keys = []
lower_key = key.lower()
final_keys = []
lower_message = message.lower()
for letter in lower_key:
if letter not in removed_keys:
try:
alphabet.remove(letter)
removed_keys.append(letter)
except KeyError:
print("Key not in alphabet")
for letter in lower_key:
if letter not in dupe_keys:
final_keys.append(letter)
dupe_keys.append(letter)
final_keys = final_keys[::-1]
for letter in final_keys:
alphabet.insert(0, letter)
output_string = ""
for letter in lower_message:
if letter in alphabet:
output_string = output_string + alphabet[value_dict[letter]-1]
else:
output_string = output_string + letter
return output_string.lower()
|
8a8be9d06bf0c0984f7fbf5c6956f29d7bd6dc32
|
jayant92/tictactoe
|
/tictac.py
| 3,194 | 3.921875 | 4 |
import random
def display_board(board):
print("\n"*100)
print(board[7]+"|"+board[8]+"|"+board[9])
print(board[4]+"|"+board[5]+"|"+board[6])
print(board[1]+"|"+board[2]+"|"+board[3])
def player_input():
marker = ""
while marker!="X" and marker != "O":
marker = input("Player One: Choose X or O: ").upper()
if marker == "X":
return ("X","O")
else:
return("O","X")
def place_marker(board,marker,position):
board[position] = marker
def win_check(board,mark):
return(
(board[7]==board[8]==board[9]==mark)or
(board[4]==board[5]==board[6]==mark)or
(board[1]==board[2]==board[3]==mark)or
(board[1]==board[4]==board[7]==mark)or
(board[2]==board[5]==board[8]==mark)or
(board[3]==board[6]==board[9]==mark)or
(board[1]==board[5]==board[9]==mark)or
(board[3]==board[5]==board[7]==mark)
)
def choose_first():
flip = random.randint(0,1)
if flip == 0:
return "Player 1"
else:
return "Player 2"
def space_check(board,position):
return board[position] == ""
def full_board_check(board):
for i in range(1,10):
if space_check(board,i):
return False
return True
def player_choice(board):
position = 0
while position not in range(1,10) or not space_check(board,position):
position = int(input("Choose Position 1-9: "))
return position
def replay():
choice = input("Play Again? Enter y or n: ").lower()
return choice=='y'
print("Welcome to TicTacToe")
the_board = [""]*10
player1_marker,player2_marker = player_input()
turn = choose_first()
print(turn+" will go first...")
play_game = input("Ready to play? Y or N: ").lower()
if play_game=="y":
game_on = True
else:
game_on = False
#Game Play
while game_on:
if turn == "Player1":
#show the board
display_board(the_board)
#choose position
position = player_choice(the_board)
#place the marker
place_marker(the_board,player1_marker,position)
#check if they won
if win_check(the_board,player1_marker):
display_board(the_board)
print("Player1 Has Won!")
game_on = False
else:
#check if tie
if full_board_check(the_board):
print("Game Tie!")
break
else:
turn = "Player2"
else:
#show the board
display_board(the_board)
#choose a position
position = player_choice(the_board)
#place marker in position
place_marker(the_board,player2_marker,position)
#check if won
if win_check(the_board,player2_marker):
display_board(the_board)
print("Player2 Has Won!")
game_on = False
else:
#check if tie
if full_board_check(the_board):
display_board(the_board)
print("Game Tie!")
game_on = False
else:
turn = "Player1"
|
ce1f91e55e29269422ff0e2b1e0af2901a0042e3
|
huyihui004/python
|
/自己/公司电脑py文件/xiaoyouxi.py
| 1,520 | 3.5625 | 4 |
#!/usr/bin/env python
#coding=utf-8
import random
import os
'''
分组实现保存不同用户的数据
game.txt的内容如下
胡益辉 3 5 31
总游戏次数,最快猜出的轮数,猜过的总轮数
'''
Name = raw_input('请输入名字:')
if not os.path.exists('game.txt'): #如果文件不存在则新建一个空文件
open('game.txt','w')
game = open('game.txt')
Data = game.readlines()
game.close()
result = {} #初始化一个字典
for line in Data:
s = line.split() #把每一行数据拆分成list
result[s[0]] = s[1:] #把第一项作为key,把剩下的作为value
if result.get(Name) is None: #如果当前玩家数据没有,则初始化数据
result[Name]=(0,0,0)
T1,T2,T3=int(result.get(Name)[0]),int(result.get(Name)[1]),int(result.get(Name)[2]) #获取玩家之前的数据
p = random.randint(1,20) #取一个随机数
num = 0
while True:
num += 1
number = input('请输入一个数字猜大小:')
if number < p:
print('小了')
elif number > p:
print('大了')
else:
print('回答正确')
break
if num < T2 or T2 == 0:
T2 = num
T3 += num
T1 += 1
P = float(T3)/T1
print "%s: 总游戏次数:%d 最快猜出的轮数:%d 平均猜出答案的轮数:%.2f" % (Name,T1,T2,P)
result[Name] = str(T1),str(T2),str(T3)
#把字典的结果字符化并写入文件
results = ''
for n in result:
reg = n + ' ' + ' '.join(result[n]) + '\n'
results += reg
game = open('game.txt','w')
game.write(results)
game.close()
|
1970de42fbf0cd80665bd5b7ddfb4362967c30f3
|
JneWalter25/SimpleChattyBot
|
/Topics/Program with numbers/Calculating S V P/main.py
| 306 | 3.53125 | 4 |
# put your python code here
length = int(input())
width = int(input())
height = int(input())
sum_lengths_edges = 4*(length + width + height)
print(sum_lengths_edges)
surface_area = 2*(length * width + width * height + length * height)
print(surface_area)
volume = length * width * height
print(volume)
|
c1de126e68d648ad9d8d178b9044b8c1e3a8d0d7
|
Sher-dil/MathSolution
|
/math_expression.py
| 2,907 | 4.03125 | 4 |
import re
def seperate_expression(expression):
#We just convert our expression to it's parts and return it as a list.
return re.findall(r'\d+\.\d+|\d+|[\+\*\-\/]', expression)
def calculate(expression):
num_sym_list=seperate_expression(expression)
#Solve our expresion by multiplication
result_list=solve_exp_by_mark("*",num_sym_list);
#Solve our expression by Division
result_list=solve_exp_by_mark("/",result_list);
#Solve our expression by Subtraction
result_list=solve_exp_by_mark("-",result_list);
#Solve our expression by Addition
result_list=solve_exp_by_mark("+",result_list);
#In this point there is only one item in the list and that is the result of expression,
#So we pop it from list
print(result_list)
def solve_exp_by_mark(mark,expression_list):
length=len(expression_list)
for i in range(length):
if expression_list[i]==mark:
if mark=="*":
expression_list[i]=float(expression_list[i-1])*float(expression_list[i+1])
elif mark=="/":
if expression_list[i+1]=='0':
return 'Can not divide number to Zero '
expression_list[i]=float(expression_list[i-1])/float(expression_list[i+1])
elif mark=="-":
expression_list[i]=float(expression_list[i-1])-float(expression_list[i+1])
else:
expression_list[i]=float(expression_list[i-1])+float(expression_list[i+1])
#we assign del to those list items which have been solved and later will be deleted.
expression_list[i-1]='del'
expression_list[i+1]=expression_list[i]
expression_list[i]='del'
i=0
while i<len(expression_list):
if expression_list[i]=='del':
expression_list.remove(expression_list[i])
i=i-1
i=i+1
return expression_list
def take_user_expression():
while True:
expression=input("Type an expression to solve for you , or type q to quit : ")
expression=expression.strip(" ")
if expression=="q":
break
# Here we only check the reqularity of our expression to prevent any kind of exception,
elif re.findall(r'[A-Za-z_][\+\-\*\/]\D*|\D+\D|^[\*\/]|[\-\+\*\/]$|\w*_\w*',expression):
print("Your expressin was not valid. ")
continue
#Here we check pattern which starts with - or + , because I was not able to solve such expression.
elif re.match(r'^[\+\-]\d+',expression):
expression='0'+expression
calculate(expression)
else:
calculate(expression)
#Run our program from this point
take_user_expression()
|
284d8ec970d662bd684799b6533f445aca1e7c15
|
nirmalshah20519/GTU_PRACTICALS
|
/PDS/SET_1/Prog-7.py
| 220 | 4.15625 | 4 |
# Python Program to find out the second largest number in the list
arr1=[100,99,98,97,96,95,94,93,92,91]
print(arr1)
arr2=arr1
arr2.sort()
print("Second Largest Element in the given array is : ", arr2[-2])
arr2.clear()
|
f6f9fae8e999c571fcc61a5dbb4a3fbffa32b1eb
|
christine2623/Mao
|
/K-fold cross validation.py
| 8,315 | 3.859375 | 4 |
# K Fold Cross Validation
# In the previous mission, we learned about cross validation,
# a technique for testing a machine learning model's accuracy on new data that the model wasn't trained on.
"""
K-fold cross-validation works by:
splitting the full dataset into k equal length partitions,
selecting k-1 partitions as the training set and
selecting the remaining partition as the test set
training the model on the training set,
using the trained model to predict labels on the test set,
computing an error metric (e.g. simple accuracy) and setting aside the value for later,
repeating all of the above steps k-1 times, until each partition has been used as the test set for an iteration,
calculating the mean of the k error values.
Using 5 or 10 folds is common for k-fold cross-validation.
"""
"""
When working with large datasets, often only a few number of folds are used because of the time and cost it takes,
with the tradeoff that having more training examples helps improve the accuracy even with less folds.
"""
# Partititioning The Data
import pandas as pd
from sklearn.linear_model import LogisticRegression
admissions = pd.read_table("admissions.data", delim_whitespace=True)
admissions["actual_label"] = admissions["admit"]
admissions = admissions.drop("admit", axis=1)
print(admissions.head())
import numpy as np
from numpy.random import permutation
shuffled_index = permutation(admissions.index)
shuffled_admissions = admissions.loc[shuffled_index]
admissions = shuffled_admissions.reset_index()
# Partition the dataset into 5 folds and store each row's fold in a new integer column named fold
# Use df.ix[index_slice, col_name] to mass assign a specific value for col_name for all of the rows in the index_slice.
# You can use this to set a value for a new column in the Dataframe as well.
admissions.ix[:128, 'fold'] = 1
# Somehow "for" loop doesn't work! (why why why??)
admissions.ix[129:257, 'fold'] = 2
admissions.ix[258:386, 'fold'] = 3
admissions.ix[387:514, 'fold'] = 4
admissions.ix[515:644, 'fold'] = 5
# Ensure the column is set to integer type.
admissions["fold"] = admissions["fold"].astype('int')
print(admissions.head())
print(admissions.tail())
# First Iteration
# let's assign fold 1 as the test set and folds 2 to 5 as the training set.
# Then, train the model and use it to predict labels for the test set.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
train_iteration_one = admissions[admissions["fold"] != 1]
test_iteration_one = admissions[admissions["fold"] == 1]
logistic_model = model.fit(train_iteration_one[["gpa"]], train_iteration_one["actual_label"])
labels = model.predict(test_iteration_one[["gpa"]])
test_iteration_one["predicted_label"] = labels
match = test_iteration_one["predicted_label"] == test_iteration_one["actual_label"]
correct_match = test_iteration_one[match]
iteration_one_accuracy = correct_match.shape[0] / test_iteration_one.shape[0]
print(iteration_one_accuracy)
# Function For Training Models
# Use np.mean to calculate the mean.
import numpy as np
fold_ids = [1,2,3,4,5]
# Write a function named train_and_test that takes in a Dataframe and a list of fold id values (1 to 5 in our case) and returns a list of accuracy values
def train_and_test(df, list):
model = LogisticRegression()
iteration_accuracy = []
for fold in list:
train = df[df["fold"] != fold]
test = df[df["fold"] == fold]
model = model.fit(train[["gpa"]], train["actual_label"])
labels = model.predict(test[["gpa"]])
test["predicted_label"] = labels
match = test["predicted_label"] == test["actual_label"]
correct_match = test[match]
iteration_accuracy.append(float(correct_match.shape[0] / test.shape[0]))
return iteration_accuracy
# Use the train_and_test function to return the list of accuracy values for the admissions Dataframe and assign to accuracies
accuracies = train_and_test(admissions, fold_ids)
# Compute the average accuracy and assign to average_accuracy.
average_accuracy = sum(accuracies)/len(accuracies)
# Another way: average_accuracy = np.mean(accuracies)
# average_accuracy should be a float value while accuracies should be a list of float values (one float value per iteration).
# Use the variable inspector or the print function to display the values for accuracies and average_accuracy
print(accuracies)
print(average_accuracy)
# Sklearn
"""
In many cases, the resulting accuracy values don't differ much between a simpler, less time-intensive method like holdout validation
and a more robust but more time-intensive method like k-fold cross-validation.
As you use these and other cross validation techniques more often,
you should get a better sense of these tradeoffs and when to use which validation technique.
"""
"""
In addition, the computed accuracy values for each fold stayed within 61% and 63%, which is a healthy sign.
Wild variations in the accuracy values between folds is usually indicative of using too many folds (k value)
"""
"""
Similar to having to instantiate a LinearRegression or LogisticRegression object before you can train one of those models,
you need to instantiate a KFold class before you can perform k-fold cross-validation.
kf = KFold(n, n_folds, shuffle=False, random_state=None)
n is the number of observations in the dataset,
n_folds is the number of folds you want to use,
shuffle is used to toggle shuffling of the ordering of the observations in the dataset,
random_state is used to specify a seed value if shuffle is set to True.
"""
"""
If we're primarily only interested in accuracy and error metrics for each fold,
we can use the KFold class in conjunction with the cross_val_score function,
which will handle training and testing of the models in each fold.
cross_val_score(estimator, X, Y, scoring=None, cv=None)
estimator is a sklearn model that implements the fit method (e.g. instance of LinearRegression or LogisticRegression),
X is the list or 2D array containing the features you want to train on,
y is a list containing the values you want to predict (target column),
scoring is a string describing the scoring criteria (list of accepted values here).
cv describes the number of folds. Here are some examples of accepted values:
an instance of the KFold class,
an integer representing the number of folds.
"""
"""
Here's the general workflow for performing k-fold cross-validation using the classes we just described:
instantiate the model class you want to fit (e.g. LogisticRegression),
instantiate the KFold class and using the parameters to specify the k-fold cross-validation attributes you want,
use the cross_val_score function to return the scoring metric you're interested in.
"""
from sklearn.cross_validation import KFold
from sklearn.cross_validation import cross_val_score
# Create a new instance of the KFold class with the following properties:
# n set to length of admissions,
# 5 folds,
# shuffle set to True,
# random seed set to 8 (so we can answer check using the same seed),
# assigned to the variable kf.
kf = KFold(admissions.shape[0], 5, shuffle=True, random_state=8)
# Create a new instance of the LogisticRegression class and assign to lr
lr = LogisticRegression()
# Use the cross_val_score function to perform k-fold cross-validation:
# using the LogisticRegression instance lr,
# using the gpa column for training,
# using the actual_label column as the target column,
# returning an array of accuracy values (one value for each fold).
accuracies = cross_val_score(lr, admissions[["gpa"]], admissions["actual_label"], scoring="accuracy", cv=kf)
# compute the average accuracy
average_accuracy = np.mean(accuracies)
print(accuracies)
print(average_accuracy)
# Interpretation
"""
Using 5-fold cross-validation, we achieved an average accuracy score of 64.4%,
which closely matches the 63.6% accuracy score we achieved using holdout validation.
When working with simple univariate models, often holdout validation is more than enough and the similar accuracy scores confirm this.
When you're using multiple features to train a model (multivariate models),
performing k-fold cross-validation can give you a better sense of the accuracy you should expect when you use the model
on data it wasn't trained on.
"""
|
c764106862aa09477602b11a6761eab8e3d79bef
|
Jventura1/python_practice
|
/sample_classes.py
| 475 | 3.9375 | 4 |
class simple_arithmetic:
'''This object takes two arguments at initialization. there are four methods that will return
simple arithmetic operations'''
def __init__(self,arg1,arg2):
self.arg1 = arg1
self.arg2 = arg2
def add(self):
return self.arg1+self.arg2
def sub(self):
return self.arg1-self.arg2
def div(self):
return float(self.arg1)/float(self.arg2)
def mult(self):
return self.arg1*self.arg2
|
0bc30d168a94324b5e6a4a70f0aa4cc6e77b25e6
|
yuhangxiaocs/LeetCodePy
|
/search/Number_of_SquarefulArrays.py
| 1,096 | 3.59375 | 4 |
import math
class Solution(object):
def numSquarefulPerms(self, A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
def check(nums):
n = len(nums)
for i in range(n - 1):
s = (nums[i] + nums[i + 1])
sqrt = int(math.sqrt(s))
if s != sqrt ** 2: return False
return True
def dfs(nums, pos, path):
if len(path) >= 2:
if not check(path): return
if pos == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1] and visited[i - 1] == True: continue
if not visited[i]:
visited[i] = True
path.append(nums[i])
dfs(nums, pos + 1, path)
path.pop()
visited[i] = False
path, res = [], []
visited = [False for _ in range(len(A))]
dfs(A, 0, path)
return len(res)
|
88af451542490159c2d02811dd50e01dc5208d90
|
lesliemayer/catalogImages
|
/Modules/imageutils.py
| 2,588 | 3.703125 | 4 |
# python code imutils.py
#
# LR Mayer from OpenCV book (pdf)
# 08/22/2016
#
# Defining our own imutils package :
import numpy as np
import cv2
from matplotlib import pyplot as plt
import __future__ # for the print function so that it works in python 3
# function to translate an image in the x & y direction
def translate(image, x, y):
print("in self defined imutils function translate **************************************")
M = np.float32([[1, 0, x], [0, 1, y]])
shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
return shifted
# function to rotate an image
# angle is the angle which to rotate the image
# scale is how much to scale the size of the image, the default is 1.0
def rotate(image, angle, center = None, scale = 1.0):
# get height & width of image
(h, w) = image.shape[:2]
# if center is a value of None, calculate center from h, w
if center is None:
center = (w / 2, h / 2)
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
# function for resizing an image w/ openCV
def resize(image, width = None, height = None, inter = cv2.INTER_AREA):
# Default interpolation is cv2.INTER_AREA
# set dim to not a value
dim = None
# get the height, width of current image
(h, w) = image.shape[:2]
# check that width or height is set, if not return original image
if width is None and height is None:
return image
# calculate width from the give height
if width is None:
r = height / float(h)
dim = (int(w * r), height)
# calculate height from width
else:
r = width / float(w)
dim = (width, int(h * r))
# end if
#resized = cv2.resize(image, dim, interpolation = inter)
resized = cv2.resize(image, dim, interpolation=CV_INTER_AREA) # better for shrinking
# CV_INTER_LINEAR is better for zooming. This is the default
# CV_INTER_CUBIC is slow
return resized
# Plot histogram of an image :
def plot_color_hist(image):
# get each separate color channel (BGR)
chans = cv2.split(image)
colors = ("b", "g", "r")
plt.figure()
plt.title("Color Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
for (chan, color) in zip(chans, colors):
# hist = cv2.calcHist([chan], [0], None, [256], [0, 256]) # sometimes this will crash python
hist, bins = np.histogram(chan.ravel(), 256, [0, 256])
plt.plot(hist, color = color)
plt.xlim([0, 256])
plt.show()
return
|
ef616e72eea64e0df6959eed3b6041f61d4250be
|
JaviS1997/feb172020
|
/tripled_letters.py
| 170 | 4 | 4 |
string = input("Give me the text please")
if string[::3] == string[1::3] == string[2::3]:
print("They are all tripled ")
else:
print("They are not all tripled")
|
20f7406d297ef7de2ef25cb198670418a91d02c1
|
tbo4500/Horizons
|
/Assignment1/Problem6/example6-1.py
| 72 | 3.75 | 4 |
array = ['a', 'b', 'c', 'd', 'e']
for i in range(3):
print array[i]
|
67846b713d0bab5066b84264a3a5d36e33324ebc
|
BIG-S2/PSC
|
/Scilpy/scilpy/utils/python_tools.py
| 503 | 3.90625 | 4 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import tee
import re
def natural_sort(l):
# Taken from http://stackoverflow.com/a/2669120/912757
def alphanum(key):
return [int(c) if c.isdigit() else c.lower()
for c in re.split('([0-9]+)', key)]
return sorted(l, key=alphanum)
def pairwise(iterable):
"""
s -> (s0,s1), (s1,s2), (s2, s3), ...
From itertools recipes
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
|
6e6eebc2b1688c4dc2e7ec3fc7f7e3ec6751c989
|
carb/EulerWork
|
/Euler5.py
| 835 | 3.765625 | 4 |
'''
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Brute force doesnt work!!
\>>> for num in range(10000000):
... e = 0
... for thang in range (1,21):
... e += (num%thang)
... if e == 0:
... print num
...
returned just zero
ok. so we have to check...
if we take the prime factors of 2520 we get 2,2,2,3,3,5,7
how can we go from
'1,2,3,4,5,6,7,8,9,10' -> '2,4,5,7,9' or '5,7,8,9'
10!
2,2,2,2,2,2,2,2,3,3,3,3,5,5,7
=>2,2,2, 3,3, 5, 7
global primes
primes = [2]
global e
e = 0
global ans
ans = []
for num in range(10000)[2:]:
e = 0
for prime in primes:
if num%prime > 0:
e += 1
if e == len(primes):
primes += [num]
|
d98bc4ba86d49cfab3fba4638a3fefce0f2107b8
|
T300M256/Python_Courses
|
/python1hw/check_string.py
| 405 | 4.375 | 4 |
#!/usr/local/bin/python3
"""check the input meets the requirements"""
s = ""
while not s.isupper() or not s.endswith("."):
s = input("Please enter an upper-case string ending with a period: ")
if not s.isupper():
print("Input is not all upper case.")
elif not s.endswith("."):
print("Input does not end with a period.")
else:
print("Input meets both requirements.")
|
d72e7b91c72074d60e0ab79157a195a7f7d79776
|
msflores10307/python-challenge
|
/PyBank/main.py
| 2,038 | 3.53125 | 4 |
import os
import csv
# sets data file path
data_path = os.path.join(".", "Resources", "budget_data.csv")
# initiates important arrays and dictionary
month_column = []
prof_loss_column = []
changes = []
monthly_prof = {}
monthly_changes = {}
# opens reader file
with open(data_path) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
next(csv_reader)
row_counter = 0
# populates arrays/dictionary for month, profit/loss,
for row in csv_reader:
month_column.append(str(row[0]))
prof_loss_column.append(float(row[1]))
monthly_prof.update( {str(row[0]) : [row[1]]} )
row_counter = row_counter + 1
# populates indexes of changes in profit/loss by month.
for i in range(len(prof_loss_column)-1):
changes.append(prof_loss_column[i+1]-prof_loss_column[i])
monthly_changes.update( {month_column[i+1]: prof_loss_column[i+1]-prof_loss_column[i] } ) # shows the change between current month and previous
# indexes of this matrix are one less than in main month matrix because first month is not included
# outputs indices of min and max changes in profit/loss
mini = changes.index(min(changes))
maxi = changes.index(max(changes))
# The total number of months included in the dataset
month_count = len(month_column)
# The net total amount of "Profit/Losses" over the entire period
TotalProfitLoss = sum(prof_loss_column)
# The average of the changes in "Profit/Losses" over the entire period
avg = sum(changes)/len(changes)
output_string = f'''
Financial Analysis
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Total Months: {month_count}
Total: ${TotalProfitLoss}
Average Change: ${avg}
Greatest Increase in Profits: {month_column[maxi+1]}(${monthly_changes[month_column[maxi+1]]})
Greatest Decrease in Profits: {month_column[mini+1]}(-${abs(monthly_changes[month_column[mini+1]])})
'''
print(output_string)
output_path = os.path.join(".", "analysis", "analysis.txt")
# writes analysis a file
with open(output_path, "w") as outfile:
outfile.write(output_string)
|
f68d9d42c6a1a752e7fd9b19e9f891b4a32100d5
|
hellcat-git/PythonBasics
|
/Lesson3_Task2.py
| 834 | 3.515625 | 4 |
my_users_attr = ['Имя', 'Фамилия', 'Год рождения', 'Город проживания', 'email', 'Телефон']
def collect_data():
new_user_data = []
for i in my_users_attr:
a = input(f"Введите значение атрибута '{i}': ")
new_user_data += [(i, a)]
new_user_dict = dict(new_user_data)
return new_user_dict
def new_user(**kwargs):
return print(f"Вы ввели параметры пользователя: {kwargs}")
# Решение 1 - собираем значения аттрибутов в цикле
new_user(**collect_data())
# Решение 2 - вводим значения аттрибутов вручную через input
new_user(Имя=input("Введите Имя: "), Фамилия=input("Введите Фамилию: "))
|
7db1b0b9c766005be18cd7bded5160b4b1d2f6ab
|
artainmo/python_bootcamp
|
/day03/ex01/ImageProcessor.py
| 667 | 3.734375 | 4 |
import matplotlib.image as img
import matplotlib.pyplot as plt
class ImageProcessor:
def load(self, path): #opens the .png file specified by the path argument and returns an array with the RGB values of the image pixels. It must display a message specifying the dimensions of the image (e.g. 340 x 500).
RGB = img.imread(path)
print(RGB.shape[0] + "x" + RGB.shape[1])
return RGB
def display(self, array): #takes a NumPy array as an argument and displays the corresponding RGB image.
return plt.imshow(array)
im = ImageProcessor()
print(im.load("../resources/42AI.png"))
print(im.display(im.load("../resources/42AI.png")))
|
7d2aa29ebb3431476eb0f189a0ab034b2e8538ff
|
kmod/icbd
|
/icbd/compiler/tests/24.py
| 411 | 3.546875 | 4 |
"""
string test
"""
s = ""
for i in xrange(10):
s += " 5"
print s
def ident(s):
return s
def double(s):
return s + s
print double("hello"), ident("world")
def callit(f):
return f("hello")
print callit("world ".__add__)
l = ["hi"]
while len(l) < 10:
l.append(l[-1] + "i")
for i in xrange(len(l)):
print i, l[i]
def get_space():
return " "
print "hello" + get_space() + "world"
|
16ebf3eaf0071d84326010beece3686762ca76c9
|
serena-mower23/repo-test
|
/serena-stuff/hello-world.py
| 188 | 3.65625 | 4 |
import pandas as pd
print('Hello World')
grades = pd.read_csv('grades.csv')
grade_pivot = grades.pivot(
columns="test",
index="student",
values="grade"
)
print(grade_pivot)
|
4db01a58cbd9ab2c54ac7e9ee68795cb0583ccb3
|
gibson20g/ExerciosPythonPojeto
|
/ex034salario.py
| 1,257 | 3.9375 | 4 |
nome = str(input("Digite o Nome do Funcionario: "))
salario = float(input("Qual é o salário do funcionario?R$: "))
if salario <= 1045:
novo = salario + (salario * 5.26 / 100)
porcent = 5.26
aumento = novo - salario
print("O salario antigo é R${:.2f}, Porcentagem de aumento {}% ".format(salario, porcent))
print("aumento de R${:.2f}, E o novo salário será {:.2f}".format(aumento, novo))
elif 2195 >= salario > 1045:
novo = salario + (salario * 4.32 / 100)
porcent = 4.32
aumento = novo - salario
print("O salario antigo é R${:.2f}, Porcentagem de aumento {}% ".format(salario, porcent))
print("aumento de R${:.2f}, E o novo salário será {:.2f}".format(aumento, novo))
elif 3500 > salario > 2195:
novo = salario + (salario * 2.75 / 100)
porcent = 2.75
aumento = novo - salario
print("O salario antigo é R${:.2f}, Porcentagem de aumento {}% ".format(salario, porcent))
print("aumento de R${:.2f}, E o novo salário será {:.2f}".format(aumento, novo))
elif salario >= 3500:
novo = salario + (salario * 1.79 / 100)
porcent = 1.79
aumento = novo - salario
print("O salario antigo é R${:.2f}, Porcentagem de aumento {}% ".format(salario, porcent))
print("aumento de R${:.2f}, E o novo salário será {:.2f}".format(aumento, novo))
|
9affeca6f4157d56207c9e00e4f18469159aca8d
|
MrWJB/rtxs
|
/rtxs/复习/偏函数复习.py
| 595 | 3.984375 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
i1 = int('12306')
print('i1的值: %s ' % i1)
def int2(x, base=2):
return int(x, base)
i2 = int2('1010010111011')
print('i2的值: %s' % i2)
# functools.partial 就是帮助我们创建一个偏函数的,不需要我们自己定义int2(), 可以直接使用下面的的代码创建一个新的函数int2:
import functools
int2 = functools.partial(int, base=2)
i3 = int2('1001010101')
print('i3的值: %s' % i3)
# 其它示例
max2 = functools.partial(max, 10)
args = (10, 20, 30, 40, 50)
print(*args)
max3 = max2(*args)
print(max3)
|
acb33b2069fa3c13e8f67328e2ad4f9ffb42fdbe
|
raghum96/pythonTutorial
|
/WhileLoop.py
| 139 | 3.59375 | 4 |
i = 0
while i < 10:
# print(i)
i = i + 1
for i in range(0, 100, 7):
if i > 0 and i % 11 == 0:
print(i)
break
|
056b6116c9f07e19d98ec9f39ea1dc11158f78d6
|
Dhrumil-Zion/Competitive-Programming-Basics
|
/LeetCode/Arrays/check_for _doubles_in_array.py
| 151 | 3.703125 | 4 |
arr = [3,1,7,11]
flag = 0
for a in arr:
temp = a*2
if temp in arr:
flag=1
print("True")
if flag==0:
print("false")
|
f46d8a29fdbb09750c1ce4fdde06d937008116a5
|
marcogmaia/proj_com
|
/q2/account.py
| 1,045 | 3.640625 | 4 |
class account():
def __init__(self, user, password):
self.user = user
self.password = password
'''getters'''
def getUser(self):
return self.user
def getPass(self):
return self.password
'''setters'''
def setUser(self, curAccount, newUser):
if newUser != "" and self.getUser() == curAccount.getUser() and self.getPass() == curAccount.getPass():
self.user = newUser
return True
return False
def setPass(self, curUser, newPass):
if newPass != "" and self.getUser() == curAccount.getUser() and self.getPass() == curAccount.getPass():
self.password = newPass
return True
return False
'''comparisons'''
def __lt__(self, other):
return self.getUser() < other.getUser()
def __le__(self, other):
return self.getUser() <= other.getUser()
def __eq__(self, other):
return self.getUser() == other.getUser()
def __ne__(self, other):
return self.getUser() != other.getUser()
def __gt__(self, other):
return self.getUser() > other.getUser()
def __ge__(self, other):
return self.getUser() >= other.getUser()
|
4e41e6bd816d64e958b6784058142039e752c645
|
henryji96/LeetCode-Solutions
|
/Easy/671.second-minimum-node-in-binary-tree/second-minimum-node-in-binary-tree.py
| 735 | 3.8125 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return -1
treeSet = set()
self.postOrder(root, treeSet)
treeSet = sorted(treeSet)
if len(treeSet) == 1:
return -1
else:
return treeSet[1]
def postOrder(self, root, treeSet):
if not root:
return
self.postOrder(root.left, treeSet)
self.postOrder(root.right, treeSet)
treeSet.add(root.val)
|
2d8f037e8317d5f09e7dca5cc98700e44a5310f6
|
mfitrihani/project-euler-solutions
|
/Python/010.py
| 573 | 3.796875 | 4 |
def generate_prime_number(max_prime_number):
candidate = [True for x in range(0, max_prime_number)]
for i in range(2, int(max_prime_number**0.5) + 2):
if candidate[i]:
j = i*i
x = 1
while j < max_prime_number:
candidate[j] = False
j = i*i + x*i
x += 1
prime_numbers = []
for x in range(0, len(candidate)):
if candidate[x]:
prime_numbers.append(x)
return prime_numbers
if __name__ == '__main__':
print((generate_prime_number(2000000)))
|
13624609bc4cca1b6e0bc0350b5c9cc7926627aa
|
daniel-reich/ubiquitous-fiesta
|
/Egh2HES8eqPTTX9Q2_4.py
| 228 | 3.546875 | 4 |
def rolling_cipher(txt, n):
return "".join(alphaSwap(c,n%26) for c in txt)
def alphaSwap(c,add):
cur = ord(c)-ord("a")+1
if cur+add<=26:
return(chr(ord(c)+add))
add = (cur+add)%26
return(chr(ord("a")+add-1))
|
c4ae13f442e1f412002bb7554263b126cc52ca19
|
KasraNezamabadi/InterviewPractice
|
/SortPractice.py
| 2,288 | 3.8125 | 4 |
import math
def MergeSort(inputList: [int]):
# Stop condition for recursive call
if len(inputList) == 1:
return inputList
# We need to divide the array into two halves and recursively call mergeSort for each.
leftSublist = inputList[:math.floor(len(inputList) / 2)]
rightSublist = inputList[math.floor(len(inputList) / 2):]
sortedLeftSubarray = MergeSort(leftSublist)
sortedRightSubarray = MergeSort(rightSublist)
finalResult = Merge(sortedLeftSubarray, sortedRightSubarray)
v = 9
return finalResult
def Merge(listA: [int], listB: [int]):
# Merge two sorted arrays and return the result
indexA = 0 # index for listA
indexB = 0 # index for listB
mergedArray = []
lower_bound = len(listA)
if len(listB) < len(listA):
lower_bound = len(listB)
while indexA < lower_bound and indexB < lower_bound:
itemA = listA[indexA]
itemB = listB[indexB]
if itemA > itemB:
mergedArray.append(itemB)
indexB = indexB + 1
else:
mergedArray.append(itemA)
indexA = indexA + 1
if indexA < len(listA):
mergedArray.extend(listA[indexA:])
if indexB < len(listB):
mergedArray.extend(listB[indexB:])
v = 9
return mergedArray
def quick_sort(input_list: [int], low, high):
if low < high:
pivot_index = partition(input_list, low, high)
quick_sort(input_list, low, pivot_index - 1)
quick_sort(input_list, pivot_index + 1, high)
def partition(input_list: [int], low, high):
pivot = input_list[high] # last element as pivot
index_before_pivot = low-1
for i in range(low, high):
if input_list[i] <= pivot:
index_before_pivot = index_before_pivot + 1
input_list[i], input_list[index_before_pivot] = input_list[index_before_pivot], input_list[i]
pivot_index = index_before_pivot + 1
input_list[pivot_index], input_list[high] = input_list[high], input_list[pivot_index]
return pivot_index
inputList = [1, 4, 2, 7, 8, 5, 3]
#print(inputList[-1])
quick_sort(input_list=inputList, low=0, high=len(inputList)-1)
print('Result: ', inputList)
#print(Merge([7, 8], [3, 5]))
#print(MergeSort(inputList=inputList))
|
116f3a3a50601caf48cc0cb3c04920c9db6074bb
|
HenDGS/Aprendendo-Python
|
/python/Exercicios/5.9.py
| 279 | 3.984375 | 4 |
usuarios=["henrique","clara","guilherme","admin","pedro"]
if usuarios:
for usuario in usuarios:
if (usuario=="admin"):
print("Olá admin, gostaria de um relatorio?")
else :
print(usuario.title() + ", bom dia!")
else:
print ("Preciamos encontrar alguns usuários")
|
e46e5331c2a3b189c5082674a1193a8b8e1cf6cd
|
gong1209/my_python
|
/Class & function/C_car.py
| 1,446 | 4.4375 | 4 |
''' 父類別 Parent class'''
class Car():
def __init__(self,year,brand,color):
self.year = year
self.brand = brand
self.color = color
self.miles = 0
def get_name(self): # 印出名字
print(str(self.year) +" "+ self.brand)
def get_mile(self): # 存取公里數
print("Your "+self.brand+" has "+str(self.miles)+" miles on it")
def update_mile(self,mileage): # 更新公里數
self.miles = mileage
def add_mile(self,kilometer): # 增加公里數
self.miles += kilometer
def fill_gas(self): # 車子加油
print("This car need a gas tank")
''' 子類別 ElectriCar '''
class ElectricCar(Car): # 定義一個子類別,且括號內一定要放入父類別
def __init__(self,year,brand,color): # 接收Car實例所需要的資訊
super().__init__(year,brand,color) # 這行會使python呼叫ElectricCar父類別的__init__()方法,讓ElectricCar實例含有父類別的所有屬性
# 對子類別新增其專有的屬性和方法'''
self.battery_size = 100
#''' 新增一個get_battery方法'''
def get_battery(self):
print("Your "+self.brand+" has "+str(self.battery_size)+"-KWh battery")
#''' 覆寫父類別的fill_gas方法'''
def fill_gas(self):
print("This car doesn't need a gas tank")
##父 : print("This car need a gas tank")
|
aa38ac57b56ae86a53d2f74fa2da22060894b3f3
|
BabyCakes13/Python-Treasure
|
/Laboratory 5/problem1/Class.py
| 544 | 3.9375 | 4 |
class Class:
"""Class which contains the transform methods."""
def __init__(self):
"""Initialises the string."""
self.string = ""
def ask_str(self):
"""Gets the string from the user."""
self.string = input("give the string...")
def transform_str(self):
"""Prints the transformed string."""
print(self.string.upper())
def class_test():
"""Tests the class."""
test = Class()
test.ask_str()
test.transform_str()
if __name__ == "__main__":
class_test()
|
860b79853073b7b85229d8f9cc5acdd195399dd5
|
huicheese/Bootcamp
|
/Lab4/Lab 4 Example 7.py
| 174 | 3.609375 | 4 |
date_input = input("Enter DOB (d/m/y)")
parts = date_input.split("/") # this will be a list of strings
my_dob = (int(parts[0]), int(parts[1]), int(parts[2]))
print(my_dob)
|
34680d1fe86a79ec05b9fd451a7d9fdbfa7de72e
|
guoweifeng216/python
|
/python_design/pythonprogram_design/Ch6/6-3-E15.py
| 718 | 4.09375 | 4 |
import turtle
def main():
## Draw nested set of five squares.
t = turtle.Turtle()
t.hideturtle()
for i in range(1, 6):
drawRectangle(t, -10 * i, -10 * i, 20 * i, 20 * i, "blue")
def drawRectangle(t, x, y, w, h, colorP="black"):
## Draw a rectangle with bottom-left corner (x, y),
## width w, height h, and pencolor colorP.
t.pencolor(colorP)
t.up()
t.goto(x, y) # start at bottom-left corner of rectangle
t.down()
t.goto(x + w, y) # draw line to bottom-right corner
t.goto(x + w, y + h) # draw line to top-right corner
t.goto(x, y + h) # draw line to top-left corner
t.goto(x, y) # draw line to bottom-left corner
main()
|
f1c4c2668b6b96df37addd17705baf073c7fb953
|
bam0/Project-Euler-First-100-Problems
|
/Problems_21-40/P23_Non-Abundant_Sums.py
| 3,183 | 3.859375 | 4 |
'''
Problem: Find the sum of all the positive integers which cannot be
written as the sum of two abundant numbers.
Using the algorithms we already created in problem 21, this problem won't present
us with too much of a challenge. First we'll generate a list of primes with our
prime sieve, then calculate the sum of divisors for each number up to 28123
(which has been proven to be the last number not expressible as the sum of two
abundant numbers).
'''
def prime_sieve(n):
L = [True] * n # Initialize the array of booleans
L[0] = L[1] = False
for (i, is_prime) in enumerate(L):
if is_prime:
yield i
for x in range(i*i, n, i): # Set the non-primes to False
L[x] = False
primes = list(prime_sieve(200)) # sqrt(30000) ~ 170, plus some padding
def sum_div(n):
prod, n_copy = 1, n # Initialize the product and a copy of n
if n==1:
return 1
for p in primes:
if n < p*p: # Now we know n is prime, so add this to our product
prod*=(n*n-1)//(n-1)
break
exp = 1 # Initialize the exponent
while not n%p:
n//=p
exp+=1
prod*=int((p**exp-1))//(p-1) # Plug p and exp into our formula
if n==1: # When n is 1, we have no more primes to check
break
return prod-n_copy # Subtract off the copy of n
'''
One method we could use is to create a set of all the numbers that CAN be
written as the sum of two abundant numbers. Then we just have to subtract that from the
sum of all the numbers from 1 to 28123.
'''
def solution1():
abund, non = [], set() # Initialize the abundant and non-abundant list/set
for i in range(1, 28124):
if sum_div(i) > i: # Check abundancy
abund.append(i)
for a in abund:
sm = a+i
if sm < 28124: # Check if sum is in range
non.add(sm) # Add it to our set
else:
break
return ((28123*28124)//2)-sum(non) # Subtract from the total sum
'''
However a slightly faster solution is to generate a list of all the numbers from 1 to 28123
first. Then whenever a number can be written as an abundant sum, we just set its value to
zero. This is similar to the method used in the prime sieve.
'''
def solution2():
nums = list(range(1, 28124)) # Initialize list of numbers
abund = []
for i in range(1, len(nums)+1):
if sum_div(i) > i:
abund.append(i)
for a in abund:
sm = a+i
if sm < 28124:
nums[sm-1] = 0 # Set value equal to 0
else:
break
return sum(nums) # Take the sum of the remaining numbers
'''
The result is still not very fast, taking ~2 seconds to complete. But this may be
more of a limitation of python, rather than the algorithm itself.
'''
print('Non-abundant sum:', solution2()) # Non-abundant sum: 4179871
|
c4cb28945cc6f922a36ed15f6307d09b1d136a7f
|
spradeepv/dive-into-python
|
/hackerrank/domain/python/data_types/lists.py
| 470 | 3.578125 | 4 |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(raw_input())
l = []
for i in range(n):
commands = raw_input().split()
count = 0
method = ""
method = commands[0]
args = map(int, commands[1:])
if method == "print":
print l
elif not args and method != "print":
getattr(l, method)()
elif len(args) == 1:
getattr(l, method)(args[0])
else:
getattr(l, method)(args[0], args[1])
|
fc78249cea41af1185722f0ad3dd2683d66d39a9
|
ahmadzaidan99/Codewars
|
/Persistent_Bugger.py
| 236 | 3.5 | 4 |
def persistence(n):
arr = [int(x) for x in str(n)]
count = 0
while(len(arr)!=1):
result=1
count += 1
for x in arr:
result *= x
arr = [int(x) for x in str(result)]
return count
|
3a328c5584ab89c3073c79a643659c3c7114313a
|
navctns/Python-Exercices
|
/38_string_print.py
| 233 | 4.3125 | 4 |
#38. Write a program to print every character of a string entered by user
#in a new line using loop
str1=input("Enter the string:")
for i in str1:
print(i)
"""
OUTPUT:
Enter the string:python
p
y
t
h
o
n
"""
|
3e881ac5996acdd84eca88d2be9aa0fec25ccfe3
|
KoskiKari/easyHangman
|
/hangman.py
| 5,032 | 4.0625 | 4 |
import time, random, os, string
def menuLayout():
#game's main menu
print(f'HANGMAN GAME ')
print(f' ____ ')
print(f'/ | ')
print(f'| O ')
print(f'| -|- ')
print(f'| / \ ')
print(f'| ')
print(f' _________ ')
print(f'| | ')
print(f'| | ')
while True:
print(f'(N)ew game, random word')
print(f'(E)asy mode, random word')
print(f'(S)elect word yourself')
print(f'(Q)uit game')
option = input('Enter option: ')
if option.lower() in ['n','s','e','q']:
return option
else:
print('Invalid option')
time.sleep(1)
def selectWord():
#allow user to create their own word, require length higher than 2
os.system('cls')
while True:
magic_word = input('Enter word to guess: ')
#check word is atleast 2 chars, and contains only letters
if len(magic_word) < 2 or not magic_word.isalpha():
os.system('cls')
print('Word needs length of 2 atleast')
continue
break
return magic_word
def wordFromFile():
#get random word from the textfile
word_list = []
with open('commonWords.txt','r') as f:
for i in f:
word_list.append(i.strip())
magic_word = random.choice(word_list)
return magic_word
def addLetters(current,magic_word):
#easy_mode letter addition, random.sample half the length of the word
#this has some problems with words that have many duplicate letters
letters = random.sample(magic_word,len(magic_word)//2)
for letter in letters:
indices = [pos for pos, char in enumerate(magic_word) if char == letter]
for position in indices:
current[position] = letter.lower()
return current
def drawHangman(count,figure):
#after initial draw, start adding body parts
if count > 0:
parts = ['O','|','-','-','/','\\']
figure[count-1] = parts[count-1]
print(f' ____ ')
print(f'/ | ')
print(f'| {figure[0]} ')
print(f'| {figure[2]}{figure[1]}{figure[3]} ')
print(f'| {figure[4]} {figure[5]} ')
print(f'| ')
print(f' _________ ')
print(f'| | ')
print(f'| | ')
return figure
def game(magic_word,easy_mode):
#create variables needed for game, add letters to word if easy mode
count = 0
figure =['', ' ' , ' ', '', '' ,'']
current = ['*' for i in range(len(magic_word))]
already_guessed = []
if easy_mode:
current = addLetters(current,magic_word)
#game loop
while True:
#input loop
while True:
os.system('cls')
drawHangman(count,figure)
#print current status with list comprehension
[print(char,end='') for char in current]
#user input handling
print(f'\nPrevious guesses: {already_guessed}')
letter = input('Enter letter to guess:')
if letter and letter not in already_guessed:
already_guessed.append(letter)
break
#check if letter present in magic_word, fill correct positions
if letter in magic_word:
indices = [pos for pos, char in enumerate(magic_word) if char == letter]
for position in indices:
current[position] = letter.lower()
#incorrect guess, add 1 count
else:
count += 1
if count > 5:
break
#check if all letters have been guessed
if '*' not in current:
print(f'\n***** {magic_word} *****\n')
print('Congratulations! You have won!')
input('Press enter to continue.')
return
#after all guesses are used, loop breaks -> defeat message
drawHangman(count,figure)
print('\nOut of guesses!')
print(f'Word was: {magic_word}')
input('Press enter to continue.')
#main
while True:
easy_mode = False
os.system('cls')
option = menuLayout()
#set easy_mode flag and change to normal mode
#TODO: easy flag in user selected word
if option == 'e':
option = 'n'
easy_mode = True
#run correct mode
if option.lower() == 's':
magic_word = selectWord()
elif option.lower() == 'n':
magic_word = wordFromFile()
elif option.lower() == 'q':
print('Thanks for playing')
break
#if somehow option other than predetermined is introduced, end loop
else:
print('Unexpected error')
break
game(magic_word,easy_mode)
|
44a3c5e35b62d1bb329b844a0aae4a1d58bab706
|
huit-sys/progAvanzada
|
/6.py
| 1,518 | 3.671875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 15:08:48 2019
@author: stitch
"""
#hacer un progrmaa en el que el ussuario introduzca el nombre de la comida que ordeno
#en un restaurante y su precio. despues, su programa debe calcular el subtotal, el iva,
#y la propina de toda la cuenta. La salida del programa dee parecerse a un ticket de restaurante.
#use un iva del 16% y una propina del 15% del subtotal. Los valores numericos deben tener dos decimales
A= str(input('introduzca el nombre de la comida: '))
a= float(input('introduzca el valor de la comida: '))
B= str(input('introduzca el nombre de la comida: '))
b= float(input('introduzca el valor de la comida: '))
C= str(input('introduzca el nombre de la comida: '))
c= float(input('introduzca el valor de la comida: '))
D= str(input('introduzca el nombre de la comida: '))
d= float(input('introduzca el valor de la comida: '))
E= str(input('introduzca el nombre de la comida: '))
e= float(input('introduzca el valor de la comida: '))
print('Platillo1: ' + A)
print('Platillo2: ' + B)
print('Platillo3: ' + C)
print('Platillo4: ' + D)
print('Platillo5: ' + E)
print('-------------------')
subtotal=a+b+c+d+e
print('subtotal: $%.2f ' % subtotal)
iva=subtotal*0.16
print('iva: $%.2f ' % iva)
propina= subtotal*0.15
print('propina: $%.2f '% propina)
print('-------------------')
print(' total')
print('-------------------')
total=subtotal+iva+propina
print('total: $%.2f' % total)
|
a73626f7b389af136ab945be353d198fa60e16e8
|
Caroline-Wendy/Python-Notes
|
/ABOP_Function.py
| 2,044 | 3.5 | 4 |
# -*- coding: utf-8 -*-
#====================
#File: abop.py
#Author: Wendy
#Date: 2013-12-03
#====================
#eclipse pydev, python3.3
#函数
def sayHello():
print('Hello World')
sayHello()
sayHello()
#带参数的函数
def printMax(a, b):
if a > b:
print(a, 'is maximum') #python自动生成空格
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)
x = 5
y = 7
printMax(x, y)
#全部变量
num = 50
def func():
global num #全局变量, 不建议使用
print('num is', num)
num = 2
print('Changed local num to', num)
func()
print('x is still', num)
#非局部变量
def func_outer():
x = 2
print('x is', x)
def func_inner():
nonlocal x #非局部变量, 函数内可见
x = 5
func_inner()
print('Changed local x to', x)
func_outer()
#默认参数
def say(message, times = 1):
print(message*times)
say('Caroline')
say('Wendy', 5)
#关键参数, 指定参数
def func(a, b=5, c=10):
print('a is', a, 'b is', b, 'c is', c)
func(1) #a的值必须要指定
func(2, c=50)
func(c = 100, a=5)
#可变参数, *number是数组, **keywords是字典(map)
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
print(key) #打印key
count += keywords[key]
return count
print(total(10, 4, 5, 6, Caroline = 50, Wendy = 100))
#返回值, 比较大小使用库函数max
def maximum(x, y):
if x>y:
return x
else:
return y
print(maximum(2, 3))
#表面return None
def someFunction():
pass
print(someFunction())
#函数文档
#格式: 首行以大写字母开始, 句号结尾, 次行空格, 接下来是描述
def Welcome(x, y):
'''
Welcome to Caroline's world.
Wendy and me will tell you how to write python.
'''
print(x)
print(y)
Welcome('Caroline', 'Wendy')
print(Welcome.__doc__)
help(Welcome) #帮助信息
|
488b698154161ce6520b54901874c0fef37a8502
|
anastyer/Python-projects
|
/генератор паролей.py
| 1,300 | 3.59375 | 4 |
import random
digit = '1234567890'
low_letters = 'qwertyuiopasdfghjklzxcvbnm'
up_letters = 'QWERTYUIOPASDFGHJKLZXCVBNM'
signs = '#$%^&*_+=?-@!'
chars = ''
n = int(input(' ? '))
length = int(input(' : '))
need_digit = input(' ? ( ) ')
need_low = input(' ? ( ) ')
need_up = input(' ? ( ) ')
need_sign = input(' , #$%^&*_+=?-@!? ( ) ')
delete_symbol = input(' il1Lo0O? ( ) ')
if need_digit.lower() == '':
chars += digit
if need_low.lower() == '':
chars += low_letters
if need_up.lower() == '':
chars += up_letters
if need_sign.lower() == '':
chars += signs
if delete_symbol.lower() == '':
for c in 'il1Lo0O':
chars = chars.replace(c, '')
def password_generate(length, chars):
password = ''
for j in range(length):
password += random.choice(chars)
print(password)
for _ in range(n):
password_generate(length, chars)
|
af7979b48e640ea6f094599f3f3015132f0f65ab
|
sroshan106/HackerRank-Solutions
|
/pairs.py
| 331 | 3.5625 | 4 |
#!/bin/python3
# Complete the pairs function below.
def pairs(k, arr):
arr= set(arr)
count=0
for i in arr:
if(i+k in arr):
count+=1
return count
nk = input().split()
n = int(nk[0])
k = int(nk[1])
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
print(result)
|
67a47f605c82a0d86d6b3aa220fb1d03455b389c
|
ItsTuukka/Ohjelmistotekniikka
|
/minigolf-game/src/field_elements/field.py
| 4,199 | 3.828125 | 4 |
import sys
import pygame
from field_elements.element import Element
from field_elements.ball import Ball
class Field:
"""A class for creating the field.
Attributes:
height, width: Dimensions of the current field
holes,
walls,
grass,
water,
light_sand,
dark_sand: Groups of sprite objects in the field
all_elements: A combined group of all of the other sprite groups
ball: A sprite object for the ball
"""
def __init__(self, field_map):
"""Constructor that creates sprite groups
for all the different elements on the field.
Args:
field_map: The map of the field as a matrix where different
values correspond to different elements.
"""
self.__cell_size = 15
self._height = len(field_map)
self._width = len(field_map[0])
self._holes = pygame.sprite.Group()
self._walls = pygame.sprite.Group()
self._grass = pygame.sprite.Group()
self._water = pygame.sprite.Group()
self._light_sand = pygame.sprite.Group()
self._dark_sand = pygame.sprite.Group()
self._all_elements = pygame.sprite.Group()
self._ball = None
self.place_elements(field_map)
def place_elements(self, field_map):
"""Method to place all the elements in their correct location based on the map
Args:
field_map: Locations for the elements
"""
for y_coord in range(self._height):
for x_coord in range(self._width):
cell = field_map[y_coord][x_coord]
norm_x = x_coord * self.__cell_size
norm_y = y_coord * self.__cell_size
if cell == 0:
self._holes.add(Element(norm_x, norm_y, 0))
elif cell == 1:
self._walls.add(Element(norm_x, norm_y, 1))
elif cell == 2:
self._grass.add(Element(norm_x, norm_y, 2))
elif cell == 3:
self._water.add(Element(norm_x, norm_y, 3))
elif cell == 4:
self._light_sand.add(Element(norm_x, norm_y, 4))
elif cell == 5:
self._dark_sand.add(Element(norm_x, norm_y, 5))
elif cell == 6:
self._ball = Ball(norm_x, norm_y)
self._grass.add(Element(norm_x, norm_y, 2))
self._all_elements.add(self._holes, self._walls, self._water,
self._grass, self._light_sand, self._dark_sand, self._ball)
def get_ball(self):
"""A method to access to the ball from outside of the class
Returns:
Ball: The ball sprite object
"""
return self._ball
def get_holes(self):
return self._holes
def get_dimensions(self):
return self._height*self.__cell_size, self._width*self.__cell_size
def update(self, display):
"""Updates all sprites in the class
Args:
display: The current pygame screen
"""
try:
self._all_elements.draw(display)
except pygame.error:
pass
def check_wall_hits(self):
"""Checks if the ball has hit the wall
Returns:
If there is contact, it returns the ball, else None.
"""
contact = pygame.sprite.spritecollide(
self._ball, self._walls, dokill=False)
return contact
def check_water_hits(self):
"""Checks if the ball has gone to water
Returns:
If there is contact, it returns the ball, else None.
"""
contact = pygame.sprite.spritecollideany(self._ball, self._water)
return contact
def in_hole(self):
"""A method to check if the hole ands the ball are colliding.
Uses a circle ratio instead of the default rectangle.
"""
in_hole = pygame.sprite.spritecollide(
self._ball, self._holes, False, pygame.sprite.collide_circle_ratio(0.3))
if in_hole:
print('you won')
pygame.quit()
sys.exit()
|
e91b3f52fbf9bb6f3de33c8190ddb7a86d38a802
|
931808901/GitTest
|
/day1/1025/demos/W4/day4/00Homework.py
| 2,957 | 3.515625 | 4 |
#! C:\Python36\python.exe
# coding:utf-8
'''
从1加到一亿,使用单线程、10并发进程、10并发线程分别求其结果,统计并比较执行时间
@结论:
·效率对比:多进程 > 多线程 ≈ 单线程
·为什么多进程最快?
多进程可以充分使用CPU【多核的并发计算能力】
·为什么多线程和点线程差不多?
多线程是伪并发
·既然多线程在效率上与单线程相差无几,多线程存在的意义是什么?
1、确实有多任务同时进行的需要
2、平摊每条线程阻塞、抛异常的风险(试想主线程被阻塞时,逻辑全线瘫痪)
@ 多线程 VS 多进程
·进程的资源开销远远大于线程,能多线程解决的就不用多进程
·计算密集型用多进程,IO密集型(读写文件、数据库、访问网络等)用多线程
'''
import multiprocessing
import time
import threadpool
def getTotal(begin, stop, dataList=None):
result = 0
for num in range(begin, stop + 1):
result += num
# if dataList!=None:
if dataList:
dataList.append(result)
return result
def singThread():
start = time.time()
result = getTotal(1, 10 ** 8)
end = time.time()
print(result, "耗时%.2f" % (end - start))
def multiProcessWay():
start = time.time()
with multiprocessing.Manager() as pm:
dataList = pm.list()
plist = []
for i in range(10):
p = multiprocessing.Process(target=getTotal, args=(i * 10 ** 7 + 1, (i + 1) * 10 ** 7, dataList))
p.start()
plist.append(p)
for p in plist:
p.join()
result = 0
for num in dataList:
result += num
end = time.time()
print(result, "耗时%.2f" % (end - start))
totalResult = 0
def onResult(result):
global totalResult
totalResult += result
def onTpoolResult(req, result):
global totalResult
totalResult += result
def processPoolWay():
start = time.time()
myPool = multiprocessing.Pool(10)
# def apply_async(self, func, args=(), kwds={}, callback=None,error_callback=None):
for i in range(10):
myPool.apply_async(getTotal, args=(i * 10 ** 7 + 1, (i + 1) * 10 ** 7), callback=onResult)
myPool.close()
myPool.join()
end = time.time()
print(totalResult, "耗时%.2f" % (end - start))
def threadPoolWay():
start = time.time()
arglist = []
for i in range(10):
arglist.append(([i * 10 ** 7 + 1, (i + 1) * 10 ** 7], None))
reqThreads = threadpool.makeRequests(getTotal, arglist, callback=onTpoolResult)
myPool = threadpool.ThreadPool(10)
for rt in reqThreads:
myPool.putRequest(rt)
myPool.wait()
end = time.time()
print(totalResult, "耗时%.2f" % (end - start))
if __name__ == "__main__":
# singThread()
# multiProcessWay()
# processPoolWay()
# threadPoolWay()
print("main over")
|
8e4aaa40eb00add78b7e12c00a4005025631ded5
|
Kevinloritsch/Buffet-Dr.-Neato
|
/Python Labs/5. Python More Casting/run5.py
| 167 | 3.796875 | 4 |
valueone = input("Please enter a first number: ")
valuetwo = input("Please enter a second number: ")
print(valueone+"*"+valuetwo)
print(int(valuetwo)*int(valueone))
|
70e729cd3ebc8118c9e7e0c51f8a6ec108bb5475
|
Ivanich99/Progect1
|
/Оценка вероятности работы устройства состоящего из нескольких элеметов.py
| 1,324 | 3.84375 | 4 |
import random
i = 0
result = 0
#v1 = float(input('Введите вероятность для A ')) На случай если вероятности для устройства задаются каждый раз
#v2 = float(input('Введите вероятность для B '))
#v3 = float(input('Введите вероятность для C '))
#v4 = float(input('Введите вероятность для D '))
#v5 = float(input('Введите вероятность для E '))
#v6 = float(input('Введите вероятность для F '))
v1 = 0.8 #на случай если не изменяется
v2 = 0.7
v3 = 0.95
v4 = 0.85
v5 = 0.9
v6 = 0.7
while i < 100:
a = random.uniform(0, 1)
b = random.uniform(0, 1)
c = random.uniform(0, 1)
d = random.uniform(0, 1)
e = random.uniform(0, 1)
f = random.uniform(0, 1)
#устройство не работает, если не работает один из модулей, 1 модуль а, второй b,c,d, причем модуль отключится при
#отключении только всех устройств в модуле
if a<= v1 and (b <= v2 or c <= v3 or d <= v4) and (e <= v5 or f <= v6):
result += 1
i+=1
result /=100
print(result)
|
967b3fd38554a22c5da23c0ddf7572ace0f07820
|
sumitpatra6/leetcode
|
/backtracking/letter_case_permutation.py
| 585 | 3.8125 | 4 |
def letter_case_permutation(S):
final_result = set()
def util(string, start, end):
if start == end:
final_result.add(''.join(string[:]))
return
if string[start].isdigit():
util(string, start+1, end)
else:
string[start] = string[start].upper()
util(string, start+1, end)
string[start] = string[start].lower()
util(string, start + 1, end)
util(list(S), 0, len(S))
print(final_result)
return list(final_result)
letter_case_permutation('a1b2')
|
a6939e0ee92c589fc3b09c7ed1ed8b2116bd51f4
|
Tom-Szendrey/Highschool-basic-notes
|
/Notes/Harder Dictionaries.py
| 919 | 4 | 4 |
inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['dagger', 'bedroll','bread loaf']
}
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
inventory["pocket"] = "seashell", "strange berry", "lint" #create pocket which is a list in in inventory
inventory["backpack"].remove("dagger") #removes dagger in backpack
inventory["gold"] += 50 #adds 50 cash money
inventory["backpack"].sort() #sorts backpack
print "This is your inventory." , inventory
print "This is your gold.", inventory["gold"]
print "This is what is in your backpack." , inventory["backpack"]
|
6ffc6a18bbd9a04db0b4d45901151a1c5fb0cb41
|
jmavis/CodingChallenges
|
/Python/Guess.py
| 1,095 | 4.25 | 4 |
#------------------------------------------------------------------------------
# Jared Mavis
# [email protected]
# Programming Assignment 3
# Guess.py - Generates a number from 1-10 and asks the user to guess up to 3 times reporting if the real number is higher or lower
#------------------------------------------------------------------------------
import random
intToWordList = ['first', 'second', 'third']
print ("\nI'm thinking of an integer in the range 1 to 10. You have three guesses.")
magicNumber = random.randint(1,10)
numGuesses = 0
maxGuesses = 3
while True:
currentGuess = int(input("\nEnter your " + intToWordList[numGuesses] + " guess: "))
numGuesses += 1
if currentGuess > magicNumber:
print ("Your guess is too high.", end="")
elif currentGuess < magicNumber:
print ("Your guess is too low.", end="")
else:
print ("You win!\n")
break
if numGuesses < maxGuesses:
print (" Guess again.")
else:
print (" You lose. \n\nThe number was " + str(magicNumber) + "\n")
break;
|
3aec47df044730a468a11d35536fbefec00258df
|
franciscojunior10/uri-answers
|
/1005.py
| 109 | 3.75 | 4 |
A = float(input(''))
B = float(input(''))
result = ((A * 3.5) + (B * 7.5)) / 11
print('MEDIA = %0.5f'%result)
|
974cd0777cfc233f5edf3e864cc3aae3f4d0e786
|
ArifSanaullah/Python_codes
|
/209.Try , Except - exception handling, python tutorial 207.py
| 424 | 4.125 | 4 |
# 209.Try , Except - exception handling, python tutorial 207
# exception
# try exception else finally
while True:
try:
age = int(input('please enter your age: ')) # seven
break
except ValueError:
print("invalid input...")
except:
print("unexpected error...")
if age < 18:
print("you can\'t play the game...!")
else:
print("you can play the game...!")
|
1951f3f37b1bf3fe2e9a5f3460976469a5d58a35
|
akjanik/Project-Euler
|
/problem-005.py
| 467 | 3.609375 | 4 |
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
#Brute force
a = 2520
step = 20
cond = True
while cond:
a += step
for i in range(20,0, -1):
if a % i:
break
cond = True
else:
if i == 2:
cond = False
print (a)
|
f20e9e24ead79c26635acb82b3060e875e468714
|
joaovictorgb/Python-Algorithms
|
/placar_futebol.py
| 1,079 | 3.90625 | 4 |
#Quantidades
Linhas = 10 ; Colunas = 2 ; mtimes = [] ;mplacar = [] ; vencedores = []
#Gerando as matrizes dos times e do placar
for i in range(Linhas):
mtimes.append([0] * Colunas)
for i in range (Linhas):
mplacar.append([0] * Colunas)
#Adiçao dos times e do placar
for i in range(Linhas):
for b in range (Colunas):
print('Digite os times que se enfrentaram', i+1, ':',end ='')
mtimes[i][b] =input('')
print()
for i in range(Linhas):
for b in range (Colunas):
print('Digite o placar da partida', i+1, ':',end ='')
mplacar[i][b] =int(input())
print()
#Laço verificador
for i in range(Linhas):
if mplacar[i][0] > mplacar[i][1] :
vencedores.append(mtimes[i][0])
elif mplacar[i][0] < mplacar[i][1]:
vencedores.append(mtimes[i][1])
#Condicionais para respostas de usuário
if len(vencedores) == 0:
print('Todos os jogos empataram')
else:
print('Times que ganharam:', end = '')
for t in range(len(vencedores) -1):
print(vencedores[t] , end = '-')
print(vencedores[t + 1])
|
74bd3b433a02610f3e746f1039386a2659401df1
|
KaySchus/Project-Euler
|
/Problem 1 - 50/Problem_10.py
| 351 | 3.515625 | 4 |
import math
def sieve(limit = 125000):
sieve = [True] * limit
sieve[0] = sieve[1] = False
primes = []
for (i, isprime) in enumerate(sieve):
if (isprime):
primes.append(i)
for n in range(i * i, limit, i):
sieve[n] = False
return primes
primes = sieve(2000000)
summation = 0
for prime in primes:
summation += prime
print(summation)
|
af4c78375ef7149b65e3601d12b60ae9f36d2ffc
|
jebrunnoe/Project-Euler
|
/problem55.py
| 409 | 3.546875 | 4 |
def palindrome(s):
if s == s[::-1]:
return True
return False
lychrels = list()
for n in range(1, 10000):
lychrel = True
s = str(n)
iterations = 0
result = n
while lychrel and iterations <= 50:
result = result + int(str(result)[::-1])
if palindrome(str(result)):
lychrel = False
iterations += 1
if lychrel: lychrels.append(s)
print lychrels, len(lychrels)
|
d4602dbcc1fc9f6882fa90607ae7868df42b458c
|
Hieunt27/GoogleKickStart_Solutions
|
/2020_RoundF/helper.py
| 474 | 3.5 | 4 |
from random import randint
print "100"
for T in range(100):
myDict=set()
n=0
while n<12:
x=randint(1,6)
y=randint(1,2*x-1)
if (x,y) in myDict:
continue
myDict.add((x,y))
n+=1
myDict=list(myDict)
result="6 "+str(myDict[0][0])+" "+str(myDict[0][1])+" "+str(myDict[1][0])+" "+str(myDict[1][1])+\
" 10"
print result
for i in range(2,12):
print str(myDict[i][0])+" "+str(myDict[i][1])
|
afeead076705c4b7ef8b5778792193067c84e4ad
|
mle8109/repo1
|
/CS_Python/DataStructure/linkedlist.py
| 1,867 | 4.1875 | 4 |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def addToFront(self, new_data):
newNode = Node(new_data)
newNode.next = self.head
self.head = newNode
def addToTail(self, new_data):
newNode = Node(new_data)
temp = self.head
if (temp == None):
self.head = newNode
else:
while (temp.next != None):
temp = temp.next
temp.next = newNode
def deleteNode(self, node_data):
found = False
current = self.head
if (current == None):
return
elif (current.data == node_data):
if (current.next == None):
self.head = None
else:
self.head = current.next
else:
while (current.next != None):
prev = current
current = current.next
if (current.data == node_data):
prev.next = current.next
print ("Node found and deleted")
found = True
if (not found):
print("Node does not exist")
def printList(self):
temp = self.head
while(temp):
print (temp.data)
temp = temp.next
#MAIN RUN
if __name__=='__main__':
lst = LinkedList()
lst.head = Node(1)
second = Node(2)
third = Node(3)
lst.head.next = second
second.next = third
lst.printList()
print("Add node 5 to the head of the list")
lst.addToFront(5)
lst.printList()
print("Add node to the end of the list")
lst.addToTail(8)
lst.printList()
print("Delete node")
lst.deleteNode(5)
lst.deleteNode(8)
lst.deleteNode(8)
lst.printList()
|
1373fb955938c3beaacadef4d5d0785e6cc73596
|
tiendong96/Python
|
/Practice/String/findAString.py
| 884 | 4.15625 | 4 |
# In this challenge, the user enters a string and a substring.
# You have to print the number of times that the substring occurs in the given string.
# String traversal will take place from left to right, not from right to left.
# https://www.hackerrank.com/challenges/find-a-string/problem
def count_substring(string, sub_string):
count = 0 #generic counter
for i in range(len(string)): #traverse through the string with the range = length of string in which case is 7
if string[i:].startswith(sub_string): #using the iterator, see if it starts with the substring. ABCDCDC start with CDC? no , next iteration, BCDCDC? no, CDCDC? yes
count += 1 #increment if found
return count
if __name__ == '__main__':
string = input().strip() #ABCDCDC
sub_string = input().strip() #CDC
count = count_substring(string, sub_string)
print(count) #2
|
582069e7c43e44b7cbc6b175867e6fd9e590f815
|
Alberts1995/Example
|
/Turtle/шар.py
| 573 | 4 | 4 |
import turtle
windows = turtle.Screen()
windows.title('мячь')
play = turtle.Turtle()
play.speed(0)
play.up()
play.goto(300, 300)
play.down()
play.hideturtle()
play.pensize(8)
play.color("yellow")
play.goto(300, -300)
play.goto(-300, -300)
play.goto(-300, 300)
play.goto(300, 300)
bool = turtle.Turtle()
bool.shape("circle")
bool.color("red")
bool.up()
dx = 3
dy = 2
while True:
x, y = bool.position()
if x + dx >= 300 or x + dx <= -300:
dx = -dx
if y + dy >= 300 or y + dy <= -300:
dy = -dy
bool.goto(x + dx, y+dy)
windows.mainloop
|
72b7a72d3d0ba14de258db56bf6a493fbff48c03
|
amrit2995/break_out_game
|
/player_bar.py
| 493 | 3.5625 | 4 |
from turtle import Turtle
direction = {'right': 0, 'left': 180}
class Player(Turtle):
def __init__(self):
super().__init__()
self.shape('square')
self.shapesize(stretch_wid=1, stretch_len=8)
self.penup()
self.color('white')
self.reset()
def left(self):
if self.xcor() > -320:
self.bk(40)
def right(self):
if self.xcor() < 320:
self.fd(40)
def reset(self):
self.goto(0, -250)
|
ce86c5a564b1ccf76bad36f0993eed84a15648be
|
ChrisHolley/toyProblems
|
/disemvowel.py
| 307 | 3.953125 | 4 |
def disemvowel(str: str):
vowelDict = {'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1, 'A': 1, 'E': 1, 'I': 1, 'O': 1, 'U': 1}
str = list(str)
print(str)
for idx, char in reversed(list(enumerate(str))):
if vowelDict.get(char) == True:
str.pop(idx)
return ''.join(str)
print(disemvowel('hello'))
|
ff750bcd7eb8f825b624ff219b3ec36310a09b90
|
ethan1022/yangsTriangle
|
/yangsTriangle.py
| 410 | 3.703125 | 4 |
# -*- coding: utf-8 -*-
def triangles(max):
n, result = 0, [1]
while n < max:
yield result
if len(result) >= 2:
result = [result[x] + result[x+1] for x in range(len(result) - 1)]
result.insert(0, 1)
result.append(1)
n = n + 1
return "done"
scale = input("input scale: ")
while scale.isdigit() == False:
scale = input("input scale: ")
g = triangles(int(scale))
for n in g:
print(n)
|
fe02b2d4a20405af920a08f78f7e66019007d106
|
charlie14516/AE402-python
|
/校長獎學金.py
| 311 | 3.921875 | 4 |
math_score=input('請輸入數學成績')
english_score=input('請輸入英文成績')
math_score=int(math_score)
english_score=int(english_score)
if((math_score>=90 and english_score>=90) or math_score==100 or english_score==100):
print('可得獎學金')
else:
print('無法得獎學金')
|
7c7c990f4719180d6227e562b690fe14da75bb22
|
marinme/learning
|
/Pythagorean Triples Checker/test_pythag.py
| 614 | 4 | 4 |
from pythag import pythag
import unittest
class TestPythag(unittest.TestCase):
def test_pythag(self):
# test basic inputs
self.assertTrue(pythag(3,4,5))
self.assertFalse(pythag(3,4,6))
def test_pythag_ordering(self):
self.assertEqual(pythag(3,4,5), pythag(5,3,4))
def test_pythag_short_input(self):
self.assertIn(pythag(3,4),[True,False]) # assumes it still returns a value by asking the user for input
def test_bad_input(self):
with self.assertRaises(ValueError):
pythag(2,3,4,5)
pythag(2,'a')
pythag(None,1)
|
3b76fab0a9cec9e06f7aeb582373dd1e77fd58ce
|
Retchut/MNUM-2020-2021
|
/exams/2015/4.py
| 433 | 3.53125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 14:33:25 2021
@author: Retch
"""
import math
def g(x): return 2*math.log(2*x)
def picard_peano(x0, n):
print("initial guess:", x0)
y0 = 0
for i in range(n):
y0 = g(x0)
x0 = y0
print("\niteration", i+1)
print("x =", x0)
return x0
x0 = 1.1
n = 1
x1 = picard_peano(x0, n)
res = x1 - x0
print(res)
|
8ad3e1de27ceb7e0c8cae7f9e153b5dfc09069d0
|
AdamZhouSE/pythonHomework
|
/Code/CodeRecords/2606/60771/285032.py
| 361 | 3.703125 | 4 |
#03
def binary(arr,l,r,x):
if r > l:
mid = int(l + (r-1)/2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary(arr,l,mid-1,x)
else:
return binary(arr,mid+1,r,x)
else:
return -1
num = eval(input())
n = int(input())
outcome = binary(num,0,len(num)-1,n)
print(outcome)
|
d03d72ec72619f8ed37762f1d75ea0b434310563
|
real-ashd/AutomateBoringStuffWithPython
|
/FileSystem/DeletingFiles.py
| 1,147 | 3.546875 | 4 |
#Delting files and folders
#Be careful as this doesn't sent the file/folders to Recycle bin
import shutil
import os
"""Using os module"""
# print(os.unlink(r'C:\Users\Abc\Documents\Folder1\hello.txt')) #Use os.unlink() to delete a file
# print(os.rmdir(r'C:\Users\Abc\Documents\Folder1\Folder2')) #To use os.rmdir() the folder must be completely empty
"""Using shutil module"""
# print(shutil.rmtree(r'C:\Users\Abc\Documents\Folder1\Folder2')) #shutil module has a function shutil.rmtree() which removes the complete tree
#Program to verify what we are deleting
#use the below program by commenting and uncommenting the statements to verify
"""
print(os.getcwd())
os.chdir('C:\\Users\\Abc\\Documents\\Folder1')
for filename in os.listdir():
if filename.endswith('.txt'):
#os.unlink
print(filename)
"""
print("Using send2trash module.")
#Install the send2trash module using pip as it doesn't come with standard python package
#py -m pip install send2trash(Windows) pip install send2trash(Linux)
import send2trash
# send2trash.send2trash((r'C:\Users\Abc\Documents\Folder1\hello.txt')) #Check your recycle bin
|
1e63b27ef7663ac451168b12608946fc88dcc3e4
|
nikrhem/simmm
|
/sum.py
| 110 | 3.578125 | 4 |
a = int(input())
m = 0
if a > 0:
for i in range(1,a+1):
m = m + i
print(m)
else :
print("invalid")
|
ed6f178101cdc1c2829ca98105e6c8320231b309
|
L200170115/prak_ASD_C
|
/Modul8/No_3.py
| 947 | 4.03125 | 4 |
class stack ():
def __init__ (self): #membuat stack kosong
self.item = []
def empty (self): #mengembalikan nilai bolean yang menunjukan apakah stack itu kosong
return len(self) == 0
def __len__ (self):#mengembalikan banyaknya item di stack
return len(self.item)
def peek(self):# mengembalikan nilai posisi atas tanpa menghapus dan mengembalikan nilai dari item yang paling atas
assert not self.empty()
return self.item[-1]
def pop(self):#mengembalikan nilai posisi atas lalu menghapus, stack kosong tidak dapat kosong
assert not self.empty()
return self.item.pop()
def push(self, data): #mendorong item ke stact, menambah item ke puncak stack
self.item.append(data)
nilai = stack()
for i in range (16):
if i % 3 == 0 :
nilai.push(i)
st = ''
for i in range(len(nilai)):
st = st + " " +str(nilai.pop())
print (st)
|
bcd1281e7106b867dd6df6af17a7898a37086af7
|
Alexandra323/car_package
|
/car_package/cars_module.py
| 1,240 | 3.96875 | 4 |
class Car():
def __init__(self, make, model, year):
self.make = make
self.model =model
self.year = year
self.odometr = 0
def car_description(self):
print(f"Car info:{self.make},{self.model}, {self.year}")
def read_odometr(self):
print(f"your odometr shows: {self.odometr}")
def set_odometr(self, miles):
if miles > self.odometr:
self.odometr = miles
else:
print(f"You can not set the odometr of less of {self.odometr}")
class ElectricCar(Car):
def __init__(self, make, model, year, battery =75):
super().__init__(make, model, year)
self.battery = battery
def car_description(self):
msg = f"Car info:{self.make}, {self.model}, {self.year}, \n"
msg +=f"battery capacity: {self.battery} -kWh."
print(msg)
def get_range(self):
if self.battery > 100:
msg = "This car has range of 320 miles fully charged battery."
elif self.battery <80:
msg = f"This ca has range of 250 miles with full charge."
else:
msg = f"THis car has range of around 290 miles with full charge."
print(msg)
|
5a3e022e7d5ede996408f36bfa39c1017b5af213
|
KimiHsieh/I2DL_19S
|
/Ex1/exercise_code/classifiers/softmax.py
| 8,818 | 3.5625 | 4 |
"""Linear Softmax Classifier."""
# pylint: disable=invalid-name
import numpy as np
from .linear_classifier import LinearClassifier
def cross_entropy_loss_naive(W, X, y, reg):
"""
Cross-entropy loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# pylint: disable=too-many-locals
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
############################################################################
# TODO: Compute the cross-entropy loss and its gradient using explicit #
# loops. Store the loss in loss and the gradient in dW. If you are not #
# careful here, it is easy to run into numeric instability. Don't forget #
# the regularization! #
############################################################################
#set parameters
N = X.shape[0] # # N examples
C = W.shape[1] # # C classes
D = X.shape[1] # # D features(Domension)
W = W.T
X = X.T
y = y.T
# Initialization
y_hat = np.zeros((C,N))
z = np.zeros((C,N))
dz = np.zeros(z.shape)
dW = np.zeros(W.shape)
z_sum = 0
L = np.zeros((N,))
J = 0
# set input for softmax
for c in range(C):
for n in range(N):
for d in range(D):
z[c,n] += W[c,d]* X[d,n] # z = input of activation(softmax)
# print("naive = " + str(z[1,1:20]))
#softmax
z_exp = np.zeros(z.shape)
ovfl = np.max(z) # overflow-prevent term
for n in range(N):
z_sum = 0
for c in range(C):
z_exp[c,n] = np.exp(z[c,n]-ovfl)
z_sum = z_sum + z_exp[c,n]
for c in range(C):
y_hat[c,n] = z_exp[c,n] / z_sum
#loss fuction L
# print(y_hat[1,1:20])
for n in range(N):
for c in range(C):
if(c == y[n,]):
L[n] = -np.log(y_hat[c,n]) # N sample's L
#cost function J --sum of L of N samples
for n in range(N):
J += L[n]
J = J/N
loss = J + reg
#gradient dw
for n in range(N):
for c in range(C):
if(c == y[n]):
dz[c,n] = y_hat[c,n]-1
else:
dz[c,n] = y_hat[c,n]
for c in range(C):
for d in range(D):
for n in range(N):
dW[c,d] += dz[c,n] * X.T[n,d]/N
for c in range(C):
for d in range(D):
dW[c,d] += reg * W[c,d]
dW = dW.T
############################################################################
# END OF YOUR CODE #
############################################################################
return loss, dW
def cross_entropy_loss_vectorized(W, X, y, reg):
"""
Cross-entropy loss function, vectorized version.
Inputs and outputs are the same as in cross_entropy_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
############################################################################
# TODO: Compute the cross-entropy loss and its gradient without explicit #
# loops. Store the loss in loss and the gradient in dW. If you are not #
# careful here, it is easy to run into numeric instability. Don't forget #
# the regularization! #
############################################################################
# set parameters
N = X.shape[0] # # N examples
C = W.shape[1] # # C classes
D = X.shape[1] # # D features(Domension)
X = X.T
y = y.T
# Initialization
dZ = np.zeros((C,N))
# set input for softmax
z = np.dot(W.T,X)
#softmax
ovfl = np.max(z, axis=0, keepdims=True) # overflow-prevent term
# print("ovfl =" +str(ovfl.shape))
z_exp = np.exp(z-ovfl)
z_sum = np.sum(z_exp, axis = 0, keepdims = True)
# print("z_exp =" +str(z_exp.shape))
# print("z_sum.shape =" +str(z_sum.shape))
y_hat = z_exp/z_sum # y_hat = output of softmax
# print("y_hat =" +str(y_hat.shape))
# print(y_hat[1,1:20])
#cross entropy/cost func batch
J = (-1 / N ) * np.sum(np.log(y_hat[y,np.arange(N)]))
# print("J =" +str(J))
loss = J + 0.5 * reg * np.sum(W*W)
# print(" loss =" +str( loss))
#gradient
dZ[:] = y_hat
dZ[y,np.arange(N)] = y_hat[y,np.arange(N)] - 1
dW = (1/N) * ( np.dot(X,dZ.T))
dW += reg*W
############################################################################
# END OF YOUR CODE #
############################################################################
return loss, dW
class SoftmaxClassifier(LinearClassifier):
#This is inheritance
#SoftmaxClassifier is child class. LinearClassifier is parent class
"""The softmax classifier which uses the cross-entropy loss."""
def loss(self, X_batch, y_batch, reg):
return cross_entropy_loss_vectorized(self.W, X_batch, y_batch, reg)
def softmax_hyperparameter_tuning(X_train, y_train, X_val, y_val):
# results is dictionary mapping tuples of the form
# (learning_rate, regularization_strength) to tuples of the form
# (training_accuracy, validation_accuracy). The accuracy is simply the
# fraction of data points that are correctly classified.
results = {}
best_val = -1
best_softmax = None
all_classifiers = []
learning_rates = [1e-7, 5e-7]
regularization_strengths = [2.5e4, 5e4, 6e3]
############################################################################
# TODO: #
# Write code that chooses the best hyperparameters by tuning on the #
# validation set. For each combination of hyperparameters, train a #
# classifier on the training set, compute its accuracy on the training and #
# validation sets, and store these numbers in the results dictionary. #
# In addition, store the best validation accuracy in best_val and the #
# Softmax object that achieves this accuracy in best_softmax. # #
# #
# Hint: You should use a small value for num_iters as you develop your #
# validation code so that the classifiers don't take much time to train; #
# once you are confident that your validation code works, you should rerun #
# the validation code with a larger value for num_iters. #
############################################################################
for lr in learning_rates:
for rs in regularization_strengths:
softmax = SoftmaxClassifier()
loss = softmax.train(X_train, y_train, learning_rate=lr, reg=rs,
num_iters=1500, verbose=True)
y_train_pred = softmax.predict(X_train)
y_val_pred = softmax.predict(X_val)
val_accuracy = np.mean(y_val == y_val_pred)
if val_accuracy > best_val:
best_val = val_accuracy
best_softmax = softmax
results[(lr, rs)] = (np.mean(y_train == y_train_pred), val_accuracy)
all_classifiers.append(softmax)
############################################################################
# END OF YOUR CODE #
############################################################################
# Print out results.
for (lr, reg) in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy))
print('best validation accuracy achieved during validation: %f' % best_val)
return best_softmax, results, all_classifiers
|
0a1f4a077dd56b59ba660c1441c4b3e2b396fb0a
|
Aasthaengg/IBMdataset
|
/Python_codes/p03852/s139643247.py
| 143 | 3.625 | 4 |
c=input()
a='aiueo'
lst=list(a)
count=0
for i in lst:
if c==i:
count+=1
if count>0:
print('vowel')
else:
print('consonant')
|
82f3180ffdf047bc4e444f3a3dc11c80a80cf119
|
leonh/pyelements
|
/examples/a2_sequences.py
| 1,274 | 4.3125 | 4 |
"""
1.Tuple : Immutable
ordered sequence of items
Items can be of mixed types, including collection types
2.Strings : Immutable•
Conceptually very much like a tuple
3.List : Mutable
ordered sequence of items of mixed types
"""
from examples.a1_code_blocks import line # import from this package
# import sys
# print(sys.path)
tu: tuple = (23, 'abc', 4.56, (2, 3), 'def')
print(line(), tu[1])
print(line(), tu[1][2])
print(line(), tu[-2])
# print(line(), tu[2][1]) # what will this do?
# slice to return a copy of a subset
t = tu[1:3]
print(line(), t)
# '+' operator concatenation of sequences produces a new instance
print(line(), 'foo' + ' ' + 'bar')
# 'in' operator
print(line(), 23 in tu)
print(line(), 'lord lucan' in tu)
# Be careful: the in keyword is also used in the syntax
# of for loops and list comprehensions.
# * operator produces a new tuple, list, or string
# that “repeats” the original content.
tu_3x = (1, 2, 3) * 3
print(line(), tu_3x)
# more about lists
li = ['a', 'd', 'a', 'm']
print(line(), li.index('a'))
print(line(), li.count('a'))
# dir() lists the attributes and methods available to an object.
print(line(), dir(li))
# other methods available to lists
# li.sort()
# print(li)
# li.reverse()
# alternative to dir()
# help(li)
|
00cf636d063792b4a2402a779d80f23a227df2e5
|
InverseLina/python-practice
|
/Base/TestFunction.py
| 2,113 | 3.59375 | 4 |
# encoding=utf-8
__author__ = 'Hinsteny'
'''
关于高阶函数的使用示例,即函数式编程
'''
from functools import reduce
from operator import itemgetter
def test_map():
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
return "Test map success!"
def test_reduce():
def f(x, y):
return x * 10 + y
r = reduce(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(r)
return "Test reduce success!"
def test_filter():
def is_odd(n):
return n % 2 == 1
r = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
return "Test reduce success!"
def test_sorted():
def sort_by_name(*args):
return itemgetter(0)
students = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
# 自定义排序函数
r = sorted(students, key=sort_by_name(0))
print(list(r))
# itemgetter函数可以实现多维排序
r = sorted(students, key=itemgetter(0))
print(list(r))
# lambda表达式
r = sorted(students, key=lambda t: t[1])
print(list(r))
# 倒置排序好的列表
r = sorted(students, key=itemgetter(1), reverse=True)
print(list(r))
return "Test sort success!"
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
def test_return_fun(*args):
f1 = lazy_sum(1, 3, 5, 7, 9)
f2 = lazy_sum(1, 3, 5, 7, 9)
print(f1 == f2)
print(f1())
print(f2())
# 闭包实现
def count():
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
def test_closure():
f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
def test_anonymous_function():
# 匿名函数
f = lambda x: x * x
print(f(5))
# Do test
if __name__ == "__main__":
test_map()
test_reduce()
test_filter()
test_sorted()
test_return_fun()
test_closure()
test_anonymous_function()
|
57091f8b2bfade335482f73f74a4a289c12c8b14
|
shubhii0206/Project-Euler
|
/Problem4_11/largest_palindrome.py
| 823 | 3.78125 | 4 |
import math
def upper_limit(n):
return int(math.pow(10, n) - 1)
def lower_limit(n):
return int(1 + (upper_limit(n) / 10))
def reverse(num):
rev = 0
while num > 0:
dig = num % 10
rev = rev * 10 + dig
num = num // 10
return rev
def isPalindrome(num):
return num == reverse(num)
def largest_palindrome(n):
start = lower_limit(n)
end = upper_limit(n)
max_product = 0
for i in range(end, start - 1, -1):
for j in range(i, start - 1, -1):
product = i * j
if product < max_product:
break
elif isPalindrome(product) and product > max_product:
max_product = product
return max_product
def problem4():
return largest_palindrome(3)
|
d9510d01578717079d08df59fc05dc84b42e77f1
|
angusmacdonald/sorting-algorithm-analysis
|
/src/sortingalgorithms/insertionsort.py
| 3,914 | 3.953125 | 4 |
import logging
import Monitoring
"""
Simple implementation
Efficient for (quite) small data sets
Adaptive, i.e. efficient for data sets that are already substantially sorted: the time complexity is O(n + d), where d is the number of inversions
More efficient in practice than most other simple quadratic, i.e. O(n2) algorithms such as selection sort or bubble sort; the best case (nearly sorted input) is O(n)
Stable, i.e. does not change the relative order of elements with equal keys
In-place, i.e. only requires a constant amount O(1) of additional memory space
Online, i.e. can sort a list as it receives it
http://en.wikipedia.org/wiki/Insertion_sort
Worst case performance O(n2)
Best case performance O(n)
Average case performance O(n2)
Worst case space complexity O(n) total, O(1)
The size of list for which insertion sort has the advantage varies by environment and implementation, but is typically between eight and twenty elements.
"""
"""
Starts off (in the outer loop) looping from the second element till the end of the array. For every outer loop it is trying to find the highest place in
the array to place array[i] (the key). It does this by starting from i and going back towards the start of the array. It pushes
the key down the array until no further improvement can be made. It doesn't have to assign the key to a new position every time - it only
pushes up the value in j to j+1. It assigns the key when no further improvement can be made.
It then increments i so that it can try to find the best position for the key.
This is good if an array is already mostly sorted, but could result in a lot of unnecessary back and forth if the next value up (i+1)
has to take the place of i, and so on.
"""
def insertionSort(array , eval=Monitoring.Monitor()):
for i in range(1, (len(array))): # start off on second element
key = array[i] #the current value we're trying to push up the array.
j= i-1 #initially this is the first element
logging.debug("i is {0:d}, j is {1:d}, key is {2:d}, array is {3}".format(i, j, key, array))
done = False
while not done:
eval.incrementComparisons()
if array[j] > key: #if the first element is greater than the second element, GET READY TO swap them.
array[j+1] = array[j] #there is an improvement to be made, so swap the higher value with the one above it in the array.
eval.incrementMoves()
j = j-1 # go down to the next element to see if it can be moved even further.
logging.debug("improvement to be made for {0:d}, j= {1:d}, array={2}".format(key, j, array))
if j < 0: #if j is >= 0, compare this element with the current ith element; if not, increment i.
done = True
else: # if the jth element is smaller than the ith element we're done (because the start of the list -before i- is already sorted)
done = True
logging.debug("\t array[{0:d}]={1:d}".format(j+1, key))
array[j+1] = key #j+1 is the position on which we became 'done' - i.e. the position for which the key value will be placed.
#if no better place was found this assignment has no affect
return array
if __name__ == '__main__':
example = [2,6,7,2,6,9,9,1,1,5]
logging.basicConfig(level=logging.DEBUG)
eval= Monitoring.Monitor()
print "Before : ", example
insertionSort(example, eval)
print "After : ", example
print "Number of comparisons: {0}\nNumber of moves: {1}".format(eval.numberOfComparisons, eval.numberOfMoves)
'''
badInsertionSortExample = [x for x in range(10, 1, -1)]
print "Before : ", badInsertionSortExample
insertionSort(badInsertionSortExample)
print "After : ", badInsertionSortExample
'''
|
70545f6febab448218c41ed6d645c461a03bf6ac
|
probbe/python_u
|
/PalindromeCheck.py
| 123 | 3.9375 | 4 |
#checks whether a passed in string is palindrome or not.
def palindrome(s):
reverse = s[::-1]
return s == reverse
|
db13c6b98eb2cdf65c806d18dac00674e58a1be3
|
sohampatne/python_basics
|
/loops/04-diamond.py
| 636 | 4.03125 | 4 |
diamondLevel = int(input('Please enter diamond level (must be even number odd number): '))
counter = 1
starCounter = 1
dashCounter = diamondLevel - 1
if diamondLevel%2 == 0 :
print('Please enter odd value!')
else :
diamondLevel = diamondLevel//2 + 1
while diamondLevel >= counter :
print(' ' * dashCounter + '*' * starCounter)
counter += 1
starCounter += 2
dashCounter -= 1
starCounter -= 4
dashCounter+= 2
counter = 1
while diamondLevel > counter :
print(' ' * dashCounter + '*' * starCounter)
counter += 1
starCounter -= 2
dashCounter += 1
|
f8e5fcd7bda104c16f9e7c093f31086ae2df3910
|
mka2011/Machine-Learning-Projects
|
/Perceptron_Algorithm/Perceptron.py
| 3,305 | 3.515625 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 18:36:10 2020
@author: manavagrawal
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
"""For getting training set"""
def getTrainVal(gate):
x = np.array([[1,0,0],[1,0,1],[1,1,0],[1,1,1]])
y = np.array([])
if gate == "AND" :
y = np.append(y,[0,0,0,1])
elif gate == "OR" :
y = np.append(y,[0,1,1,1])
elif gate == "NAND" :
y = np.append(y,[1,1,1,0])
else :
y = np.append(y,[1,0,0,0])
return x,y
def sigmoid(val):
val = np.array(val)
return 1 / (1 + np.exp(-val))
"""ANN function, returns weights and list of change in weight per iteration"""
def getWeight(x,y):
weight = np.random.rand(3)
weight2 = np.random.rand(3)
cost = list()
epochs = 1000
for i in range(epochs):
index = np.random.randint(0,3)
changeInWeight_temp = (y[index] - sigmoid(x[index] @ weight.T))
cost.append(changeInWeight_temp)
changeInWeight = (changeInWeight_temp * x[index])
weight = weight + changeInWeight
changeInWeightBatch = 0.1*((y - sigmoid(x @ weight2.T)) @ x)
weight2 = weight2 + changeInWeightBatch
return weight2,cost
"""returns predicted output against test set"""
def predict(weight,x_train):
pred = weight @ x_train.T
for i in range(len(pred)):
if pred[i] <= 0:
pred[i] = 0
else:
pred[i] = 1
return pred
"""Calculates accuracy against test set ouptut"""
def calcAccuracy(y_pred,y_test):
acc = 0
for i in range(len(y_pred)):
if y_pred[i] == y_test[i]:
acc += 1
return (acc/len(y_pred) * 100)
"""For plotting multiple graphs"""
fig, axs = plt.subplots(4, 1, figsize=(15, 12))
e1 = 1000
"""Running prediction algorithm for AND gate"""
x_train, y_train = getTrainVal("AND")
weight,cost = getWeight(x_train,y_train)
y_pred = predict(weight, x_train)
print("The accuracy is : ",calcAccuracy(y_pred,y_train),"%")
axs[0].plot(range(e1),cost)
axs[0].set_ylim([-1, 1])
axs[0].set_xlabel("Epochs")
axs[0].set_ylabel("Change in Weight")
"""Running prediction algorithm for NAND gate"""
x_train2, y_train2 = getTrainVal("NAND")
weight2, cost2 = getWeight(x_train2, y_train2)
y_pred2 = predict(weight2, x_train2)
print("The accuracy is : ",calcAccuracy(y_pred2,y_train2),"%")
axs[1].plot(range(e1),cost2)
axs[1].set_ylim([-1, 1])
axs[1].set_xlabel("Epochs")
axs[1].set_ylabel("Change in Weight")
"""Running prediction algorithm for OR gate"""
x_train3, y_train3 = getTrainVal("OR")
weight3, cost3 = getWeight(x_train3, y_train3)
y_pred3 = predict(weight3, x_train3)
print("The accuracy is : ",calcAccuracy(y_pred3,y_train3),"%")
axs[2].plot(range(e1),cost3)
axs[2].set_ylim([-1, 1])
axs[2].set_xlabel("Epochs")
axs[2].set_ylabel("Change in Weight")
"""Running prediction algorithm for NOR gate"""
x_train4, y_train4 = getTrainVal("NOR")
weight4, cost4 = getWeight(x_train4, y_train4)
y_pred4 = predict(weight4, x_train4)
print("The accuracy is : ",calcAccuracy(y_pred4,y_train4),"%")
axs[3].plot(range(e1),cost4)
axs[3].set_ylim([-1, 1])
axs[3].set_xlabel("Epochs")
axs[3].set_ylabel("Change in Weight")
|
d9cddad7d9ab2aeb1ec0d15431c1e2d1a464be9f
|
basvandriel/learning-python
|
/input.py
| 184 | 4.15625 | 4 |
# User input
name = input('Name: ')
age = input('Age: ')
print('Hello,', name, '. You are', age, 'years old')
# Type conversion in input
num = input('Number: ')
print(int(num) - 5)
|
a50b6b8ad280414e20d3293b1626cc8d0b1d01d2
|
syurskyi/Algorithms_and_Data_Structure
|
/_algorithms_challenges/exercism/exercism-master(1)/word-count/word_count.py
| 292 | 4.09375 | 4 |
import re
def count_words(sentence):
results = {}
words = re.findall(r"[a-zA-Z0-9]+'?[a-zA-Z0-9]+|[a-zA-Z0-9]", sentence.lower())
print(words)
for word in words:
if word.lower() not in results:
results[word.lower()] = words.count(word)
return results
|
f07a1904b3cc43143f8a840cadb3ee71433c18c2
|
coderabbit6/python
|
/Python网络爬虫/爬虫小例子/多进程的使用.py
| 1,283 | 3.578125 | 4 |
from multiprocessing import Process,Pool
import time
import os
# import calendar
def run(name):
print("{0} is running".format(name))
time.sleep(3)
print("{0} is ending".format(name))
if __name__ == '__main__':
p = Pool(10)
for i in range(10):
print("{0} is running".format(i))
p.apply_async(run,args=(i,))
p.close()
p.join()
print("hhh")
# -*- coding:utf-8 -*-
# from multiprocessing import Process,Pool
# import os,time
# def run_proc(name): ##定义一个函数用于进程调用
# for i in range(5):
# time.sleep(0.2) #休眠0.2秒
# print("{0} is running".format(name))
# #执行一次该函数共需1秒的时间
# if __name__ =='__main__': #执行主进程
# mainStart = time.time() #记录主进程开始的时间
# p = Pool(8) #开辟进程池
# for i in range(16): #开辟14个进程
# p.apply_async(run_proc,args=('Process'+str(i),))#每个进程都调用run_proc函数,
# #args表示给该函数传递的参数。
# p.close() #关闭进程池
# p.join() #等待开辟的所有进程执行完后,主进程才继续往下执行
# mainEnd = time.time() #记录主进程结束时间
|
8ca51187994fe7ba61936e8bca41a3a7db107f9f
|
manastole03/Programming-practice
|
/python/String/0's_at_left.py
| 112 | 3.921875 | 4 |
str=input('Enter a string: ')
wid=int(input('Enter width: '))
print('Left 0s to given string- ',str.zfill(wid))
|
b0e0e076b215d9ff493c154d3978de6b7146bc79
|
ngoctrong2009/KIEUNGOCTRONG_57132025
|
/swap.py
| 160 | 3.59375 | 4 |
print("nhap a :")
a = float(input())
print("nhap b :")
b = float(input())
tam = a
a = b
b = tam
print("a va b sau khi hoan doi")
print("a = ",a)
print("b = ",b)
|
bc0b6ce6ef5d8d3cfd37f8dd9e4c8ce7b4ff02b8
|
rainydyinlondon/pythonbasicapplication
|
/propertiestekrar2.py
| 1,854 | 3.65625 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 15:53:02 2021
@author: Feyza
"""
class Product:
def __init__(self,name,price): #Oluşturulan Nesne için çalışacak kodlar
self.name=name
if price>=0: # (self,name,price): parametre olarak gelicek değer >=0 mı diye kontrol ediyoruz...
self._price=price #Encapsulation kafası..
else:
raise ValueError(" Heyyy seni çılgın fiyatı için negatif değer ataması yapılamaz...")
#Decorator Kullanımı
@property
def price(self): #Get komutu gibi düşünebilirsin..
return self._price
@price.setter # Bilgi set etme olanağını sağlıyor / def set_price(self,value): gibi düşünebilirsin....
def price(self,value):
if value>=0: # (self,value): dışardan gönderilen/ (parametre olarak gelicek değer) >=0 mı diye kontrol ediyoruz...
self._price=value
else:
raise ValueError("Rainyy Ürün fiyatı için negatif değer ataması yapılamaz...")
p=Product("Iphone",9000)
# print(p.price)
p.price=-8000
print(p.price) # @price.setter çalıştırıldı...
# def set_price(self,value):
# if value>=0: # (self,value): parametre olarak gelicek değer >=0 mı diye kontrol ediyoruz...
# self._price=value
# else:
# raise ValueError("Ürün fiyatı için negatif değer ataması yapılamaz...")
# def get_price(self):
# return self._price
# p=Product("Iphone",9000)
# p.set_price(900)
# # p.price=-900
# """print(p.price) # Bu şekilde çağıramıyoruz çünkü ..... AttributeError: 'Product' object has no attribute 'price' """
# p.get_price()
|
ff3e25128abc916d609c18161d6fd04481871b3b
|
ikostan/Exercism_Python_Track
|
/bank-account/bank_account.py
| 2,202 | 3.953125 | 4 |
import threading
class BankAccount(object):
"""
Simulate a bank account supporting opening/closing,
withdrawals, and deposits of money.
"""
def __init__(self):
self._balance = 0.0
self._is_opened = False
self._lock = threading.Lock()
def get_balance(self) -> float:
"""
Returns current balance
:return:
"""
self._check_is_account_opened()
return self._balance
def open(self) -> None:
"""
Simulate a bank account supporting opening
:return:
"""
if not self._is_opened:
self._is_opened = True
else:
raise ValueError("ERROR: account already opened")
def deposit(self, amount) -> None:
"""
Clients can make deposits
:param amount:
:return:
"""
self._check_is_account_opened()
BankAccount._check_is_negative_amount(amount)
with self._lock:
self._balance += amount
def withdraw(self, amount) -> None:
"""
Clients can make withdrawals
:param amount:
:return:
"""
self._check_is_account_opened()
BankAccount._check_is_negative_amount(amount)
with self._lock:
if amount <= self.get_balance():
self._balance = self._balance - amount
else:
raise ValueError("ERROR: insufficient balance")
def close(self) -> None:
"""
It should be possible to close an account
:return:
"""
self._check_is_account_opened()
self._is_opened = False
self._balance = 0.0
def _check_is_account_opened(self) -> None:
"""
Operations against a closed account must fail
:return:
"""
if not self._is_opened:
raise ValueError('ERROR: account is closed.')
@staticmethod
def _check_is_negative_amount(amount) -> None:
"""
Cannot withdraw or deposit negative amount
:param amount:
:return:
"""
if amount < 0:
raise ValueError("ERROR: Cannot withdraw/deposit negative amount")
|
a928fb214a14ac1617af688db59075e6be5ee7d6
|
haiou90/aid_python_core
|
/day16/exercise_personal/07_exercise.py
| 352 | 3.640625 | 4 |
list01 = [54,43,23,67,28,69,90]
def get_number(list_target):
list_result = []
for number in list_target:
list_result.append(number % 10)
return list_result
result = get_number(list01)
print(result)
def get_number(list_target):
for number in list_target:
yield number % 10
for num in get_number(list01):
print(num)
|
9a4696fc9d87fe8e2dfc665ecc2574b49085b5ca
|
jongin1004/algorithm-coding_test-
|
/문제/count_of_primes.py
| 667 | 3.65625 | 4 |
def isPrimes(x): # 소수인지 검증하는 함수 선언
for i in range(2, x): # 2부터 x보다 작은 값까지 for문
if x % i == 0: # i값으로 x를 나눴을 때 딱 나뉘어 떨어지면, 소수가 아니므로 False 리턴
return False
return True
num = int(input()) # n을 입력 받음
primesList = [] # 소수를 넣을 리스트
for i in range(num-1, 1, -1): # num이 2이하 일 때에는 for문이 0번 돌기 때문에 알아서, 소수 카운트는 0
if isPrimes(i) == True: # 소수일 떄
primesList.append(i) # 소수 리스트에추가
print(len(primesList)) # len함수로 리스트 count
|
bc87e25dd96b56ee3fac4296caabc46433282f80
|
ImtiazVision/Python
|
/HW Chp 7/ex16.py
| 1,821 | 3.625 | 4 |
# c05ex02.pyw
# An archery target.
import math
from graphics import *
def targetWindow():
win = GraphWin("Archery Scorer", 400, 400)
win.setCoords(-6, -6, 6, 6)
win.setBackground("gray")
center = Point(0,0)
# Draw the target
c1 = Circle(center, 5)
c1.setFill("white")
c1.draw(win)
c2 = Circle(center, 4)
c2.setFill("black")
c2.draw(win)
c3 = Circle(center, 3)
c3.setFill("blue")
c3.draw(win)
c4 = Circle(center, 2)
c4.setFill("red")
c4.draw(win)
c5 = Circle(center, 1)
c5.setFill("yellow")
c5.draw(win)
return win
def drawInterface(win):
msg = Text(Point(0,5.5), "Click where arrow lands")
msg.setStyle("bold")
msg.setSize(14)
msg.draw(win)
arrowBox = Text(Point(-4,-5.5),"Arrow: ")
arrowBox.setStyle("bold")
arrowBox.draw(win)
totalBox = Text(Point(4,-5.5), "Total: ")
totalBox.setStyle("bold")
totalBox.draw(win)
return msg, arrowBox, totalBox
def getScore(pt):
x,y = pt.getX(), pt.getY()
dist = math.sqrt(x*x + y*y)
if dist <= 1:
score = 9
elif dist <= 2:
score = 7
elif dist <=3:
score = 5
elif dist <= 4:
score = 3
elif dist <= 5:
score = 1
else:
score = 0
return score
def main():
win = targetWindow()
msg, arrowBox, totalBox = drawInterface(win)
arrow = 0
total = 0
for i in range(5):
hit = win.getMouse()
dot = Circle(hit, 0.1)
dot.setFill("green")
dot.draw(win)
score = getScore(hit)
arrowBox.setText("Arrow: {0:1}".format(score))
total = total + score
totalBox.setText("Total: {0:2}".format(total))
msg.setText("Click anywhere to quit.")
win.getMouse()
win.close()
main()
|
8e7e56dca7121d0064c0d6dc4895822e2eb6b386
|
raffmiceli/Project_Euler
|
/Problem 96/test 3.py
| 854 | 3.5 | 4 |
def solve(sudoku):
mask = [0,1,2,9,10,11,18,19,20]
def getSet(i):
s, row, col = set(), int(i/9), i%9
corner = (int(row/3)*27) + (int(col/3)*3)
for i in range(9):
for j in [row*9+i, col+i*9, corner + mask[i]]:
s.add(sudoku[j])
return set("123456789") - s
try:
i = sudoku.index("0")
for value in getSet(i):
result = solve(sudoku.replace("0",value,1))
if result: return result
except:
return sudoku
return False
def problem096():
t, i, s = 0, 0, ""
for line in open('sudoku old.txt').readlines():
if len(line) > 8:
s += line[:9]
if i == 9:
t += int(solve(s)[:3])
i, s = 0, ""
else: i += 1
return t
print problem096()
|
cbbd4b8ca3392c0ec00beb14fa72cdf5a216ef68
|
romanchemist/OOP
|
/venv/nasled.py
| 413 | 3.640625 | 4 |
class W:
def X(self):
print('W')
class A(W):
def X(self):
print('A')
super().X()
# W.X(self) # TAK NE PRAVIL'NO!!!
class B(W):
def X(self):
print('B')
super().X()
class C(A, B):
def X(self):
print('C')
super().X()
# super(A, self).X() # propustit B
# A.X(self) # TAK NE PRAVIL'NO!
c = C().X()
print(C.mro())
|
8985ffba7afdb929f137e63628f083393a9d62ae
|
faizanzafar40/Intro-to-Programming-in-Python
|
/2. Practice Programs/10. list_exercise.py
| 248 | 4.40625 | 4 |
'''
Take a list and write a program that prints out all the
elements of the list that are less than 13.
'''
test_list = [1, 1, 2, 3, 5, 8, 13, 21, 4, 55, 9]
for i in test_list:
if(i < 13):
print("Values from list less than 13: ", i)
|
302268553ff9220905c5d0cbddb3f65c651de782
|
faelks/dh2321-group-vis
|
/data_handler/kth_social_usage_quantify.py
| 1,397 | 3.71875 | 4 |
from enum import Enum
import numpy as np
def get_social_usage_number(original_text):
social_usage = None
# Quantify the fixed options
# KTH Social is likely not going to be used for any interaction.
# I think that the lecturer explained that it will probably only
# used for checking the projects done in previous years.
# With this reasoning, this feature might be fairly irrelevant.
# Mapping into values 0-3 where 0 is unlikely to use and 3
# is a relatively high frequency of use.
# mapping options to numbers
usage = {
"Yes, but only a few times a week.": 3,
"I use it to check the schedule and to go to the canvas pages for my courses": 3,
"Yes, but the last time I checked was two weeks ago.": 2,
"Use it very rarely, less than once a month. ": 2,
"No, but I wouldn't mind using it.": 1,
"I haven't really had courses that use it alot but i did not like it when it was used. I think canvas it just a better option but i would not mind using kth social if i had to.": 1,
"Have not really used it at all, dont really know what it is. Guess I am open to use it.": 1,
"No but I guess I would use it if I had to.": 1,
"No and I haven't heard about it.": 0,
"No and I will never use it.": 0,
}
social_usage = usage.get(original_text)
return social_usage
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.