blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
7f645e5e72d0dffc061c63f89683217c56b4572d | catherinewu12/BikeShare-Project | /bike user interface.py | 14,490 | 4.0625 | 4 | '''
Name: Catherine Wu
Student ID: 20099368
Date last modified: November 15th, 2018
User Interface
This program runs the user interface of the BikeShare Program. It shows all the functionalities
of the program but they do not run on real data.
The test data is created in the first readData function and stored to be used
in all the other functions.
'''
'''This function return some random test data to be used throughout interface '''
def readData():
return [[1, 'station1', 1.0, 1.0, 100, 50, 50], [2, 'station2', 2.0, 2.0, 200, 40, 160],\
[3, 'station3', 3.0, 3.0, 30, 30, 0]]
'''This function asks the user for the input of their station ID number
call this function before every task where an ID number is needed
ensures the user inputs a value which is found in the data list'''
def getStationID(stationList):
valid = False
while not valid:
idInput = int(input("Enter the ID number for the station in which you are interested: "))
for i in range(len(stationList)):
if idInput in stationList[i]:
valid = True
print ()
return idInput
print ()
print ("That is not a valid station ID. Please try again. Use an integer from 1-3.")
'''This function prints and returns all data values of a user-requested station.
stationID is the user input number indicating the station in which they are interested.
stationList is the list of lists containing all of the station data'''
def stationInfo(stationID, stationList):
stationData = []
#search through the entire station data for the correct station based on ID
for i in range(len(stationList)):
if stationID in stationList[i]:
#iterate through each data value of the correct station and append to
#a list to be printed to the user
for j in range(len(stationList[i])):
stationData.append(stationList[i][j])
#print information to the user
print ("Below is the information for station", stationID)
print ()
print("Station Name:", stationData[1])
print("Latitude:", stationData[2])
print("Longitude:", stationData[3])
print("Capacity:", stationData[4])
print("Number of bikes available:", stationData[5])
print("Number of docks available:", stationData[6])
return stationData
'''This function checks a requested station in the data list for available bikes.
stationID is the user input number indicating the station in which they are interested
stationList is the list of lists containing all of the station data'''
def isBikeAvailable(stationID, stationList):
#search through the entire station data for the correct station based on ID
for i in range(len(stationList)):
if stationID in stationList[i]:
#store the value for number of available bikes at the requested station
numBikes = stationList[i][5]
return numBikes
'''This function checks a requested station in the data list for available docks.
stationID is the user input number indicating the station in which they are interested.
stationList is the list of lists containing all of the station data '''
def isDockAvailable(stationID, stationList):
#search through the entire station data for the correct station based on ID
for i in range(len(stationList)):
if stationID in stationList[i]:
#store the value for number of available docks at the requested station
numDocks = stationList[i][6]
return numDocks
'''This function searches through the data list for stations with 1+ available bikes.
The station names and # of available bikes are appended to a new list and sorted from
most available bikes to least. The function returns this list.
stationList is the list of lists containing all of the station data'''
def bikeAvailableStations(stationList):
#list of stations with available bikes
bikeAvailability = []
for i in range(len(stationList)):
#check for no available bikes
if stationList[i][5] > 0:
#append name and # of available bikes
bikeAvailability.append(stationList[i][1:6:4])
#must sort list from most bikes to least in actual implementation
return bikeAvailability
'''This function searches through the data list for stations with 0 available docks.
The station names are appended to a new list which is returned by the function.
stationList is the list of lists containing all of the station data'''
def fullCapacityStations(stationList):
#list of stations at capacity
capacity = []
for i in range(len(stationList)):
#check for no available docks
if stationList[i][6] == 0:
#append name
capacity.append(stationList[i][1])
return capacity
'''This function allows users to rent some number of bikes from a requested station.
The station is checked for anough bike available and the data values are appropriately
increased/decreased.
stationList is the list of lists containing all of the station data
stationID is the station from which they want to rent
'''
def rentBike(stationList, stationID):
invalidInput = True
while invalidInput:
#ensure they enter a numerical character, not a string
try:
numBikes = int(input("Please enter the number of bicycles you wish to rent: "))
invalidInput = False
except:
print("That is invalid. Please enter an integer value (ex. 1)")
print ()
#must check through the data list for bike availability and change data values
#in final implementation
#user interaction
if numBikes == 1:
print("You have rented", numBikes, "bicycles")
else:
print("You have rented", numBikes, "bicycles")
return None
'''This function allows users to return some number of bikes to a requested station.
The station is checked for enough dock availability and the data values are appropriately
increased/decreased.
stationList is the list of lists containing all of the station data
stationID is the station to which they want to return the bikes'''
def returnBike(stationList, stationID):
invalidInput = True
while invalidInput:
#ensure they enter a numerical character, not a string
try:
numReturns = int(input("Please enter the number of bicycles you wish to return: "))
invalidInput = False
except:
print("That is invalid. Please enter an integer value (ex. 1)")
print ()
#must check for available docks and change data values in final implementation
#user interaction
if numReturns == 1:
print ()
print("You have successfully returned", numReturns, "bicycle.\
Thank you for using the Bikeshare services.")
else:
print ()
print("You have successfully returned", numReturns, "bicycles.\
Thank you for using the Bikeshare services.")
return None
'''This function gives users basic directions to go from one station to another.
Ths user must input both station IDs before using this functionality.
The two station parameters are user inputs. stationList is the list of lists containing all station data'''
def giveDirections(station1, station2, stationList):
#must find difference between longitude and latitude for final implementation
#inform user to travel to the destination
#will include actula directions in final implementation
print("Travel to get from Station", station1, "to Station", station2)
return None
'''This function prints the menu of tasks the program is capable of performing
The user is also asked for input on what functionality they would like to be executed'''
def menu():
print("What would like to do today?")
print("1 Look up information about a station")
print("2 Check for available bicycles")
print("3 Check for available bicycle docks")
print("4 Rent a bicycle")
print("5 Return a bicycle")
print("6 Get directions to another station")
print("7 Find stations at full capacity")
print ()
#get user input
userChoice = input("Please enter the number corresponding to the functionality\
you would like to check out!\n")
return userChoice
'''This function is called at the end of each loop of the main function.
User is asked if they wish to continue using the program.
'''
def repeatProgram():
checkRepeat = True
#loop to ensure user input is 'y' or 'n'
while checkRepeat:
repeat = input("If you wish to return to the menu, enter 'y'. \
If you wish to exit the program, enter 'n'\n")
#if user wishes to exit, return that information to main function
if repeat == 'n':
print ()
print ("Thank you for using the Toronto Bikeshare Program App! We hope \
you enjoy your cycling experience!")
return False
#catch any characters which are not correct
elif repeat != 'y':
print ("That was not a valid character. Try again.")
#if user wishes to return to main menu, return info to main function
else:
print ()
return True
'''This is the main function.
Based on the user choice made in the menu function, user inputs are retrieved
and other functions are called to execute the task.
It runs a loop to allow user to return to the main menu after each task,
based on user input received from repeatProgram function.'''
def main():
#keeps loop running
running = True
#stores the data in a variable to be used as a parameter for the other functions
stationList = readData()
#opening message to user
print("Welcome to the Toronto Bikeshare Program! We are delighted to offer\
rental bicycles for you to use as you travel around our wonderful city!")
print ()
#loop which executes function calls based on user's input choice
#loads the menu at the beginning of each loop
while running:
taskNum = menu()
#big 'if statement' to execute different functions for each possible input value
if taskNum == '1':
print("You have selected to look up information about a station")
print ()
stationID = getStationID(stationList)
stationData = stationInfo(stationID, stationList)
elif taskNum == '2':
print("You have selected to check for bicycle availability")
#two options are given to user when they choose to check for bike availability
choiceCheck = input("To check general availability enter '1'. To check availability \
at a specific station, enter '2'\n")
if choiceCheck == '1':
stationAvailability = bikeAvailableStations(stationList)
#all stations with available bikes are printed in a sorted list
print("Below are listed the stations with available bikes")
for i in range(len(stationAvailability)):
print (stationAvailability[i])
elif choiceCheck == '2':
stationID = getStationID(stationList)
#user requested station is checked for available bikes
print("There are",isBikeAvailable(stationID, stationList), \
"bicycles available at Station", stationID)
#catch incorrect input values from user
else:
print ("You have made an invalid input value. Please return \
to the menu and retry this functionality")
elif taskNum == '3':
print("You have selected to check for bicycle dock availability")
print()
#request station ID from user
stationID = getStationID(stationList)
print("There are",isDockAvailable(stationID, stationList), \
"bicycle docks available at Station", stationID)
elif taskNum == '4':
print("You have selected to rent a bicycle")
print()
#request station ID from user
stationID = getStationID(stationList)
rentBike(stationList, stationID)
elif taskNum == '5':
print("You have selected to return a bicycle")
print()
#request station ID from user
stationID = getStationID(stationList)
returnBike(stationList, stationID)
elif taskNum == '6':
print("You have selected to get directions to another station")
print()
#request station ID from user for both stations and store in parameter values
station1 = int(input("Enter the ID number for the station where you are currently situated: "))
station2 = getStationID(stationList)
giveDirections(station1,station2,stationList)
elif taskNum == '7':
print("You have selected to see a list of stations at full capacity")
atCapacity = fullCapacityStations(stationList)
print()
print("Below is a list of stations which are at full capacity (have no available docks):")
#print the station names in a list order(one underneath the other)
for i in range(len(atCapacity)):
print(atCapacity[i])
#ensure the user doesn't cause an error by inputing an invalid character
else:
print("You have not made a valid selection.\
Make sure to enter only a numerical value between 1 and 7.")
print()
#call repeatProgram function to ask user if they wish to continue
#after completing the task
running = repeatProgram()
#run program!!
main()
|
cc9ab9fc53c8d284b13ea2c870791a2470f3eb50 | nguyenngochuy91/companyQuestions | /google/longestRepeatingSubstring.py | 516 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 5 20:51:19 2020
@author: huyn
"""
class Solution:
def longestRepeatingSubstring(self, S: str) -> int:
s = set()
maxLength = ""
for i in range(len(S)):
for j in range(i,len(S)):
string = S[i:j+1]
if string not in s:
s.add(string)
else:
if len(string)>len(maxLength):
maxLength = string
return len(maxLength) |
f3c318d32602d84e5f5b4c0c145173f016bca246 | ayumoesylv/draft-tic-tac-toe | /l2 class 07-10 project.py | 287 | 4.5 | 4 | #write a program to replace the last element in a list with another list.
listA = [1, 3, 5, 7, 9, 10]
listB = [2, 4, 6, 8]
listA[(len(listA) - 1)] = listB
print(listA)
#teacher's method
list1 = [1, 3, 5, 7, 9, 10]
list2 = [2, 4, 6, 8]
del(list1[-1])
list1.extend(list2)
print(list1) |
5a2dfac15b153dc0f3411f5dc5ed496da488dfd1 | brett-scheller/Text-Mimic | /mimic.py | 2,040 | 3.640625 | 4 | import random
#capture some global vars from makeDict
#firstWord = 0
#lastWord = 0
#wordDict = 0
def mimic(filename):
#input text sample from .txt file into single string
infile = open(filename)
blockString = infile.read()
infile.close()
#clean block string (remove newline, space out mid punc, etc)
blockString = blockString.replace('\n', ' ')
blockString = blockString.replace(',', ' ,')
blockString = blockString.replace(';', ' ;')
blockString = blockString.replace(':', ' :')
if blockString[-1] == '.':
blockString = blockString.strip()[0:-1]
#turn string into sentence list
sentenceList = blockString.split('. ')
#capture lists of first and last words
firstWord = []
for sentence in sentenceList:
firstWord.append(sentence.split()[0])
lastWord = []
for sentence in sentenceList:
lastWord.append(sentence.split()[-1])
#revert to string then split to word list (inefficient?)
blockString = ' '.join(sentenceList)
wordList = blockString.split()
wordList.append('END')
wordDict = {}
#assign words to dict keys with values list of following words
for i in range(len(wordList)-1):
key = wordList[i]
if key in firstWord:
key = key.lower()
if key not in wordDict.keys():
wordDict[key] = []
wordDict[key].append(wordList[i+1])
#build a sentence using word dict and random.choice
retList = [random.choice(firstWord)]
i = 0
while i < len(retList):
nextWord = random.choice(wordDict[retList[i].lower()])
retList.append(nextWord)
if nextWord
if nextWord in lastWord:
if random.randrange(3) == 0:
break
i += 1
if i > 25:
break
retString = ' '.join(retList)
retString = retString.replace(' ;', ';')
retString = retString.replace(' :', ';')
retString = retString.replace(' ,', ',')
print(retString)
mimic('Cthulu.txt')
|
161e07b3e95edc780249683011dc5e0d09c19a38 | Fedurov/amis_python | /km72/Fedurov_Danil/11/task3.py | 517 | 3.8125 | 4 | X = []
Y = []
def func1(n):
if n > 0:
X.append(input("Введіть елемент - "))
return func1(n - 1)
else:
return X
n = int(input("Введіть кількість елементів списку - "))
func1(n)
def revers(n):
if n == 0:
return Y
else:
Y.append(X[n - 1])
return revers(n - 1)
revers(n)
print(X, "Початковий список")
print(Y, "Перевернутий список")
|
c30414e23362a4e7a7b8479d5fd418e1bbb82aeb | SafonovMikhail/python_000577 | /000402AstartaPy/Astarta000402PyNoviceсh01p01p04TASK01.py | 553 | 4.03125 | 4 | '''
Придумайте пример с использованием математических операторов и отработайте их в интерактивной оболочке:
Придумайте пример с использованием операторов: **, % и *
Придумайте пример с использованием операторов: //, **, *, (+/-) и %
'''
print(7 ** 2 % 6 * 2)
print(((7 // 2 ** 2) * 2 + 2) % 3)
# обратить внимание на действия со степенью
|
ffe9a3d9c43c4a13947036d71f5035955a4e61a6 | dkurchigin/gb_algorythm | /lesson3/task1.py | 464 | 3.625 | 4 | # 1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
divisible_by = {x: 0 for x in range(2, 10)}
for number in range(2, 100):
for check_div in range(2, 10):
if number % check_div == 0:
divisible_by[check_div] += 1
for key, value in divisible_by.items():
print(f'{key} - {value}')
|
0181d4cee54a1287d72b614aa277ce50421c2ece | hector98/PYTHON | /Calif.py | 509 | 3.796875 | 4 | if __name__ == '__main__':
ins="Insuficiente: "
su="suficiente: "
bi="Bien: "
ex="Excelente: "
for cont in range(1, 21):
print("Escribe la calificacion", cont)
cal=float(input())
if cal <= 5.9:
ins += str(cal)+'\n '
if cal >= 6 and cal <= 7.9:
su += str(cal)+'\n'
if cal >= 8 and cal <= 9.9:
bi += str(cal)+'\n'
if cal == 10:
ex += str(cal)+'\n'
print(ins+'\n'+ su +'\n'+ bi +'\n'+ ex)
|
8bacddf0f25381b6fc96c0d62d06449498cb9509 | punchabird/Learn-Python-The-Hard-Way | /ex18.py | 677 | 4.15625 | 4 | #this one is like your scripts with argv
def print_two(*args):
arg1, arg2, = args
print(f"arg1: {arg1}, arg2: {arg2}")
#ok, learning about *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
#this just takes one argument
def print_one(arg1):
print(f"arg1: {arg1}")
#this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
#to run, call, or use a function all mean the same thing
#lines of code in the function should be indented four spaces
#going back with no indents closes your function
|
69e099460be48326bb603c241d3d85e4a9910c00 | abgasim/test-fit | /calc.py | 158 | 3.5 | 4 | def add(x,y):
x+y
def subtract (x,y) :
return x-y
def multiply (x,y):
return x*y
def divide(x,y):
return x/y
def square(x):
return x*x |
a87a5d31dc3bacb2e7c863c9f7ae48fdd994eb9c | ryan970516/AE402 | /class6-2 | 663 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 14:39:05 2020
@author: anne
"""
class Animal:
def __init__(self,HP):
self.HP = HP
def hurt(self,damage):
self.HP -= damage
print("剩下血量" + str(self.HP))
class Dog(Animal):
def __init__(self,HP):
super().__init__(HP)
class ShibaInu(Dog):
def __init__(self):
super().__init__(1)
def Roar(self):
print("旺旺")
class Husky(Dog):
def __init__(self):
super().__init__(1)
def Roar(self):
print("阿嗚")
dog = ShibaInu()
dog.Roar() |
9f8237d7da7aee9c97d5dc9ea616a8dec93a05bb | brrbaral/pythonbasic | /OOPinPython/MethodOverriding.py | 274 | 3.875 | 4 | class Parent:
def MyMethod(self):
print("calling parent myMethod")
class Child(Parent):
def MyMethod(self):
print("Calling Child method")
c1=Child()
c1.MyMethod()
#NEED TO CALL EXPLICITLY PARENT METHOD ALSO
p1=Parent()
p1.MyMethod() |
084a0df6defbe57f544b8c16d887c5083c4e56bd | jh-lau/leetcode_in_python | /02-算法思想/动态规划/516.最长回文子序列.py | 1,165 | 3.640625 | 4 | """
User: Liujianhan
"""
__author__ = 'liujianhan'
class Solution:
@staticmethod
def longest_sub_palindrome_sub_sequence(s):
length = len(s)
dp = [[0] * length for _ in range(length)]
for i in range(length):
dp[i][i] = 1
for i in range(length - 1, -1, -1):
for j in range(i + 1, length):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][-1]
@staticmethod
def method_2(s):
from functools import lru_cache
@lru_cache(None)
def helper(s):
if len(s) <= 1:
return len(s)
if s[0] == s[-1]:
return helper(s[1:-1]) + 2
else:
return max(helper(s[1:]), helper(s[:-1]))
return helper(s)
if __name__ == '__main__':
print(Solution().longest_sub_palindrome_sub_sequence('bbbab'))
print(Solution().method_2('bbbab'))
print(Solution().longest_sub_palindrome_sub_sequence('cbbd'))
print(Solution().method_2('cbbd')) |
2483f0d7952bbe7213849660426ae43441770d38 | uoguelph-mlrg/cnn-moth-detection | /tools_theano.py | 5,076 | 3.8125 | 4 | import numpy as np
import theano
# import theano.tensor as T
def shared_dataset(data_xy, borrow=True):
""" Function that loads the dataset into shared variables
The reason we store our dataset in shared variables is to allow
Theano to copy it into the GPU memory (when code is run on GPU).
Since copying data into the GPU is slow, copying a minibatch everytime
is needed (the default behaviour if the data is not in a shared
variable) would lead to a large decrease in performance.
"""
data_x, data_y = data_xy
shared_x = theano.shared(np.asarray(data_x,
dtype=theano.config.floatX),
borrow=borrow)
shared_y = theano.shared(np.asarray(data_y,
dtype=theano.config.floatX),
borrow=borrow)
# When storing data on the GPU it has to be stored as floats
# therefore we will store the labels as ``floatX`` as well
# (``shared_y`` does exactly that). But during our computations
# we need them as ints (we use labels as index, and if they are
# floats it doesn't make sense) therefore instead of returning
# ``shared_y`` we will have to cast it to int. This little hack
# lets ous get around this issue
return shared_x, shared_y
# end def shared_dataset
def class_weight_given_y(y):
'''
calculate the weights of different classes for class balancing.
class_weight is a vector. len(class_weight) is number of classes in y.
And sum(class_weight) == number of classes
y is a vector. len(y) is the number of examples. The values of y[i] is from
0 to n-1, where n is the number of classes.
Algorithm:
class_num is the vector with number of examples for each class.
len(class_num) = number of classes.
class_weight[i] = 1 / class_num[i] / sum(1 / class_num) * len(class_num)
'''
n = int(np.max(y)) + 1 # number of classes
y = np.array(y)
class_num = np.ones(n)
for ind in range(n):
class_num[ind] = np.sum(y == ind)
class_weight = np.ones(n)
den = sum(1. / class_num)
for ind in range(n):
class_weight[ind] = 1. / class_num[ind] / den * n
return class_weight
# end def class_weight_given_y
# this function can turn any function that only applies on a fixed batch
# size to function that can take data of any size
# because for theano convnets, the batch_size has to be fixed, so need
# need to right another 2 functions predict and predict_proba to take
# arbitrary size input
def batch_to_anysize(batch_size, fcn_hdl, X):
'''
X is a np matrix with X.shape[0] = number of examples
and X.shape[1] = number of feature dimensions (self.img_size ** 2)
fcn_hdl is the function handle that been passed in
'''
n_iter = X.shape[0] / batch_size
num_rem = X.shape[0] % batch_size
# if number of example is not integer times batch_size, need to pad X
if num_rem > 0:
n_iter += 1
X = np.cast[np.float32](np.r_[X, np.zeros((batch_size - num_rem, X.shape[1]))])
# determine the shape of y by looking at f's output
y_sample = fcn_hdl(X[:batch_size, :])
if y_sample.ndim == 1:
y = np.cast[np.float32](np.zeros(X.shape[0]))
else:
y = np.cast[np.float32](np.zeros((X.shape[0], y_sample.shape[1])))
# for each batch calculate y
for ind in range(n_iter):
ind_start = ind * batch_size
ind_end = (ind + 1) * batch_size
if y.ndim == 1:
y[ind_start:ind_end] = fcn_hdl(X[ind_start:ind_end, :])
else:
y[ind_start:ind_end, :] = fcn_hdl(X[ind_start:ind_end, :])
# if needed cut the padded part of y
if num_rem > 0:
if y.ndim == 1:
y = y[:(n_iter - 1) * batch_size + num_rem]
else:
y = y[:(n_iter - 1) * batch_size + num_rem, :]
return y
# end def batch_to_anysize
def cost_batch_to_any_size(batch_size, fcn_hdl, X, y):
'''
function for calculating arbitrary input size cost.
Because of this function takes 2 inputs, which as a different format comparing to other _batch functions, so cannot use batch_to_anysize function.
and here the last batch has to be discarded as it very hard (if possible) to separate the padded value from the orginal true values
so to make the predicted cost accurate, use the batch_size that can divide the dataset size
NOTE: if needed, should make this a generic function
'''
assert X.shape[0] == y.shape[0]
n_batch = X.shape[0] / batch_size
cost_sum = 0.
# for each batch calculate cost
for ind in range(n_batch):
ind_start = ind * batch_size
ind_end = (ind + 1) * batch_size
cost_sum += fcn_hdl(X[ind_start:ind_end, :],
y[ind_start:ind_end])
return cost_sum / n_batch
# end def cost_batch_to_any_size
|
ad84807f6a9c61ff013e815691883023946ac870 | chenshanghao/LeetCode_learning | /Problem_46/learning_solution3.py | 647 | 3.59375 | 4 | class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.result = []
self.backtrack(nums, [])
return self.result
def backtrack(self, nums, temp):
# print(temp)
if len(temp) == len(nums):
self.result.append(temp[:])
# 由于长度一样, 所以不用知道 index,连 i 都免了
else:
for n in nums:
if n in temp:
continue
temp.append(n)
self.backtrack(nums, temp)
temp.pop()
|
d07515ad0042ff5e242decddb7f12482af8e98d2 | oattia/eccadv | /eccadv/model/attacker/attacker.py | 969 | 3.640625 | 4 | from enum import Enum
class Attacks(Enum):
FGSM = 0
BIM = 1
MIM = 2
class Attacker:
"""
Abstract Class to hide the details of the adversarial attack library used:
(Cleverhans, Foolbox, Advertorch, Adversarial-Robustness-Toolbox).
"""
def __init__(self, name, attack_params):
self.name = name
self.nn_model = None
self.attack_params = attack_params
def initialize(self, nn_model):
self.nn_model = nn_model
def get_params(self):
return self.attack_params
def perturb(self, samples):
""""
Perturb the samples according to the adversarial attack.
"""
raise NotImplementedError
class DummyAttacker(Attacker):
"""
Dummy attacker that does not perturb the given samples.
"""
def __init__(self, name, attack_params={}):
super(DummyAttacker, self).__init__(name, {})
def perturb(self, samples):
return samples
|
a25ba4d77d5943c9340b90e5480f49a539b92d03 | LourdesOshiroIgarashi/algorithms-and-programming-1-ufms | /Lists/Listas e Repetição - AVA/ThiagoD/13.py | 259 | 3.734375 | 4 | k = int(input())
valores = []
for i in range(k):
j = i + 1
valor = 5 * (i) - j ** 2
valores.append(valor)
print("Sequência:")
for i in valores:
print(i, end=" ")
print("\n")
print(f"Para k = {k}, o valor do somatório é: {sum(valores)}")
|
2448565cf2bc65fbb5aaad8218f1bc790d6ce4c5 | Angineer/SunTweet | /Sun.py | 823 | 3.671875 | 4 | class datum:
def __init__(self, dataSource):
"""Initializes datapoint
Arguments
path: The location of the data stream from which to read.
Should be a text file with the following format:
date time datavalue
on each line
"""
self.dataSource=dataSource
self.date="01/01/2000"
self.time="00:00"
self.value=0
def Update(self):
"""Update the datapoint to have the most recent value from the data stream"""
#Read in raw data
with open(self.dataSource, 'r') as dataFile:
dataFile.seek(-22, 2)
line=dataFile.read(22)
#Parse data
lineList=line.split()
date=lineList[0]
time=lineList[1]
value=lineList[2]
#Set to new value
self.date=date
self.time=time
self.value=value
def GetDateTime(self):
return self.date+" "+self.time
def GetValue(self):
return self.value |
fbbee81b799b318918fa4951c6a1560fb9bb9454 | zheswien/opencvTuto | /T17_CannyEdgeDetection.py | 689 | 3.75 | 4 | ###############
# Canny edge -> An edge detection operator that uses a multi-stage algorithm to detect a wide range of edges in images.
# Composed of 5 stages:
# - Noise reduction
# - Gradient calculation
# - Non-maximum suppression (Edge detection)
# - Double threshold (Find potential edges)
# - Edge tracking by hysteresis
###############
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('messi5.jpg', 0)
canny = cv2.Canny(img, 100, 200)
titles = ['image', 'canny']
images = [img, canny]
for i in range (len(images)):
plt.subplot(1, 2, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show() |
006f0c75b6c40f3ffd02dace31d25cdfb8f5737c | ManishBhat/Project-Euler-solutions-in-Python | /P357_prime_generating_integers | 1,814 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 12:25:30 2020
@author: manish
"""
from math import sqrt
from numba import jit
@jit
def sieve_of_erat(N):
"""
Function implements sieve of Eratosthenes (for all numbers uptil N).
Returns array erat_sieve
If erat_sieve[i] is True, then 2*i + 3 is a prime.
"""
lim = int(N/2)
if N % 2 == 0:
lim -= 1
erat_sieve = [True]*lim
prime_list = []
prime_list.append(2)
for i in range(int((sqrt(N)-3)/2)+1): # Only need to run till sqrt(n)
if erat_sieve[i] == True:
j = i + (2*i+3)
while j < lim:
erat_sieve[j] = False
j += (2*i+3)
for i in range(lim):
if erat_sieve[i] == True:
prime_list.append(2*i+3)
return erat_sieve, prime_list
def isprime(x, esieve):
if x % 2 ==0:
return False
y = (x-3)//2
return esieve[y]
def is_prime_gen_integer(N, esieve):
sq_N = int(sqrt(N))
for d in range(2, sq_N + 1):
if N % d == 0:
x = N // d + d
if x % 2 ==0:
return False
y = (x-3)//2
if esieve[y] is False:
return False
return True
def Q357():
#N = 100
N = 100_000_000
esieve, plist = sieve_of_erat(N)
ans = 1 # 1 is a prime generating integer.
# But, apart from 1 all the remaining prime generating integers are even and of the form 4n + 2
for x in plist[1:]:
n = x-1
if n% 4 != 0:
if is_prime_gen_integer(n, esieve):
ans += n
print("Answer is:", ans)
if __name__ == '__main__':
import time
start_time = time.time()
Q357()
print("Program run time(in s): ", (time.time() - start_time)) |
76ffd35f41b364751094bb30e6217e12409f0d64 | mathematixy/MLBox | /python-package/mlbox/encoding/na_encoder.py | 5,925 | 3.703125 | 4 |
# coding: utf-8
# Author: Axel ARONIO DE ROMBLAY <axelderomblay@gmail.com>
# License: BSD 3 clause
import numpy as np
import pandas as pd
import warnings
from sklearn.preprocessing import Imputer
class NA_encoder():
"""
Encodes missing values for both numerical and categorical features. Several strategies are possible in each case.
Parameters
----------
numerical_strategy : string or float or int, defaut = "mean"
The strategy to encode NA for numerical features.
Available strategies = "mean", "median", "most_frequent" or a float/int value
categorical_strategy : string, defaut = '<NULL>'
The strategy to encode NA for categorical features.
Available strategies = a string or np.NaN
"""
def __init__(self, numerical_strategy = 'mean', categorical_strategy = '<NULL>'):
self.numerical_strategy = numerical_strategy #mean, median, most_frequent and a value
self.categorical_strategy = categorical_strategy #'<NULL>' or np.NaN for dummification
self.__Lcat = []
self.__Lnum = []
self.__imp = None
self.__fitOK = False
def get_params(self, deep=True):
return {'numerical_strategy' : self.numerical_strategy,
'categorical_strategy' : self.categorical_strategy}
def set_params(self,**params):
self.__fitOK = False
for k,v in params.items():
if k not in self.get_params():
warnings.warn("Invalid parameter a for encoder NA_encoder. Parameter IGNORED. Check the list of available parameters with `encoder.get_params().keys()`")
else:
setattr(self,k,v)
def fit(self, df_train, y_train=None):
'''
Fits NA Encoder.
Parameters
----------
df_train : pandas dataframe of shape = (n_train, n_features)
The train dataset with numerical and categorical features.
y_train : [OPTIONAL]. pandas series of shape = (n_train, ). defaut = None
The target for classification or regression tasks.
Returns
-------
None
'''
self.__Lcat = df_train.dtypes[df_train.dtypes == 'object'].index #list of categorical variables
self.__Lnum = df_train.dtypes[df_train.dtypes != 'object'].index #list of numerical variables
if(self.numerical_strategy in ['mean','median',"most_frequent"]):
self.__imp = Imputer(strategy=self.numerical_strategy)
if(len(self.__Lnum)!=0):
self.__imp.fit(df_train[self.__Lnum])
else:
pass
self.__fitOK = True
elif((type(self.numerical_strategy)==int)|(type(self.numerical_strategy)==float)):
self.__fitOK = True
else:
raise ValueError("numerical strategy for NA encoding is not valid")
return self
def fit_transform(self, df_train, y_train=None):
'''
Fits NA Encoder and transforms the dataset.
Parameters
----------
df_train : pandas dataframe of shape = (n_train, n_features)
The train dataset with numerical and categorical features.
y_train : [OPTIONAL]. pandas series of shape = (n_train, ). defaut = None
The target for classification or regression tasks.
Returns
-------
df_train : pandas dataframe of shape = (n_train, n_features)
The train dataset with no missing values.
'''
self.fit(df_train,y_train)
return self.transform(df_train)
def transform(self, df):
'''
Transforms the dataset
Parameters
----------
df : pandas dataframe of shape = (n, n_features)
The dataset with numerical and categorical features.
Returns
-------
df : pandas dataframe of shape = (n, n_features)
The dataset with no missing values.
'''
if(self.__fitOK):
if(len(self.__Lnum)==0):
return df[self.__Lcat].fillna(self.categorical_strategy)
else:
if(self.numerical_strategy in ['mean','median',"most_frequent"]):
if(len(self.__Lcat)!=0):
return pd.concat((pd.DataFrame(self.__imp.transform(df[self.__Lnum]), columns=self.__Lnum, index=df.index),
df[self.__Lcat].fillna(self.categorical_strategy)),axis=1)[df.columns]
else:
return pd.DataFrame(self.__imp.transform(df[self.__Lnum]), columns=self.__Lnum, index=df.index)
elif((type(self.numerical_strategy)==int)|(type(self.numerical_strategy)==float)):
if(len(self.__Lcat)!=0):
return pd.concat((df[self.__Lnum].fillna(self.numerical_strategy),
df[self.__Lcat].fillna(self.categorical_strategy)),axis=1)[df.columns]
else:
return df[self.__Lnum].fillna(self.numerical_strategy)
else:
raise ValueError("call fit or fit_transform function before")
|
6317157aad17aab8182513c8bdabad8279a62230 | Mauricio1xtra/Revisar_Python_JCAVI | /Proj_class7/pacote/prog2.py | 136 | 3.953125 | 4 | ##Criando uma função para o módulo 2 do pacote
def listaPares(x):
for p in range(x):
if p % 2 == 0:
print(p) |
48904ec3d30704f774091427bc566f00deb6ccd5 | 121910313025/lab-01-09 | /L12-selection sort iterative.py | 443 | 4.03125 | 4 | #121910313025
#To implement selection sort iterative
arr=[]
n=int(input("enter range:"))
for i in range(n):
ele=int(input())
arr.append(ele)
#code begins
for i in range(len(arr)):
min_indx=i
for j in range(i+1,len(arr)):
if arr[min_indx]>arr[j]:
min_indx=j
#swap
arr[i],arr[min_indx]=arr[min_indx],arr[i]
#print
print("Sorted array is :")
for i in range(len(arr)):
print(arr[i])
|
3e65d71bddeefa2b577bf9031c146c4df48ca0a9 | arbaj09/python | /argsKW.py | 922 | 3.71875 | 4 | # def funargs(Nornal,*args,**kwargs):
# print(Nornal)
#
# for item in args:
#
# print(item)
# print("\nNow i would like to introduce some of heros : ")
# for key,value in kwargs.item():
# print(f"(key) is a {value}")
#
# har=["harry", "rohan","skillf","hammad","the programmer"]
# normal="i am a normal argument and the student are:"
# kw=["rohan","monitor"]
# funargs(normal,*har,**kw)
def funargs(nornal, *args, **kwargs):
print(nornal)
for item in args:
print(item)
print("now i would like to introduce some heros")
for key, value in kwargs.item():
print(f"(key) is a {value}")
har = ["rohan", "harry", "skillf", "hammad", "shivam", "the programmer"]
normal = "i am a normal argument and the student are :"
kw = {"rohan:monitor", "harry:fitness instructor", "the programmer:cordinator"}
funargs(normal, *har, **kw)
|
7ae5b57385892b4c6b5f525a161ec569ac1fb947 | Ahmad-Hassan-03kml/Python-Practice-codes-Begginers-to-Pro | /function_referrence.py | 236 | 3.609375 | 4 |
def func( pr1 ):
print("list before eddit {}" .format(pr1)) # 20
pr1 = [1,2,3,4,5 ,6,7,7]
print("list after eddit {}" .format(pr1)) # 20
#end of func
pr1 = 20
func(pr1)
print(pr1)# 20
|
a7883a44d3b51c14eb4a34908f46bebe8ba0c2f3 | arunkumarp93/datastructure | /stack/balancedpara.py | 713 | 3.6875 | 4 | """find the parentheses closed properly
stack used to slove the problem
add the parenthes "(" and remove until the list length becomes zero
"""
""" python list can be used as the stack
need to use append instead of push"""
def findpara(symbolString):
s = []
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol == '(':
s.append(symbol)
else:
if len(s) == 0:
balanced = False
else:
s.pop()
index = index + 1
if balanced and len(s)==0:
return True
else:
return False
print (findpara('(())'))
print (findpara('(()'))
|
29b0cdae18c3e59aed45bbea8e2e196fd5820737 | leptokurtoza/27.04.2018 | /exceptions_errors.py | 849 | 3.59375 | 4 | '''Popraw błędy i uruchom program.
Powodzenia:) '''
#błędy, znajdź i popraw
len('abrakadabra'
print(1235+ '4')
slownik = ['a': 'pierwszy', 'b':'drugi']
1nazwa = 'mojanazwa'
krotka = (2, 4 ,9)
krotka[1] = 3
moja_lista = ['cos', 'kot', 1, 2]
moja_lista[4]
x = 0
while x > 0:
print('wiekszy')
x += 1
if 4 = 5-1:
print('etwas')
#ZeroDivisionError
def moja_funkcja(x, y):
try:
print(0.8*x/(y-2))
except:
print('nie dziel przez 0')
moja_funkcja(16, 23)
moja_funkcja(16, 2)
#kiedy wydaje się, że wszystko jest ok
def pierwiastkowanie(x): #uwaga, mamy być w zbiorze liczb rzeczywistych
print(x**(1/2))
pierwiastkowanie(67)
pierwiastkowanie(-10)
# czy to chcieliśmy osiagnąć?
def witanie(imie):
print('Hej ' + imie)
witanie('Asia')
witanie(23)
|
01aea43592b1fe18e31a5649c328441194be80a5 | Ugtan/Project-Euler | /PycharmProjects/PROJECTEULER/25th.py | 804 | 4.15625 | 4 | # PROBLEM 25TH
"""The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?"""
def fibonacci(n):
if n == 1 or n == 2:
return 1
else:
return (fibonacci(n - 1) + fibonacci(n - 2))
def main():
for index in range(1, 10000):
if len(str(fibonacci(index))) == 5:
print("The index of the first term in the Fibonacci sequence to contain 1000 digits is {}.".format(index))
break
if __name__ == "__main__":
main()
|
05336bce8f913cc01281db4a219cee4485040bb1 | codeevs/PythonLearn | /Modulo3/02-mayoreigual.py | 54 | 3.59375 | 4 | n = int(input("Ingresa un número: "))
print(n >= 100) |
7a92460b645ee6175001ff73fad0857b544c2cf1 | apadamsee/TextMiningMP3---apadamsee | /textmining.py | 3,803 | 3.5625 | 4 | """
MP3 Lyric Scraping from Genius
@author: Afraz Padamsee
This file contains the code for connecting to the Genius API and scraping lyrics from Genius
"""
import requests
import urllib.request as urllib
import json
from bs4 import BeautifulSoup
import re
def search_for_song(search_term):
"""
Searches for search_term on Genius thru its API and returns a JSON object of the top search result('hit')
UNIT TESTED: by comparing searches on the Genius website to the results of the same searches on this function and seeing if they matched
e.g. print(search_for_song('highest in the room')) -- (correctly searched for and grabbed the Travis Scott song)
"""
# Format a request URI for the Genius API (to search for songs)
_URL_API = "https://api.genius.com/"
_URL_SEARCH = "search?q="
querystring = _URL_API + _URL_SEARCH + urllib.quote(search_term)
request = urllib.Request(querystring)
request.add_header("Authorization", "Bearer " + "QootmN8aXaeUEtMguYVsDpQyr1VO6s1O8FUB0cTccMeyB4GRTHMvlDfUUb7YjEF1") #utilizing user access token
request.add_header("User-Agent", "")
# Actually search for the song
response = urllib.urlopen(request, timeout=3).read().decode('UTF-8')
json_obj = json.loads(response)
if 'New Music Friday' in json_obj['response']['hits'][0]['result']['full_title']: # Avoiding issue where Genius returns the top search term as its weekly "New Music Friday" series that the song is a part of, rather than the song itself
return json_obj['response']['hits'][1]['result']
else:
return json_obj['response']['hits'][0]['result']
def pull_spec_data(search_term, data_term):
"""
Since search_for_song returns a JSON object that functions as a dict, this function returns the the specified
category/data_term out for the specified song in the search term
Options for data_term:
'annotation_count', 'api_path', 'full_title', 'header_image_thumbnail_url', 'header_image_url', 'id', 'lyrics_owner_id',
'lyrics_state', 'path', 'pyongs_count', 'song_art_image_thumbnail_url', 'song_art_image_url', 'stats', 'title',
'title_with_featured', 'url', 'primary_artist'
UNIT TESTED: by putting in each item in data_term list(above) and seeing if it returned the same info (but just for that specfific data term) as was in the general call of the search_for_song
**Problem w/ 'primary_artist' that it has a sublist attached to it, so caling it in this manner returns another list for the primary_artist rather than 1 thing... ignoring it because for this project's purpose, primary_artist won't need to be called
e.g. print(pull_spec_data('highest in the room','full_title'))
"""
json_obj = search_for_song(search_term)
return json_obj[data_term]
# print(json_obj['response']['hits'][0]['result'].keys())
def get_lyrics(search_term):
"""
Scrapes the lyrics for the song specified in the search_term
UNIT TESTED: by putting in multiple search terms and seeing if it pulled the lyrics
e.g. print(get_lyrics('highest in the room'))
"""
URL = pull_spec_data(search_term, 'url')
# URL = json_obj['response']['hits'][0]['result']['url']
page = requests.get(URL)
html = BeautifulSoup(page.text, "html.parser") # Extract the page's HTML as a string
# Scrape the song lyrics from the HTML
lyrics = html.find("div", class_="lyrics").get_text()
return lyrics
#### For scraping if you have the song ID
# song_id = 82926
# querystring = "https://api.genius.com/songs/" + str(song_id) # Songs endpoint
# request = urllib.Request(querystring)
# request.add_header("Authorization", "Bearer " + "QootmN8aXaeUEtMguYVsDpQyr1VO6s1O8FUB0cTccMeyB4GRTHMvlDfUUb7YjEF1")
# request.add_header("User-Agent", "")
# response = urllib.urlopen(request, timeout=3)
# raw = response.read()
# json_obj = json.loads(raw)['response']['song']
|
d72900d62f7e0819a7d47db871e7064fe3168ca2 | Glowingspy/cosine-tangent-and-sine | /cos, tan and sine calculater.py | 2,528 | 4.125 | 4 | import time
import math
print('This program tells calculates the sine, cosine and tangent of the value you have inputed')
def cos():
print('Type the integer!')
z = int(input())
time.sleep(1)
cis = math.cos(z)
time.sleep(1)
print(cis)
time.sleep(1)
print('Do you want to start again')
time.sleep
print('Type "yes" , or "no"')
abc = input()
if abc == 'yes':
begin()
elif abc == 'no':
print('Thank you for using! ')
else:
print('That was an invalid statment. The program will restart anyway.')
begin()
def sin():
time.sleep(1)
print('Type the integer!')
b = int(input())
time.sleep(1)
sine = math.sin(b)
time.sleep(1)
print(sine)
time.sleep(1)
print('Do you want to start again')
time.sleep(1)
print('Type "yes" , or "no"')
c = input()
if c == 'yes':
print('Ok')
begin()
elif c == 'no':
print('Thank you for using! ')
else:
print('That was an invalid statment. The program will restart anyway.')
begin()
def tan():
print('Type the integer!')
h = int(input())
time.sleep(1)
tani = math.tan(h)
time.sleep(1)
print(tani)
time.sleep(1)
print('Do you want to start again')
print('Type "yes" , or "no"')
d = input()
if d == 'yes':
begin()
elif d == 'no':
print('Thank you for using! ')
else:
print('That was an invalid statment. The program will restart anyway.')
begin()
def main():
print('What type of function do you want? ')
time.sleep(0.5)
print('sine ------- sin')
time.sleep(1)
print('cosine ------ cos')
time.sleep(1)
print('tangent -------- tan')
time.sleep(0.5)
y = input()
if y == 'cos':
print('Ok')
cos()
elif y == 'sin':
print('Ok')
sin()
elif y == ('tan'):
tan()
else:
print('That was an invalid statment. Try again!!!')
main()
def begin():
print('Do you want to start?')
time.sleep(1)
print('Type "yes" or "no" ')
time.sleep(1)
x = input()
if x == 'yes':
print('Ok')
main()
elif x == 'no':
print('Get out of here!!!')
else:
print('That was an invalid statment. Please try again')
time.sleep(1)
begin()
begin() |
376c6bad299e91cdc0f8970a727ea8c3fd3923d2 | Y-Suzaki/python-advanced-sample | /advanced/sample_metaclass.py | 903 | 4.03125 | 4 | from abc import abstractmethod
from abc import ABCMeta
class Human:
@abstractmethod
def shut(self):
pass
class Employee(Human):
def __init__(self):
print('init:{}'.format(self.__class__))
# @abstractmethodを付与しただけでは、特にエラーになってくれない
# classオブジェクト作成時に、metaclassの機能を動かす必要がある
print('start employee = Employee()')
employee = Employee()
employee.shut()
# metaclass=ABCMetaを指定する。ABCクラスを継承するでも良い。
class NewHuman(metaclass=ABCMeta):
@abstractmethod
def shut(self):
pass
class NewEmployee(NewHuman):
pass
# TypeError: Can't instantiate abstract class NewEmployee with abstract methods shutをきちんとraiseしてくれる
print('start new_employee = NewEmployee()')
new_employee = NewEmployee()
|
cfaa20fa6349968c4df3400efd03b6a6c1e1664b | RishiKuls/turtle-programing-python | /5.py | 398 | 3.859375 | 4 | import turtle
t=turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
colors=["red","black","blue","orange","green","purple","pink"]
your_name=turtle.textinput("enter your name","what is your name")
for x in range(100):
t.pencolor(colors[x%4])
t.penup()
t.width(3)#3
t.forward(x*4)#x
t.left(92)#50
t.pendown()
t.write(your_name,font=("times",int((x+4)/4),"bold")) |
b95de395640cd172fa7dc2093c466ede184e81dd | Aitmambetov/2chapter-task10 | /task10.py | 1,306 | 4.6875 | 5 | """
You are given a string.
In the first line, print the third character of this string.
In the second line, print the second to last character of this string.
In the third line, print the first five characters of this string.
In the fourth line, print all but the last two characters of this string.
In the fifth line, print all the characters of this string with even indices
(На английском языке что бы Вы научились понимать remember indexing starts at 0, so the characters are displayed starting with
the first).
In the sixth line, print all the characters of this string with odd indices (На английском языке что бы Вы научились понимать i.e.
starting with the second character in the string).
In the seventh line, print all the characters of the string in reverse order.
In the eighth line, print every second character of the string in reverse order,
starting from the last one.
In the ninth line, print the length of the given string.
"""
given_str = str(input('введите любое слово '))
print(given_str[2])
print(given_str[1:])
print(given_str[:5])
print(given_str[:-2])
print(given_str[1::2])
print(given_str[0::2])
print(given_str[::-1])
rev = given_str[::-1]
print(rev[1::2])
print(len(given_str)) |
f888539e36684f488933380b6ada9bb7b4f60077 | abhinav-kesari/tathastu_week_of_code | /Day1/program4.py | 302 | 4.09375 | 4 | cost_price = float(input("Enter Cost price :"))
selling_price = float(input("Enter Selling price :"))
profit = selling_price - cost_price
print("Profit from this sell : ",profit )
newselling_price = 0.05 * profit + selling_price
print("Selling price after profit increse by 5% :",newselling_price) |
f3e5d554d73f7858256bb924a8788b66f10bac04 | mccre110/computer-science-1 | /Perfect Number.py | 284 | 3.8125 | 4 | number = int(input("Enter a number to classify: "))
divisor=1
sum_of_div=0
for test in range(2,1,number+1):
if number%divisor ==0:
sum_of_div +=divisor
divisor+=1
if sum_of_div==number:
print(number,"is perfect")
else:
print(number,"is not perfect")
|
213a44dc446c2a7eaed726db9e38ad609858b7a9 | LuisWitts/Python- | /aula 8 modulos.py | 135 | 4.125 | 4 | from math import sqrt
N = int(input('Digite um número'))
raiz = math.sqrt(N)
print('A raiz de {} é igual a {:.2f}'.format(N, raiz))
|
e0d878c8872ba9bee2aa2bdd229f1de165886bf4 | rudysemola/ASE-skeleton-HW1 | /bedrock_a_party/classes/party.py | 2,724 | 3.671875 | 4 | """File that contains all classes."""
class Food:
def __init__(self, food, user):
"""
:param food food that the guest will bring
:param user username of the guest
"""
self.food = food
self.user = user
def __eq__(self, other):
if isinstance(other, Food):
return self.food == other.food and self.user == other.user
return False
def serialize(self):
return {'food': self.food,
'user': self.user}
class FoodList():
def __init__(self):
self.foodlist = []
def add(self, food, user):
to_add = Food(food, user)
if to_add in self.foodlist:
raise ItemAlreadyInsertedByUser(user + " already committed to bring " + food)
self.foodlist.append(to_add)
return to_add
def remove(self, food, user):
to_remove = Food(food, user)
try:
self.foodlist.remove(to_remove)
except ValueError:
raise NotExistingFoodError("user " + user + " has not added " + food + " to this party foodlist")
def serialize(self):
return [f.serialize() for f in self.foodlist]
class Party:
"""
params:
:param _id id of the party
:guests: array of users that will be able to add and remove food
"""
def __init__(self, _id, guests):
if len(guests) == 0:
raise CannotPartyAloneError("You cannot create a party without guests")
self.id = _id
self.guests = guests
self.food_list = FoodList()
def get_food_list(self):
return self.food_list
def add_to_food_list(self, item, user):
if user in self.guests:
return self.food_list.add(item, user)
else:
raise NotInvitedGuestError(user + " is not invited to this party")
def remove_from_food_list(self, item, user):
self.food_list.remove(item, user)
def serialize(self):
return {
'id': self.id,
'guests': self.guests,
'foodlist': self.food_list.serialize()
}
class CannotPartyAloneError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class NotInvitedGuestError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ItemAlreadyInsertedByUser(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class NotExistingFoodError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
|
7e614a71048d8ab79d02ae38304fbb6c8238e5d6 | ksd4224/Profiling | /profilingObject.py | 4,969 | 4.53125 | 5 | import profiling
print("This program profiles 3 people by asking the user information of those 3 people." +
"After the information is entered the user can lookup people based on attributes."+
"This can help organizations/police department look up people just by entering one"+
"attribute of the person (address, height, name, weight, phone number, etc)\n")
# info about person1
name1 = input("Enter Name: ")
address1 = input("Enter Address: ")
phone1 = input("Enter Phone Number: ")
gender1 = input("Enter Gender: ")
height1 = input("Enter Height (in Feet): ")
weight1 = input("Enter Weight (in Lbs): ")
person1 = profiling.Profiling(name1)
person1.addAddress(address1)
person1.addPhone(phone1)
person1.addGender(gender1)
person1.addHeight(height1)
person1.addWeight(weight1)
#info about person2
name2 = input("\nEnter Name: ")
address2 = input("Enter Address: ")
phone2 = input("Enter Phone Number: ")
gender2 = input("Enter Gender: ")
height2 = input("Enter Height (in Feet): ")
weight2 = input("Enter Weight (in Lbs): ")
person2 = profiling.Profiling(name2)
person2.addAddress(address2)
person2.addPhone(phone2)
person2.addGender(gender2)
person2.addHeight(height2)
person2.addWeight(weight2)
#info about person3
name3 = input("\nEnter Name: ")
address3 = input("Enter Address: ")
phone3 = input("Enter Phone Number: ")
gender3 = input("Enter Gender: ")
height3 = input("Enter Height (in Feet): ")
weight3 = input("Enter Weight (in Lbs): ")
person3 = profiling.Profiling(name3)
person3.addAddress(address3)
person3.addPhone(phone3)
person3.addGender(gender3)
person3.addHeight(height3)
person3.addWeight(weight3)
'''_____________________________________________________________________________'''
#LOOK UP A PERSON BASED ON ATTRIBUTES
lookUp = input("Look up a person?: ")
while lookUp == "Y" or lookUp == "y" or lookUp == "yes" or lookUp == "Yes" or lookUp == "YES":
method = input("Method of looking up (name, address, phone, gender, height, weight): ")
#lookup using name
if method.lower() == "name":
name_lookUp = input("Name lookup: ")
print("\n")
if name_lookUp.lower() == name1.lower():
person1.profile()
print("\n")
if name_lookUp.lower() == name2.lower():
person2.profile()
print("\n")
if name_lookUp.lower() == name3.lower():
person3.profile()
print("\n")
#lookup using address
elif method.lower() == "address":
add_lookUp = input("Address lookup: ")
print("\n")
if add_lookUp.lower() == address1.lower():
person1.profile()
print("\n")
if add_lookUp.lower() == address2.lower():
person2.profile()
print("\n")
if add_lookUp.lower() == address3.lower():
person3.profile()
print("\n")
#lookup using phone number
elif method.lower() == "phone":
phone_lookUp = input("Phone Number lookup: ")
print("\n")
if phone_lookUp.lower() == phone1.lower():
person1.profile()
print("\n")
if phone_lookUp.lower() == phone2.lower():
person2.profile()
print("\n")
if phone_lookUp.lower() == phone3.lower():
person3.profile()
print("\n")
#lookup using gender
elif method.lower() == "gender":
gender_lookUp = input("Gender lookup: ")
print("\n")
if gender_lookUp.lower() == gender1.lower():
person1.profile()
print("\n")
if gender_lookUp.lower() == gender2.lower():
person2.profile()
print("\n")
if gender_lookUp.lower() == gender3.lower():
person3.profile()
print("\n")
#lookup using height
elif method.lower() == "height":
height_lookUp = input("Height lookup: ")
print("\n")
if height_lookUp.lower() == height1.lower():
person1.profile()
print("\n")
if height_lookUp.lower() == height2.lower():
person2.profile()
print("\n")
if height_lookUp.lower() == height3.lower():
person3.profile()
print("\n")
#lookup using weight
elif method.lower() == "weight":
weight_lookUp = input("Weighe lookup: ")
print("\n")
if weight_lookUp.lower() == weight1.lower():
person1.profile()
print("\n")
if weight_lookUp.lower() == weight2.lower():
person2.profile()
print("\n")
if weight_lookUp.lower() == weight3.lower():
person3.profile()
print("\n")
else:
print("You did not chose the method from the given list")
lookUp = input("Look up a person?: ")
|
32c376349eac64453cdfb369c2c50f5d5ff929ad | ru04ru041989/MOOC | /Project_Euler/Q36.py | 677 | 3.78125 | 4 | # Double-base palindromes
"""
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
"""
def check_palindrome(n):
if len(n) == 1 or n == '':
return True
while n:
if n[0] == n[-1]:
return check_palindrome(n[1:-1])
return False
def main(limit):
ans = []
for i in range(limit):
if check_palindrome(str(i)) and check_palindrome(str(bin(i))[2:]):
ans.append(i)
return ans
ans = main(1000000) |
6ee080bde93dbfe7aa1382509f1b91ef904d8ee6 | mi6eto/SoftUni | /Programming Fundamentals/text_processing/05.emoticon_finder.py | 122 | 3.671875 | 4 | text = input()
for el in range(len(text)):
emoji = text[el]
if emoji == ":":
print(emoji + text[el + 1])
|
8ec009af11e769e365f991c8ee8f5b607b63a24d | Hikarou/ciphers | /main.py | 3,350 | 3.921875 | 4 | from caesar.caesar import Caesar
from vigenere.vigenere import Vigenere
if __name__ == "__main__":
while True:
# Traitement du choix de l'algorithme
out = -1
alg = 0
while alg == 0:
print("Quel algorithme sera utilisé ? (Q : pour quitter)\n\t1 - César\n\t2 - Vigenère")
alg = input()
if alg.lower() == "q":
out = 0
break
try:
alg = int(alg)
if alg > 2 or alg < 1:
raise ValueError()
except ValueError:
print(
"La valeur donnée n'est pas un algorithme possible!\n"
"\t1 - César\n\t2 - Vigenère"
)
alg = 0
if out == 0:
break
# Traitement du choix de la clé
cle = -1
while True:
print("Quelle sera la clé de l'algorithme choisi ? (Q : pour quitter)")
if alg == 1:
print("\t[0;26]")
else:
print("\t[a-zA-Z]+")
cle = input()
if cle.lower() == "q":
out = 0
break
# Si c'est l'algorithme de César, il faut que ce soit un chiffre.
if alg == 1:
try:
cle = int(cle)
break
except ValueError:
print(
"La clé donnée n'est pas un entier!\n"
"Merci de donner une valeur correcte!\n"
)
cle = -1
elif alg == 2:
break
if out == 0:
break
chiffr = -1
while chiffr == -1:
print("Il faut chiffrer le message ou le déchiffrer ? (Q : pour quitter)\n\t1 - Chiffrer\n\t2 - Déchiffrer")
chiffr = input()
if chiffr.lower() == "q":
out = 0
break
try:
chiffr = int(chiffr)
if chiffr > 2 or chiffr < 1:
raise ValueError()
except ValueError:
print(
"La valeur donnée n'est pas un choix possible!\n"
"\t1 - Chiffrer\n\t2 - Déchiffrer"
)
chiffr = -1
if out == 0:
break
print("Quel message faudra-t'il ", end="")
if chiffr == 2:
print("dé", end="")
print("chiffrer ?")
mess = input()
if alg == 1: # César
alg = Caesar(cle)
elif alg == 2: # Vigenere
alg = Vigenere(cle)
else:
print("L'aglorithme n'est pas le bon... ceci ne devrait jamais arriver")
quit(-1)
outMess = ""
if chiffr == 1:
outMess = alg.cipher_string(mess)
elif chiffr == 2:
outMess = alg.decipher_string(mess)
else:
print("Le choix de (dé)chiffrement n'est pas le bon... ceci ne devrait jamais arriver")
quit(-1)
print("Le message initial était :\n{}\nAprès ".format(mess), end="")
if chiffr == 2:
print("dé", end="")
print("chiffrement, le message est :\n{}".format(outMess))
print("Bye!")
|
0772e4761ae0601f3177a4cab543744bcfbd39b1 | suprithreddym/python | /oops/basicclass.py | 1,107 | 3.75 | 4 | class kettle(object):
power_source = "electricity"
def __init__(self,make,price):
self.make = make
self.price = price
self.on = False
def switch_on(self):
self.on = True
kenwood = kettle("kenwood", 8.99)
print(kenwood.make)
print(kenwood.price)
hamiton = kettle("hamilton", 14.55)
print("Models: {} = {}, {} = {}".format(kenwood.make, kenwood.price, hamiton.make, hamiton.price))
print("Models: {0.make} = {0.price} , {1.make} = {1.price}".format(kenwood, hamiton))
print(hamiton.on)
hamiton.switch_on() # calling by calue
print(hamiton.on)
kettle.switch_on(kenwood) # using class to call
print(kenwood.on)
print("*" * 80)
kenwood.power = 1.5 # assigning values dynamically using instance
print(kenwood.power)
print("switch to atomic power")
kettle.power_source = "atomic"
print(kettle.power_source)
print("switch to gas")
kenwood.power_source = "gas"
print(kettle.power_source)
print(kenwood.power_source)
print(hamiton.power_source)
print(kettle.__dict__)
print(kenwood.__dict__)
print(hamiton.__dict__) |
81e9078b1802ab7a794587ebc4c54496eb6c779e | muguang/qlcoder | /uv_anaiysis.py | 880 | 3.5625 | 4 | """
每一个网站都会根据访客日志统计访客数据,比如UV。UV能够回答一个关键的市场营销问题:“到底有多少人(潜在客户)看到了你发布的信息(即网站)。
下面根据题目给出的某购物网站访问日志,统计当天该网站UV。日志文件的每一行代表一次访问行为,每行分别包含三项,用户访问的时间,用户的id,用户的行为。请问8月24号当天,该网站有多少个用户访问了。
"""
f = open("uv.txt")
list_user = []
s = f.readlines()
print(len(s))
len_l = len(s)
for i in range(len_l):
ss = s[i]
user_id = ss.split(" ")[1]
if user_id not in list_user:
list_user.append(user_id)
print(len(list_user))
print(len(list_user))
# while True:
#
#
# #print(s)
# Python print(len({i.split(' ')[1] for i in open('./uv.txt')}))
|
c9f101d6dd261db62168e728cd5b09a5a4723517 | MohamadHaziq/100-days-of-python | /day_11-20/day_11/blackjack.py | 3,596 | 3.875 | 4 | ############### Blackjack Project #####################
#Difficulty Normal 😎: Use all Hints below to complete the project.
#Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project.
#Difficulty Extra Hard 😭: Only use Hints 1 & 2 to complete the project.
#Difficulty Expert 🤯: Only use Hint 1 to complete the project.
############### Our Blackjack House Rules #####################
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace can count as 11 or 1.
## Use the following list as the deck of cards:
## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
## The cards in the list have equal probability of being drawn.
## Cards are not removed from the deck as they are drawn.
## The computer is the dealer.
import os
import random
import art
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
play = input("Press 'y' if you wanna play and 'n' if you don't wanna: ")
def clear():
# for windows
if os.name == 'nt':
_ = os.system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = os.system('clear')
def deal_card():
card = random.choice(cards)
return card
def calculate_score(player):
score = sum(player)
if score == 21 and len(player) == 2:
score = 0
if score > 21 and 11 in player:
player.remove(11)
player.append(1)
score = sum(player)
return score
def compare(user_score, dealer_score):
if user_score > 21 and dealer_score > 21:
print ("Y'all both lose")
elif user_score > 21:
print ("Player goes bust ! Dealer wins")
elif dealer_score > 21:
print ("Dealer goes bust ! Player wins")
elif user_score > dealer_score and user_score <= 21:
print ("Player Wins")
elif dealer_score > user_score and dealer_score <= 21:
print ("Dealer Wins")
elif user_score == dealer_score:
print ("Draw game !")
def play_blackjack():
print (art.logo)
user_cards = []
dealer_cards = []
for n in range(2):
user_cards.append(deal_card())
dealer_cards.append(deal_card())
user_score = calculate_score(user_cards)
dealer_score = calculate_score(dealer_cards)
if user_score == 0:
print ("You win, Blackjack !")
if dealer_score == 0:
print ("You lose, dealer Blackjack")
keep_drawing = True
print (f"Your current hand is {user_score} consisting {user_cards}")
print (f"Dealer first card is {user_cards[0]}")
while user_score < 21 and keep_drawing == True:
draw_card = input("Type 'draw' to draw a card or anything else to pass: ")
if draw_card == 'draw':
user_cards.append(deal_card())
user_score = calculate_score(user_cards)
print (f"Your current hand is {user_score} consisting {user_cards}")
else:
keep_drawing = False
if user_score > 21:
print ("You went bust !")
print (f"Dealer current hand is {dealer_score} consisting {dealer_cards}")
while dealer_score < 17 and dealer_score != 0:
print ("Dealer draws a card")
dealer_cards.append(deal_card())
dealer_score = calculate_score(dealer_cards)
print (f"Dealer current hand is {dealer_score} consisting {dealer_cards}")
compare(user_score, dealer_score)
while play == 'y':
play_blackjack()
play = input("Play again ? 'y', n' ?: ")
if play == 'y':
clear()
else:
play = 'n'
|
26a89fafde36ff3a347eb9408186bd6170b6c1b9 | jimmyjwu/yelp_expert_finding | /analysis/analysis_utilities.py | 6,921 | 3.5 | 4 | """
Utilities specifically for machine learning and data analysis.
"""
from utilities import *
def balanced_sample(users, label_name='label'):
"""
Given a list of user dictionaries with a Boolean label, returns a maximal sample of the users
in which both labels are equally common.
"""
positive_samples = [user for user in users if user[label_name] == 1]
negative_samples = [user for user in users if user[label_name] == 0]
if len(positive_samples) < len(negative_samples):
return positive_samples + random.sample(negative_samples, len(positive_samples))
else:
return random.sample(positive_samples, len(negative_samples)) + negative_samples
def remove_attribute(users, attribute):
""" Deletes an attribute from all users in a list of user dictionaries. """
[ user.pop(attribute, None) for user in users ]
def vectorize_users(users, attributes, label_name='label'):
"""
Given a list of user dictionaries, returns
X : a numpy array of arrays, each representing the attribute values of a single user
y : a numpy array of corresponding correct labels for X
NOTE: Output vectors respect ordering of input attributes: for every x in X, x[i] is the value
of attribute attributes[i].
"""
user_vectors = []
labels = []
for user in users:
user_vectors += [ [user[attribute] for attribute in attributes if attribute != label_name] ]
labels += [ user[label_name] ]
return numpy.array(user_vectors), numpy.array(labels)
def partition_data_vectors(feature_vectors, labels, fraction_for_training=0.7):
"""
Given a list of feature vectors (lists) and their corresponding labels, returns:
- A training set
- A test set, disjoint from the training set
- A recall test set (subset of test data labeled positive)
NOTE: Does not sample randomly. Any randomization must be applied before using this utility.
"""
dataset_size = len(feature_vectors)
training_set_size = int(fraction_for_training * dataset_size)
test_set_size = dataset_size - training_set_size
training_set = feature_vectors[0:training_set_size]
training_set_labels = labels[0:training_set_size]
test_set = feature_vectors[-test_set_size:]
test_set_labels = labels[-test_set_size:]
positive_test_set = [vector for i, vector in enumerate(test_set) if test_set_labels[i] == 1]
positive_test_set_labels = [1]*len(positive_test_set)
return training_set, training_set_labels, test_set, test_set_labels, positive_test_set, positive_test_set_labels
def normalize_users(users, excluded_attributes=[]):
"""
Given a list of user dictionaries whose attributes are numeric values, returns a list of
users in which all attributes, EXCEPT those whose names are in excluded_attributes,
are normalized to [0, 1].
Normalization is done using min-max.
"""
excluded_attributes = set(excluded_attributes)
# Find extreme values for each attribute
max_user = {attribute: float('-infinity') for attribute in users[0].keys()}
min_user = {attribute: float('infinity') for attribute in users[0].keys()}
for user in users:
for attribute, value in user.iteritems():
if attribute not in excluded_attributes:
max_user[attribute] = max(max_user[attribute], value)
min_user[attribute] = min(min_user[attribute], value)
# Normalize users
for user in users:
for attribute, value in user.iteritems():
if attribute not in excluded_attributes:
user[attribute] = float(value - min_user[attribute]) / (max_user[attribute] - min_user[attribute])
return users
def show_histogram(values, value_name='Value', bins=100, range_to_display=(0,0), normed=False):
if range_to_display == (0,0):
n, bins, patches = pyplot.hist(values, bins=bins, normed=normed, facecolor='g', alpha=0.75)
else:
n, bins, patches = pyplot.hist(values, bins=bins, range=range_to_display, normed=normed, facecolor='g', alpha=0.75)
pyplot.xlabel(value_name)
pyplot.ylabel('Frequency')
# pyplot.title('Histogram of ' + value_name + 's')
pyplot.axis('tight')
pyplot.grid(True)
pyplot.show()
def show_histogram_with_broken_y_axis(values, value_name='Value', bins=100, range_to_display=(0,0), normed=False, cutout=(0,0)):
"""
Displays a histogram with a break (a section cut out) in the y-dimension.
"""
n, bins, patches = pyplot.hist(x=values, bins=bins, range=range_to_display, normed=normed, facecolor='g', alpha=0.75)
bins = numpy.delete(bins, -1)
width = bins[2] - bins[1]
pyplot.xlabel(value_name)
pyplot.ylabel('Frequency')
# pyplot.title('Histogram of ' + value_name + 's')
pyplot.axis('tight')
# Create two plots with a y-axis break in between
figure, (axes_1, axes_2) = pyplot.subplots(2, 1, sharex=True)
# Plot the same data as bar charts on both axes
axes_1.bar(bins, n, width, color='g', alpha=0.75)
axes_2.bar(bins, n, width, color='g', alpha=0.75)
# Turn grid lines on
axes_1.grid(True)
axes_2.grid(True)
axes_1.set_ylim(bottom=cutout[1]) # Limit first axis to upper parts of bars
axes_2.set_ylim(0, cutout[0]) # Limit second axis to lower parts of bars
# Fix x-axis boundaries (without this, visible boundary is changed by diagonal lines below)
axes_1.set_xlim(right=range_to_display[1])
axes_2.set_xlim(right=range_to_display[1])
# Hide the spines between axes_1 and axes_2
axes_1.spines['bottom'].set_visible(False)
axes_2.spines['top'].set_visible(False)
axes_1.xaxis.tick_top()
axes_1.tick_params(labeltop='off') # Omit tick labels at the top
axes_2.xaxis.tick_bottom()
# Add short diagonal lines around breaks
# Note: axis dimensions are always on a [0,1] scale regardless of actual range
d = .015 # Size of diagonal lines
kwargs = dict(transform=axes_1.transAxes, color='k', clip_on=False)
axes_1.plot((-d, +d), (-d, +d), **kwargs) # Top-left diagonal
axes_1.plot(((1 - d), (1 + d)), (-d, +d), **kwargs) # Top-right diagonal
kwargs.update(transform=axes_2.transAxes) # Switch to the bottom axes
axes_2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # Bottom-left diagonal
axes_2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # Bottom-right diagonal
pyplot.show()
def show_feature_importances(forest, features):
"""
Given a trained forest-type classifier (e.g. random forest, boosted decision tree, etc.),
displays a bar chart of the features' relative importances according to the Gini impurity index.
"""
m = len(features)
sorted_importances_and_features = sorted(zip(forest.feature_importances_, features))
sorted_importances, sorted_features = zip(*sorted_importances_and_features)
# Print the feature ranking
for importance, feature in sorted_importances_and_features:
print feature, ':\t', format_as_percentage(importance)
# Plot the feature importances of the forest
pyplot.figure()
# pyplot.title('Feature Importances')
pyplot.barh(range(m), sorted_importances, color='c', align='center')
pyplot.yticks(range(m), sorted_features, fontsize='xx-large')
pyplot.ylim([-1, m])
pyplot.axis('tight')
pyplot.grid(True)
pyplot.show()
|
fbf17a4b2389de4c7c6be95d7751a922d9b1359d | mveilleux/ml-for-trading | /ml.py | 1,224 | 3.640625 | 4 | from scipy import stats
from sklearn import neighbors
import numpy as np
'''
# Linear Regression
learner = LinRegLearner() # Makes an instance of the learner
learner.train(Xtrain, Ytrain) # Trains the model with our data
Y = learner.query(Xtest) # run test data to get the y data
# KNN
learner = KNNLearner(k=3) # sets how many nearest neighbors to use
learner.train(Xtrain, Ytrain) # Trains the model with our data
Y = learner.query(Xtest) # run test data to get the y data
use numpy.corrcoef to measure correlation
'''
class LinRegLearner:
def __init__(self):
pass
def train(self, X, Y):
self.m, self.b, self.r_value, self.p_value, self.std_err = stats.linregress(X,Y)
def query(self, X):
y = self.m * X + self.b
return y
class KNNLearner:
def __init__(self, k=3):
self.learner = neighbors.KNeighborsClassifier(n_neighbors=k)
def train(self, X, Y):
# Reshape X for KNN algo
if (X.ndim == 1):
X = np.reshape(X, (X.shape[0], 1))
# Convert Y to integers (ie; *100)
Y = Y * 100
Y = Y.astype(int)
self.learner.fit(X, Y)
def query(self, X):
return float(self.learner.predict(X)[0]) / 100
|
74b6280ba272188be71052df34ed15c76cd3b08e | AnzeMendoza/PythonUNSAM | /ejercicios_python/10-clase/alquiler.py | 1,504 | 3.890625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def ajuste_lineal_simple(x, y):
"""Retorna los coheficientes de la regresión lineal."""
a = sum(((x - x.mean()) * (y - y.mean()))) / sum(((x - x.mean()) ** 2))
b = y.mean() - a * x.mean()
return a, b
def plot_dispercion(lista_x, lista_y):
"""Plot del Scatter"""
plt.scatter(x=lista_x, y=lista_y)
plt.title("gráfico de dispersión de Superficie-Alquiler")
plt.xlabel("Superficie")
plt.ylabel("Alquiler")
plt.show()
def plot_recta(lista_x, lista_y):
"""Plot de la recta que ajusta a la dispersión."""
a, b = ajuste_lineal_simple(lista_x, lista_y)
grilla_x = np.linspace(min(lista_x), max(lista_x), num=100)
grilla_y = grilla_x * a + b
plt.plot(grilla_x, grilla_y, c="red")
plt.show()
return a, b
def error_cuadratico_medio(superficie, alquiler, a, b):
"""Imprime el calculo del error cuadratico medio."""
errores = alquiler - (a * superficie + b)
print("###################################")
print(errores)
print("ECM:", (errores ** 2).mean())
print("###################################")
def main():
print("Ejercicio 10.14: precio_alquiler ~ superficie")
superficie = np.array([150.0, 120.0, 170.0, 80.0])
alquiler = np.array([35.0, 29.6, 37.4, 21.0])
plot_dispercion(superficie, alquiler)
a, b = plot_recta(superficie, alquiler)
error_cuadratico_medio(superficie, alquiler, a, b)
if __name__ == "__main__":
main()
|
cfe50089c225b580b92eb6b1c13067f6ef61e915 | wpolanco/Hacktoberfest2021-2 | /prime.py | 399 | 4.28125 | 4 | #Python Program to Check if a number is prime or not
def check_prime(n):
if n > 1:
for i in range(2, n):
if (n % i) == 0:
return True
break
else:
return "Input number must be greater than 1"
n = int(input("Enter the number to check if it is Prime: "))
if check_prime(n):
print(n, "is not a Prime Number.")
else:
print(n, "is a Prime Number")
|
cdda28a2b2213ea6c2e49dd6a12e0e4801666a16 | rhenderson2/python1-class | /chapter06/hw_6-10.py | 325 | 4.03125 | 4 | # homework assignment section 6-10
favorite_numbers = {'John': [7, 3, 5],
'Mike': [4, 7],
'John L': 2,
'Niki': [8, 5, 6],
'Mary': 4}
for key,value in favorite_numbers.items():
print(f"\nName: {key}")
print(f"Favorite Number(s): {value}") |
8f6f52794bf4ae20d54d58a3b4ad1c76c6a50175 | SirClashin1/FirstMatPlotLibProject | /randomplot.py | 844 | 3.84375 | 4 | #imports
import matplotlib.pyplot as plt
import random
#initializing variables
temp = 0
r = random.randint
x_vals = []
y_vals = []
z_vals = []
#adding random variables to the list
for i in range(1, 11):
temp = r(1, 100)
x_vals.append(temp)
for i in range(1, 11):
temp = r(1, 100)
y_vals.append(temp)
for i in range(1, 11):
temp = r(1, 100)
z_vals.append(temp)
#sorting lists
x_vals.sort()
y_vals.sort()
z_vals.sort()
#making 2nd graph even more random
temp = r(1,2)
if temp == 1:
temp = y_vals
else:
temp = x_vals
#making titles
plt.title("Random plot")
plt.xlabel("x-values")
plt.ylabel("y-values")
#plotting and showing graph
plt.plot(x_vals, y_vals, color = "blue")
plt.plot(temp, z_vals, color = "red")
plt.show() |
6479c8131bc5f0e02b64137c497e0c19862fdbc1 | Kings-Ggs-Arthers/CP3-Gun-siri | /assignments/Lecture54_Gun_s.py | 928 | 3.75 | 4 | def login():
usernameInput = input("Username :")
passwordInput = input("Password :")
if usernameInput == "gun" and passwordInput == "siri":
return True
else:
return False
def showMenu():
print(" ----- A shop ----- ")
print("Select Menu")
print("1.Vat calculate")
print("2.Price calculate")
def selectMenu():
userSelect = int(input("Menu :"))
if userSelect == 1:
price = int(input("price :"))
vatCalculate(price)
elif userSelect == 2:
priceCalculate()
def vatCalculate(Prices):
vat = 7
result = Prices + (Prices * vat / 100)
return print(result)
def priceCalculate():
price1 = int(input("1st Price :"))
price2 = int(input("2nd Price :"))
return print(vatCalculate(price1 + price2))
if login() == True :
showMenu()
selectMenu()
else:
print("Invalid Username or Password") |
811a5e0186bba6c7b57d491822ca814c918f2814 | ricardovogel/adventofcode2017 | /day04/d04c2.py | 564 | 3.53125 | 4 | def isPalindrome(a, b):
a = sorted(a)
b = sorted(b)
return a == b
res = 0
with open("day04/input.txt") as f:
for line in f:
a = []
for word in line.split():
if word in a:
res -= 1
break
stopIt = False
for knownWord in a:
if isPalindrome(word, knownWord):
res -= 1
stopIt = True
break
if stopIt:
break
a.append(word)
res += 1
print(res)
|
7bab1f7242aac45c2a21ad4dd027917a5b3e9578 | UCREL/pymusas | /pymusas/base.py | 4,290 | 3.84375 | 4 | """
Base classes for custom classes to inherit from.
"""
from abc import ABC, abstractmethod
import importlib
from typing import Iterable, List, cast
import srsly
class Serialise(ABC):
'''
An **abstract class** that defines the basic methods, `to_bytes`, and
`from_bytes` that is required for all :class:`Serialise`s.
'''
@abstractmethod
def to_bytes(self) -> bytes:
'''
Serialises the class to a bytestring.
# Returns
`bytes`
'''
... # pragma: no cover
@staticmethod
@abstractmethod
def from_bytes(bytes_data: bytes) -> "Serialise":
'''
Loads the class from the given bytestring and returns it.
# Parameters
bytes_data : `bytes`
The bytestring to load.
# Returns
:class:`Serialise`
'''
... # pragma: no cover
@staticmethod
def serialise_object_to_bytes(serialise_object: "Serialise"
) -> bytes:
'''
Given a serialise object it will serialise it to a bytestring.
This function in comparison to calling `to_bytes` on the serialise
object saves meta data about what class it is so that when loading the
bytes data later on you will know which class saved the data, this
would not happen if you called `to_bytes` on the custom object.
# Parameters
serialise_object : `Serialise`
The serialise object, of type :class:`Serialise`, to serialise.
# Returns
`bytes`
'''
class_name = serialise_object.__class__.__name__
module_name = serialise_object.__module__
serialised_object = serialise_object.to_bytes()
serialised_object_and_meta_data \
= (serialised_object, (class_name, module_name))
return cast(bytes, srsly.msgpack_dumps(serialised_object_and_meta_data))
@staticmethod
def serialise_object_from_bytes(bytes_data: bytes) -> "Serialise":
'''
Loads the serialise object from the given bytestring and return it.
This is the inverse of function of :func:`serialise_object_to_bytes`.
# Parameters
bytes_data : `bytes`
The bytestring to load.
# Returns
`Serialise`
'''
serialised_custom_object, meta_data = srsly.msgpack_loads(bytes_data)
class_name, module_name = meta_data
custom_object_class: Serialise \
= getattr(importlib.import_module(module_name), class_name)
return custom_object_class.from_bytes(serialised_custom_object)
@staticmethod
def serialise_object_list_to_bytes(serialise_objects: Iterable["Serialise"]
) -> bytes:
'''
Serialises an `Iterable` of serialise objects in the same way as
:func:`serialise_object_to_bytes`.
# Parameters
serialise_objects : `Iterable[Serialise]`
The serialise objects, of type :class:`Serialise`, to serialise.
# Returns
`bytes`
'''
serialised_objects: List[bytes] = []
for serialise_object in serialise_objects:
serialised_object \
= Serialise.serialise_object_to_bytes(serialise_object)
serialised_objects.append(serialised_object)
return cast(bytes, srsly.msgpack_dumps(serialised_objects))
@staticmethod
def serialise_object_list_from_bytes(bytes_data: bytes
) -> Iterable["Serialise"]:
'''
Loads the serialise objects from the given bytestring and return them.
This is the inverse of function of
:func:`serialise_object_list_to_bytes`.
# Parameters
bytes_data : `bytes`
The bytestring to load.
# Returns
`Iterable[Serialise]`
'''
serialised_objects: List[bytes] = srsly.msgpack_loads(bytes_data)
serialise_objects: List[Serialise] = []
for serialised_object in serialised_objects:
serialise_object \
= Serialise.serialise_object_from_bytes(serialised_object)
serialise_objects.append(serialise_object)
return serialise_objects
|
10a459235ea2ee698db65431d14423e2373f8da3 | nightstrawberry/Python_Learning | /quiz/004.py | 395 | 3.9375 | 4 | print('-------------Ұc--------------')
temp = input("һСĸ:\n")
guess = int(temp)
if guess == 8:
print("ԲۣС𣿣")
print("ߣҲûн")
elif guess > 8:
print("磬˴ˣ")
else:
print('磬СС~~')
print("Ϸ~")
|
260847451d42fb41ad8613bddc69b48dd9acf4e1 | EdieM/Practice | /app_factorial.py | 752 | 4 | 4 |
# Write a method that takes an integer `n` in; it should return
# n*(n-1)*(n-2)*...*2*1. Assume n >= 0.
#
# As a special case, `factorial(0) == 1`.
#
# Difficulty: easy.
n = raw_input("Give me a number, please: ")
int_n = int(n)
def factorial(int_n):
if int_n == 0:
return 1
else:
return int_n * factorial(int_n - 1)
print "The factorial of %d is %d. " % (int_n, factorial(int_n))
#These are tests to check that code is working. should all print True
print 'factorial(0) == 1: ' + str(factorial(0) == 1)
print 'factorial(1) == 1: ' + str(factorial(1) == 1)
print 'factorial(2) == 2: ' + str(factorial(2) == 2)
print 'factorial(3) == 6: ' + str(factorial(3) == 6)
print 'factorial(4) == 24: ' + str(factorial(4) == 24)
print "_" * 40
|
3d34118d8ac2ef61449c1ff694a5b2abab2ea328 | laranea/FinancialEngineering | /Project3_OptionHedging/american-call_binomial.py | 17,116 | 3.578125 | 4 | """
Financial Engineering Project 3: Option Hedging
This program calculates the American Call premium using Binomial Tree Pricing Model
It also compares the convergence in the Binomial Tree Model to the Black Scholes
Model.
@authors: Muhammad Shahraiz Niazi and Shuto Araki
@professor: Dr. Zhixin Wu
@date: 05/12/2018
========== GLOBAL VARIABLES ==========
** Dictionary is a data structure that connects key and value pair.
All dictionaries in this project contains dates as keys. **
call_prices:
A dictionary of call prices
sigma_list:
A dictionary of implied volatilities
stock_prices:
A dictionary of stock prices
"""
# Import Dependencies
import numpy as np
from scipy.stats import norm
import math
import matplotlib.pyplot as plt
def binomial_tree_call(N = 5, T = 33/252, S0 = 52.39, sigma = 0.3746345, r = 0.0218, K = 52.5, q = 0.0225):
"""
This function displays two binomial trees: a stock price movement and calculated
option value at each node. At the end, it also displays the final value of
option and delta. By default, all the arguments are assigned from the data
at the beginning of the hedging period.
Args:
N: The number of steps in the binomial tree
T: Time to maturity (annualized)
S0: Initial stock price
sigma: Volatility (annualized)
r: Risk-free interest rate
K: Strike price of the call option
q: Dividend yield rate
Returns:
Nothing
"""
#initialize
dt = T/N
u = np.exp(sigma*np.sqrt(dt))
d = 1/u
p = (np.exp((r-q)*dt)-d)/(u-d)
# Price Tree
price_tree = np.zeros([N+1,N+1])
#Option Tree
option = np.zeros([N+1,N+1])
for i in range(N+1):
for j in range(i+1):
price_tree[j,i] = S0*(d**j)*(u**(i-j))
#Option values
option = np.zeros([N+1,N+1])
option[:,N] = np.maximum(np.zeros(N+1), price_tree[:,N]-K)
for i in np.arange(N-1,-1,-1):
for j in np.arange(0,i+1):
option[j,i] =np.maximum(np.exp(-r*dt)*(p*option[j,i+1]+(1-p)*option[j+1,i+1]), price_tree[j,i]-K)
for i in range(N+1):
print("At t =", round(i*dt, 3))
for j in range(i+1):
print(end=' ')
if(price_tree[j,i]!=0):
print(round(price_tree[j,i], 2), end=' ',)
print()
for j in range(i+1):
print("({0:.2f})".format(option[j,i]), end=' ')
print('\n')
print("The final value of option is at t = 0:", round(option[0,0], 2))
delta = (option[0,1] - option[1,1]) / (price_tree[0,1] - price_tree[1,1])
print("Delta:", round(delta, 5))
def call_option_price(N = 200, T = 33/252, S0 = 52.39, sigma = 0.3746345, r = 0.0218, K = 52.5, q = 0.0225, delta=False):
"""
This function returns the call option premium. If specified, it returns
delta.
Args:
N: The number of steps in the binomial tree
T: Time to maturity (annualized)
S0: Initial stock price
sigma: Volatility (annualized)
r: Risk-free interest rate
K: Strike price of the call option
q: Dividend yield rate
delta: If True, the function returns the delta value.
Returns:
float: option at t = 0 if delta is False
float: delta value at t = 0 if delta is True
"""
#Dividend yield rate subtraction
# initialize
dt = T/N
u = np.exp(sigma*np.sqrt(dt))
d = 1/u
p = (np.exp((r-q)*dt)-d)/(u-d)
# Price Tree
price_tree = np.zeros([N+1,N+1])
for i in range(N+1):
for j in range(i+1):
price_tree[j,i] = S0*(d**j)*(u**(i-j))
#Option values
option = np.zeros([N+1,N+1])
option[:,N] = np.maximum(np.zeros(N+1), price_tree[:,N]-K)
for i in np.arange(N-1,-1,-1):
for j in np.arange(0,i+1):
option[j,i] =np.maximum(np.exp(-r*dt)*(p*option[j,i+1]+(1-p)*option[j+1,i+1]), price_tree[j,i]-K)
if delta:
return (option[0,1] - option[1,1]) / (price_tree[0,1] - price_tree[1,1])
return option[0,0]
def approxBlackScholes(start = 3, end = 1000, step = 50):
"""
This function displays how the Binomial Tree Model converges to a certain
value as the number of steps in the tree increases.
Args:
start: starting number of steps in int
end: ending number of steps in int
step: how many steps it skips from one calculation to another
Returns:
Nothing
"""
for n in range(start, end, step):
print("N =", n, ":", call_option_price(N = n))
def exactBlackScholes(T = 33/252, S0 = 52.39, sigma = 0.3746345, r = 0.0218, K = 52.5, q = 0.0225):
"""
This function calculates the exact value of call option premium assuming
that it is an European option.
Args:
T: Time to maturity (annualized)
S0: Initial stock price
sigma: Volatility (annualized)
r: Risk-free interest rate
K: Strike price of the call option
q: Dividend yield rate
Returns:
Tuple of floats: call and put option premium at t = 0
"""
d1 = (math.log(S0 / K) + (r - q + sigma**2 / 2) * T) / (sigma * math.sqrt(T))
d2 = d1 - sigma*math.sqrt(T)
e = math.e
c = S0 * e**(-q*T) * norm.cdf(d1) - K * e**(-r*T) * norm.cdf(d2)
p = K * e**(-r*T) * norm.cdf(-d2) - S0 * e**(-q*T) * norm.cdf(-d1)
return c, p
def displayBlackScholes(T = 33/252, S0 = 52.39, sigma = 0.3746345, r = 0.0218, K = 52.5, q=0):
"""
This function calculates the call and put option premium at t = 0 and
displays the results.
Args:
T: Time to maturity (annualized)
S0: Initial stock price
sigma: Volatility (annualized)
r: Risk-free interest rate
K: Strike price of the call option
q: Dividend yield rate
Returns:
Nothing
"""
c, p = exactBlackScholes(T, S0, sigma, r, K, q)
print("c =", c)
print("p =", p)
def plotOptionPrices(start = 1, end = 200, step = 1):
"""
This function displays a graph that shows how the Binomial Tree Model
converges to the Black-Scholes Model as the number of steps in the tree
increases.
Args:
start: starting number of steps in int
end: ending number of steps in int
step: how many steps it skips from one calculation to another
Returns:
Nothing
"""
callPriceList = []
c, p = exactBlackScholes()
for n in range(start, end, step):
callPriceList.append(call_option_price(N = n))
plt.plot(list(range(start, end, step)), callPriceList, label = "Binomial Tree")
plt.plot([start, end], [c, c], '--', color='r', label = "Black Scholes")
plt.xlabel("Number of Steps in Binomial Tree")
plt.ylabel("Call Option Price")
plt.title("The Binomial Tree Model approximates the Black Scholes Model")
plt.legend(loc="upper right", shadow=True, fancybox=True)
plt.show()
# Call Option Prices During the Hedging Period
# INTC call maturity on 06/15/2018
call_prices = {"05/01/2018": 2.08,
"05/02/2018": 2.13,
"05/03/2018": 1.80,
"05/04/2018": 2.08,
"05/07/2018": 2.45,
"05/08/2018": 2.42,
"05/09/2018": 2.81,
"05/10/2018": 3.06,
"05/11/2018": 3.04
}
# Implied Volatility During the Hedging Period
sigma_list = { "05/01/2018": 0.2832,
"05/02/2018": 0.2838,
"05/03/2018": 0.2821,
"05/04/2018": 0.2796,
"05/07/2018": 0.2759,
"05/08/2018": 0.2972,
"05/09/2018": 0.2741,
"05/10/2018": 0.2801,
"05/11/2018": 0.2700
}
# Stock Prices During the Hedging Period
stock_prices = { "05/01/2018": 52.39,
"05/02/2018": 52.54,
"05/03/2018": 51.97,
"05/04/2018": 52.63,
"05/07/2018": 53.40,
"05/08/2018": 53.15,
"05/09/2018": 54.11,
"05/10/2018": 54.48,
"05/11/2018": 54.59
}
def dynamicDeltaHedgingSimulation(historicalSigma = False):
"""
This function simulates the dynamic delta hedging using INTC (Intel Corp.)
stocks and calls. The hedging period was 05/01/2018 to 05/11/2018.
The position was changed every business day.
Args:
historicalSigma: boolean value that chooses whether to use historical
volatility or implied volatility
Returns:
Nothing
"""
# Replace the implied volatility values with historical ones.
if historicalSigma:
print("USING HISTORICAL VOLATILITY\n")
# A list of delta values
delta_list = [
call_option_price(N=33, T=33/252, S0=stock_prices["05/01/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=32/252, S0=stock_prices["05/02/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=31/252, S0=stock_prices["05/03/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=30/252, S0=stock_prices["05/04/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=29/252, S0=stock_prices["05/07/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=28/252, S0=stock_prices["05/08/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=27/252, S0=stock_prices["05/09/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=26/252, S0=stock_prices["05/10/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=25/252, S0=stock_prices["05/11/2018"], sigma=0.3746345, delta=True)
]
else:
print("USING IMPLIED VOLATILITY\n")
delta_list = [
call_option_price(N=33, T=33/252, S0=stock_prices["05/01/2018"], sigma=sigma_list["05/01/2018"], delta=True),
call_option_price(N=33, T=32/252, S0=stock_prices["05/02/2018"], sigma=sigma_list["05/02/2018"], delta=True),
call_option_price(N=33, T=31/252, S0=stock_prices["05/03/2018"], sigma=sigma_list["05/03/2018"], delta=True),
call_option_price(N=33, T=30/252, S0=stock_prices["05/04/2018"], sigma=sigma_list["05/04/2018"], delta=True),
call_option_price(N=33, T=29/252, S0=stock_prices["05/07/2018"], sigma=sigma_list["05/07/2018"], delta=True),
call_option_price(N=33, T=28/252, S0=stock_prices["05/08/2018"], sigma=sigma_list["05/08/2018"], delta=True),
call_option_price(N=33, T=27/252, S0=stock_prices["05/09/2018"], sigma=sigma_list["05/09/2018"], delta=True),
call_option_price(N=33, T=26/252, S0=stock_prices["05/10/2018"], sigma=sigma_list["05/10/2018"], delta=True),
call_option_price(N=33, T=25/252, S0=stock_prices["05/11/2018"], sigma=sigma_list["05/11/2018"], delta=True)
]
portfolio = 100000
print("Stock: INTC")
print("Initial Porfolio Value:", portfolio)
print()
print("================================")
print("05/01/2018")
print("\tPortfolio Value:", portfolio)
print("\tShort 5 Calls")
print("\tDelta =", delta_list[0])
numOfStock = round(delta_list[0] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/02/2018")
portfolio = 100000 + (stock_prices["05/02/2018"] - stock_prices["05/01/2018"]) * numOfStock - (call_prices["05/02/2018"] - call_prices["05/01/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[1])
numOfStock = round(delta_list[1] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/03/2018")
portfolio = 100000 + (stock_prices["05/03/2018"] - stock_prices["05/02/2018"]) * numOfStock - (call_prices["05/03/2018"] - call_prices["05/02/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[2])
numOfStock = round(delta_list[2] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/04/2018")
portfolio = 100000 + (stock_prices["05/04/2018"] - stock_prices["05/03/2018"]) * numOfStock - (call_prices["05/04/2018"] - call_prices["05/03/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[3])
numOfStock = round(delta_list[3] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/07/2018")
portfolio = 100000 + (stock_prices["05/07/2018"] - stock_prices["05/04/2018"]) * numOfStock - (call_prices["05/07/2018"] - call_prices["05/04/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[4])
numOfStock = round(delta_list[4] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/08/2018")
portfolio = 100000 + (stock_prices["05/08/2018"] - stock_prices["05/07/2018"]) * numOfStock - (call_prices["05/08/2018"] - call_prices["05/07/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[5])
numOfStock = round(delta_list[5] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/09/2018")
portfolio = 100000 + (stock_prices["05/09/2018"] - stock_prices["05/08/2018"]) * numOfStock - (call_prices["05/09/2018"] - call_prices["05/08/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[6])
numOfStock = round(delta_list[6] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/10/2018")
portfolio = 100000 + (stock_prices["05/10/2018"] - stock_prices["05/09/2018"]) * numOfStock - (call_prices["05/10/2018"] - call_prices["05/09/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[7])
numOfStock = round(delta_list[7] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/11/2018")
portfolio = 100000 + (stock_prices["05/11/2018"] - stock_prices["05/10/2018"]) * numOfStock - (call_prices["05/11/2018"] - call_prices["05/10/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[8])
numOfStock = round(delta_list[8] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("IF NOT HEDGED, portfolio value would have been", 100000 - (call_prices["05/11/2018"] - call_prices["05/01/2018"]) * 500)
def staticDeltaHedgingSimulation(historicalSigma=False):
"""
This function simulates the static delta hedging using INTC (Intel Corp.)
stocks and calls. The hedging period was 05/01/2018 to 05/11/2018.
The position was changed once at the beginning.
"""
# Replace the implied volatility values with historical ones.
if historicalSigma:
print("USING HISTORICAL VOLATILITY\n")
# A list of delta values
delta_list = [
call_option_price(N=33, T=33/252, S0=stock_prices["05/01/2018"], sigma=0.3746345, delta=True),
call_option_price(N=33, T=25/252, S0=stock_prices["05/11/2018"], sigma=0.3746345, delta=True)
]
else:
print("USING IMPLIED VOLATILITY\n")
delta_list = [
call_option_price(N=33, T=33/252, S0=stock_prices["05/01/2018"], sigma=sigma_list["05/01/2018"], delta=True),
call_option_price(N=33, T=25/252, S0=stock_prices["05/11/2018"], sigma=sigma_list["05/11/2018"], delta=True)
]
portfolio = 100000
print("Stock: INTC")
print("Initial Porfolio Value:", portfolio)
print()
print("================================")
print("05/01/2018")
print("\tPortfolio Value:", portfolio)
print("\tShort 5 Calls")
print("\tDelta =", delta_list[0])
numOfStock = round(delta_list[0] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("================================")
print("05/11/2018")
portfolio = 100000 + (stock_prices["05/11/2018"] - stock_prices["05/01/2018"]) * numOfStock - (call_prices["05/11/2018"] - call_prices["05/01/2018"]) * 500
print("\tPortfolio Value:", portfolio)
print("\tDelta =", delta_list[1])
numOfStock = round(delta_list[1] * 500)
print("\tHold", numOfStock, "stocks")
print()
print("IF NOT HEDGED, portfolio value would have been", 100000 - (call_prices["05/11/2018"] - call_prices["05/01/2018"]) * 500)
|
d4d194d4e43455944a8cf029fbdfb1412d511482 | jkurambhatti/jayeshPythonProjects | /FlaskProjects/FlaskProjects.py | 1,899 | 3.96875 | 4 | '''
we will be learning how to create a webpage with simple 'hello world'
we will be creating different webpages
using variables (strings, integers)
'''
from flask import Flask, request, render_template
import Image
app = Flask(__name__)
@app.route('/') # specifies route to the root directory '/' means 'root'
def hello_world():
return 'Hello World!'
@app.route('/name') # specifies route to the name directory
def name():
return '<h1> Jayesh Kurambhatti</h1>'
@app.route('/contact_no') # specifies route to the contact directory
def contact():
return '''<h1> 9916567478 8088286577</h1>
<h2>address : <h3>bangalore</h3></h2>
<h3> locality</h3> : btm
'''
# for using a variable you should enter the var name in <> ,eg : <about>, <var2>, <train>, etc
# also the url is always in '' or "", so see the example below
@app.route('/friend/<user>') # demo of using a string
def call(user):
return 'hey there %s' % user
@app.route("/post/<int:post_id>") # demo of int var mention the datatype inside <>
def print_postid(post_id):
return "the post-id is %s" % post_id
@app.route('/tea')
def print_tea():
img = Image.open("cup.jpg",'r')
return img
# whenever you request for a url or webpage or anything, the HTTP GET method is used
# when you are filling a form then we use HTTP POST method to POST info.
@app.route('/method')
def which_m():
return "the method used is %s " % request.method
# write function for calling html file using render_template library
@app.route('/homepage/<uname>')
def home(uname):
return render_template("index.html",name = uname) # copy the uname into variable name of render_templaate()
if __name__ == '__main__': # its kind of like main() file always run the app from this file
app.run() # starts the server
|
360697b1bd232d78014cbce560225c294a8de181 | CXuTao/Python_source | /python_grammar/tkinter/3.button.py | 576 | 3.734375 | 4 | import tkinter
def func():
print("xt is a good man")
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title("哈哈哈")
#设置大小和位置
win.geometry("400x400+200+20")
#进入消息循环
#创建按钮
button1 = tkinter.Button(win, text="按钮", command=func,
width=10, height=10)
button1.pack()
button2 = tkinter.Button(win, text="按钮", command=lambda :print("xt is a good man"))
button2.pack()
button3 = tkinter.Button(win, text="按钮", command=win.quit)
button3.pack()
win.mainloop() |
6bd01ed3670fac703a569c11dda753447430989d | AnandManwani/Python-Codes | /python_IF_Else.py | 635 | 4.3125 | 4 | #!/bin/python3
#Given an integer, , perform the following conditional actions:
#If n is odd, print Weird
#If n is even and in the inclusive range of 2 to 5 , print Not Weird
#If n is even and in the inclusive range of 6 to 20 , print Weird
#If n is even and greater than 20 , print Not Weird
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if (n % 2 != 0):
print ("Weird")
elif (n % 2 == 0 ) and (n in range(2, 5)):
print ("Not Weird")
elif (n % 2 == 0) and (n in range(6, 21)):
print ("Weird")
else:
print ("Not Weird")
|
71927bcbecd21dc47e4b205af5a7d5618d94c2ad | chenyaoling/python-study2 | /day09/01-re模块的使用.py | 748 | 3.609375 | 4 | """
1、导入模块
2、通过 match 方法,验证正则
3、判断 验证是否成功
4、如果成功,获取匹配的结果
"""
# 1、导入模块
import re
# 2、通过 match 方法,验证正则
# re.match("正则表达式", "要验证/检测的字符串")
# match() 方法如果匹配成功,返回 match object 对象
# match() 方法如果匹配失败,返回 None
# 正则字符串 要检测的内容
result = re.match("\w{4,20}@163\.com$", "hello@163.com")
# 3、判断 验证是否成功
if result:
print("匹配成功!")
# 4、如果成功,获取匹配的结果
print("匹配结果:", result.group())
print(result.start())
print(result.end())
print(result.span())
else:
print("匹配失败!")
|
5125555a282ea422dd2eb2b4721ff62782d93b37 | multifacet/0sim-plotting-scripts | /plot-meminfo.py | 685 | 3.53125 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
from sys import argv, exit
"""
Usage: ./plot Field label:file ...
"""
field = argv[1]
# {label: [values]}
data = {}
for a in argv[2:]:
label, fname = a.split(':')
fdata = []
with open(fname, 'r') as f:
for line in f.readlines():
parts = line.strip().split()
if parts[0] == field:
val = int(parts[1])
fdata.append(val)
else:
print("doesn't match: %s" % parts)
data[label] = fdata
for label in data:
plt.plot(data[label], label=label, marker='o')
plt.grid(True)
plt.legend()
plt.show()
|
d645f28fe08025513d9f3dbec1e4147bdc539c8d | GODKIMCHI142/bit_seoul | /Study/keras/keras25_split_1112.py | 1,857 | 3.640625 | 4 | # 이 소스를 분석하시오
# 넘파이를 선언하기 위해 임포트함
import numpy as np
# 데이터 준비
dataset = np.array(range(1,11)) # 1~10
size = 5 # 원하는 열의 길이
print("dataset : >>> \n",dataset) # [ 1 2 3 4 5 6 7 8 9 10]
print("len(dataset) : >>> \n",len(dataset)) # 10
def split_x(seq, size): # 함수선언
aaa = [] # 빈 리스트를 만듬
for i in range(len(seq) - size +1): # for문이 도는 횟수는 dataset의 길이 - 열의 길이 + 1
subset = seq[i : (i+size)] # 인덱스 i ~ i+5까지 리스트로 뽑고 1만큼 순차적으로 증가한다
aaa.append([item for item in subset]) # subset안에서 가져온 데이터를 aaa에 넣는다
print("type(aaa) : >>> \n",type(aaa)) # aaa의 타입을 출력해본다.
return np.array(aaa) # aaa를 numpy.ndarray 타입으로 바꾼다.
datasets = split_x(dataset, size) # 함수를 호출하고 dataset과 size를 넘겨준뒤 새로운 리스트를 리턴받는다.
print("=================")
print("datasets : >>>> \n",datasets)
print("type(datasets) : >>>> \n",type(datasets))
# x_len = x.__len__()
# print("x.__len__() : ",x.__len__())
# new_x = []
# np.array(new_x)
# for i in range(x[1,].size):
# # print("s",x[1,].size)
# # new_x += [x[0,i],x[1,i],x[2,i]]
# # on = np.array(x[0,i])
# # tw = np.array(x[1,i])
# # th = np.array(x[2,i])
# # new_x = np.append(new_x,[on],axis=0)
# # new_x = np.append(new_x,[tw],axis=0)
# # new_x = np.append(new_x,[th],axis=0)
# new_x.append([x[0,i],x[1,i],x[2,i]])
# new_x = np.array(new_x)
# print(new_x)
# print("new_x.shape >>> ",new_x.shape)
|
269989ec2a9fd72a572014a3a04718b09ca5a364 | mdengler/alienhome | /bin/csvvert.py | 1,287 | 4.25 | 4 | #!/usr/bin/env python
"""
Displays a CSV file's contents vertically.
Example:
$ cat | ~/bin/csvvert.py
Year,Make,Model,Length
1981,Ford,Capri Ghia,2.34
1986,Ford,Reliant Regal,2.34
1990,Ford,Sierra RS Cosworth,2.38
Year: 1981
Make: Ford
Model: Capri Ghia
Length: 2.34
Year: 1986
Make: Ford
Model: Reliant Regal
Length: 2.34
Year: 1990
Make: Ford
Model: Sierra RS Cosworth
Length: 2.38
"""
import csv
import os
import sys
def get_fields_reader(csv_lines):
fields = list(csv.reader(csv_lines[0:1]))[0]
csvreader = csv.DictReader(csv_lines)
return fields, csvreader
def print_vertically(csv_lines):
fields, csvreader = get_fields_reader(csv_lines)
max_fieldname_length = max([len(f) for f in fields])
lineformat = "%%%is: %%s%%s" % max_fieldname_length
for row in csvreader:
for field in fields:
sys.stdout.write(lineformat % (field, row[field], os.linesep))
sys.stdout.write(os.linesep)
if __name__ == "__main__":
if len(sys.argv) <= 1:
print_vertically(sys.stdin.readlines())
else:
for filename in sys.argv[1:]:
if filename == "-":
fh = sys.stdin
else:
fh = open(filename)
print_vertically(fh.readlines())
|
af7dcacbf8d6aa208a0c5a4f3a98ef918390a206 | caiotorrez/URI | /Ad-Hoc (URI)/Og.py | 166 | 3.671875 | 4 | while True:
numeros = raw_input()
n1 = int(numeros[0])
n2 = int(numeros[2])
if n1 == 0 and n2 == 0:
break
else:
print n1+n2
|
34f0948470106ba9d06197d811882215e5b4a257 | heyheycel/advent-of-code | /2018/code_day2.py | 929 | 3.59375 | 4 |
instructions = []
with open('input_day2.txt') as f:
for line in f:
instructions.append(line.strip())
def numberOfTwo(letters):
for i in letters.values():
if i ==2:
return 1
return 0
def numberOfThree(letters):
for i in letters.values():
if i ==3:
return 1
return 0
twos=0
threes=0
for line in instructions:
letter_count={}
for letter in line:
if letter in letter_count:
letter_count[letter]+=1
else:
letter_count[letter]=1
twos+=numberOfTwo(letter_count)
threes+=numberOfThree(letter_count)
print(twos)
print(threes)
print("Part 1: "+str(twos*threes))
for word1 in instructions:
for word2 in instructions:
diff = 0
for i in range(len(word1)):
if word1[i] != word2[i]:
diff += 1
if diff>1:
break;
if diff == 1:
ans = []
for i in range(len(word1)):
if word1[i] == word2[i]:
ans.append(word1[i])
print (''.join(ans))
print (word1,word2) |
f12e7b22722590c1c7373714de385d7178ae283b | zhjr2019/PythonWork | /01_Python_Basis/Python_BFW/02_作业/第03章 字符串处理/assignment_01.py | 1,019 | 3.9375 | 4 | """
1.上机题
分别使用加法、减法、乘法和除法编写四个表达式,使用print语句输出结果
要求:使用变量接收输入的数字用于计算
"""
if __name__ == '__main__':
while True:
num1 = input("请输入一个数:")
num2 = input("请输入再一个数:")
if num1.isdigit() and num2.isdigit():
num1 = int(num1)
num2 = int(num2)
print("{0} + {1} = {2}".format(num1, num2, num1 + num2)) # 两数相加,并输出结果
print("{0} - {1} = {2}".format(num1, num2, num1 - num2)) # 两数相减,并输出结果
print("{0} * {1} = {2}".format(num1, num2, num1 * num2)) # 两数相乘,并输出结果
while num2 == 0: # 判断除数是否为零
num2 = int(input("请重新输入一个不为0的除数:")) # 两数相除,并输出结果
print("{0} / {1} = {2}".format(num1, num2, num1 / num2))
else:
print("请输入数字!") |
32e7740d64e5c987ab1ea353f449c6c280805ebd | Suzanna-Neely-Yates/ConnectFourAI | /ConnectFourAI.py | 10,228 | 3.78125 | 4 | # Suzanna (Neely) Yates
#
# Class: Board
# -- Variable: Data storing the two-dimensional array (LoL), which is the game board.
# -- Variable: Height storing the number of rows on the game board.
# -- Variable: Width storing the number of columns on the game board.
#
# Data Members: Two-Dimensional List (LoL)
# -- contains charactures to represent the game area
# -- pair of variables holding the number of rows and columns on the board (6 rows and 7 columns - standard)
import random
"""
Inarow functions outside the class.
"""
def inarow_Neast(ch, r_start, c_start, A, N):
"""Starting from (row, col) of (r_start, c_start)
within the 2d list-of-lists A (array),
returns True if there are N ch's in a row
heading east and returns False otherwise.
"""
H = len(A)
W = len(A[0])
if r_start < 0 or r_start > H - 1:
return False # out of bounds row
if c_start < 0 or c_start + (N-1) > W - 1:
return False # out of bounds col
# loop over each location _offset_ i
for i in range(N):
if A[r_start][c_start+i] != ch: # a mismatch!
return False
return True # all offsets succeeded, so we return True
def inarow_Nsouth(ch, r_start, c_start, A, N):
"""Starting from (row, col) of (r_start, c_start)
within the 2d list-of-lists A (array),
returns True if there are N ch's in a row
heading south and returns False otherwise.
"""
H = len(A)
W = len(A[0])
if r_start < 0 or r_start + (N-1) > H - 1:
return False # out of bounds row
if c_start < 0 or c_start > W - 1:
return False # out of bounds col
# loop over each location _offset_ i
for i in range(N):
if A[r_start+i][c_start] != ch: # a mismatch!
return False
return True # all offsets succeeded, so we return True
def inarow_Nnortheast(ch, r_start, c_start, A, N):
"""Starting from (row, col) of (r_start, c_start)
within the 2d list-of-lists A (array),
returns True if there are N ch's in a row
heading northeast and returns False otherwise.
"""
H = len(A)
W = len(A[0])
if r_start - (N-1) < 0 or r_start > H - 1:
return False # out of bounds row
if c_start < 0 or c_start + (N-1) > W - 1:
return False # out of bounds
# loop over each location _offset_ i
for i in range(N):
if A[r_start-i][c_start+i] != ch: # a mismatch!
return False
return True # all offsets succeeded, so we return True
def inarow_Nsoutheast(ch, r_start, c_start, A, N):
"""Starting from (row, col) of (r_start, c_start)
within the 2d list-of-lists A (array),
returns True if there are N ch's in a row
heading southeast and returns False otherwise.
"""
H = len(A)
W = len(A[0])
if r_start < 0 or r_start + (N-1) > H - 1:
return False # out of bounds row
if c_start < 0 or c_start + (N-1) > W - 1:
return False # out of bounds col
# loop over each location _offset_ i
for i in range(N):
if A[r_start+i][c_start+i] != ch: # a mismatch!
return False
return True # all offsets succeeded, so we return True
class Board:
"""A data type representing a Connect-4 board
with an arbitrary number of rows and columns.
"""
def __init__(self, width, height):
"""Construct objects of type Board, with the given width and height."""
self.width = width
self.height = height
self.data = [[' ']*width for row in range(height)]
def __repr__(self):
"""This method returns a string representation
for an object of type Board.
"""
s = '' # the string to return
for row in range(0, self.height):
s += '|'
for col in range(0, self.width):
s += self.data[row][col] + '|'
s += '\n'
s += (2*self.width + 1) * '-' # bottom of the board
s += '\n' # and the numbers underneath here
for col in range(0, self.width):
s += " " + str(col%10)
return s # the board is complete, return it
def addMove(self, col, ox):
"""
Inputs self, col and ox.
Outputs the adding of the move. Placing it on the board.
"""
H = self.height
for row in range(0,H):
if self.data[row][col] != " ":
self.data[row-1][col] = ox
return
self.data[H-1][col] = ox
def clear(self):
"""
Inputs self.
Outputs the cleared chart.
"""
H = self.height
W = self.width
for row in range(0, H):
for col in range(0, W):
self.data[row][col] = " "
return
def setBoard(self, moveString):
"""Accepts a string of columns and places
alternating checkers in those columns,
starting with 'X'.
For example, call board.setBoard('012345')
to see 'X's and 'O's alternate on the
bottom row, or board.setBoard('000000') to
see them alternate in the left column.
moveString must be a string of one-digit integers.
"""
nextChecker = '🔴' # start by playing 'X'
for colChar in moveString:
col = int(colChar)
if 0 <= col <= self.width:
self.addMove(col, nextChecker)
if nextChecker == '🔴':
nextChecker = '🔵'
else:
nextChecker = '🔴'
def allowsMove (self, col):
"""
True if col is in-bounds and open.
False otherwise.
"""
H = self.height
W = self.width
D = self.data
if col >= W or col < 0:
return False
elif D[0][col] != " ":
return False
else:
return True
def isFull(self):
"""
Inputs self and outputs if the chart is full:
True or False.
"""
H = self.height
W = self.width
D = self.data
for col in range(W):
if D[0][col]== " ":
return False
return True
def delMove(self, col):
"""
Inputs self and col.
Outputs a deleted move.
"""
H = self.height
for row in range(0,H):
if self.data[row][col] != " ":
self.data[row][col] = " "
return
def winsFor(self, ox):
"""
Inputs self and ox.
Outputs if ox wins.
"""
H = self.height
W = self.width
D = self.data
for row in range(H):
for col in range(W):
if inarow_Neast(ox, row, col, self.data, 4) == True:
return True
elif inarow_Nsouth(ox, row, col, self.data, 4) == True:
return True
elif inarow_Nnortheast(ox, row, col, self.data, 4) == True:
return True
elif inarow_Nsoutheast(ox, row, col, self.data, 4) == True:
return True
else:
return False
def hostGame(self):
"""
Inputs self.
Outputs the game a user can play.
"""
print ("Welcome to Connect Four!")
width = self.width
height = self.height
#board = Board(width, height)
print (self)
playing = True
while playing == True:
xusers_col = -1
while not self.allowsMove(xusers_col):
xusers_col = int(input("🔴 , choose a column: "))
self.addMove(xusers_col, "🔴")
print(self)
if self.winsFor("🔴") == True:
print ("Congrats. You won!")
playing = False
break
elif self.isFull() == True:
print ("Board is full.")
playing = False
break
ousers_col = -1
while not self.allowsMove(ousers_col):
choice = self.aiMove("🔵")
ousers_col = choice #int(input("O, choose a column: "))
self.addMove(ousers_col, "🔵")
print(self)
if self.winsFor("🔵") == True:
print ("Sorry. You lost!")
playing = False
break
elif self.isFull() == True:
print ("Board is full.")
playing = False
break
def colsToWin(self, ox):
"""
Inputs self, ox.
Outputs a list of columns where the player can win.
"""
list_wins = []
for a in range(self.width): #column in board
if self.allowsMove(a) == True:
trial = self.addMove(a, ox)
if self.winsFor(ox) == True:
list_wins.append(a)
self.delMove(a)
return list_wins #return list of columns where ox move to win
def aiMove(self, ox):
"""
Inputs o or x.
Outputs the column the computer chooses.
"""
list_wins = self.colsToWin(ox)
switch = self.switchatob(ox)
list_lose = self.colsToWin(switch)
if len(list_wins) != 0: #if computer can win
return list_wins[0]
#self.addMove(list_wins[0], ox)
elif len(list_lose) != 0: #if computer cannot win
return list_lose[0]
#self.addMove(list_lose[0], ox )#block opponent
else: #if no way for ox to win nor way to block ox
random_move = random.randrange(self.width)
while not self.allowsMove(random_move):
random_move = random.randrange(self.width)
return random_move
#self.addMove(random_move, ox)
def switchatob (self, ox):
"""
Helper function for aiMove.
Inputs x or o.
Outputs the opposite letter.
"""
if ox == "X" or ox == "x" or ox == "🔴":
return "🔵"
elif ox == "O" or ox == "o" or ox == "🔵":
return "🔴" |
b4326008dfbf414566638271c830ed6ce3d6c418 | BaijingML/leetcode | /kuaishou2019_zifuchuanpaixu.py | 374 | 3.765625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: python3.6
@Author : Zhangfusheng
@Time : 2019/9/24 21:30
@File : kuaishou2019_zifuchuanpaixu
@Software: PyCharm
"""
if __name__ == '__main__':
n = int(input())
nums = []
for i in range(n):
temp = input()[-6:]
nums.append(int(temp))
nums.sort()
for i in nums:
print(i)
|
cd075e1574216d7b315fba45e6973a5ab2ae8e58 | Razdeep/PythonSnippets | /NOV25/19.py | 111 | 3.6875 | 4 | # Appending data in file
fp=open('data.txt','a')
text='This is the new text appended'
fp.write(text)
fp.close() |
3aaf81c34cac99f0a6160314eaec3ee2379b1076 | vinaygaja/gaja | /miniproject1.py | 553 | 3.921875 | 4 | #miniproject 1
number=range(1,25)
loginnum=input('assume number:')
loginnum=int(loginnum)
lch=0
while lch<5:
passcode=input('guess the number:')
passcode=int(passcode)
if passcode < loginnum-2:
print("invalid passcode")
elif passcode>loginnum+2:
print("INVALLID PASSCODE")
elif passcode >= loginnum-2 and passcode < loginnum:
print("InVaLiD PaSsCoDe")
elif passcode>loginnum and passcode<=loginnum+2:
print("InVaLiD PaSsCoDe")
elif passcode==loginnum:
print("welcome")
lch+=1
|
b99fe5adeacf27681b6ca3ae7974ad8da6ef24d4 | Isabellajones71/Day1-Exercises | /dd1.py | 375 | 3.890625 | 4 | # print("Hello")
# a= 10
# b = 20
# if (a>b):
# print("{} is bigger than {}".format(a,b))
# else:
# print("{} is bigger than {}".format(b,a))
# list_data = [1, 2, 3, 4, 5]
# #
# # for m in list_data:
# # print(m * 2)
#Declare a list of 10 numbers
# have a check condition like if a<15
#If the condition is satisfied write it to another list and print the list |
3104fb65519b7ae1aed9bc3987b798d2e1cd55e1 | ASdeWekker/dotfiles | /scripts/python/codewithmosh/03/14_exercise.py | 283 | 3.90625 | 4 | """
Python code with mosh exercise
"""
def main():
""" Function """
count = 0
for x in range(1,10):
if x % 2 == 0:
print(x)
count += 1
print(f"We have {count} even numbers")
if __name__ == "__main__":
main()
|
69521437ffd692f6ed3cb733e7fc9ff27fcf2a36 | dr-aheydari/novosparc | /novosparc/geometry/_geometry.py | 1,019 | 3.5625 | 4 | from __future__ import print_function
###########
# imports #
###########
import numpy as np
#############
# functions #
#############
def construct_target_grid(num_cells):
"""Constructs a rectangular grid. First a grid resolution is randomly
chosen. grid_resolution equal to 1 implies equal number of cells and
locations on the grid. The random parameter beta controls how rectangular
the grid will be -- beta=1 constructs a square rectangle.
num_cells -- the number of cells in the single-cell data."""
grid_resolution = int(np.random.randint(1, 2+(num_cells/1000), 1))
grid_resolution = 2
num_locations = len(range(0, num_cells, grid_resolution))
grid_dim = int(np.ceil(np.sqrt(num_locations)))
beta = round(np.random.uniform(1, 1.5), 1) # controls how rectangular the grid is
# beta = 1 # set this for a square grid
x = np.arange(grid_dim * beta)
y = np.arange(grid_dim / beta)
locations = np.array([(i, j) for i in x for j in y])
return locations
|
f5e1f28fb1dedabe424cc9ab366fffee1766b8c6 | afsana1210/python-learning | /map_eg.py | 88 | 3.515625 | 4 | def square(nums):
return nums**2
my_list=[1,2,4,5]
res=map(square,my_list)
print(res) |
3dd069abf28f3c4b8ecc5455eabe528b16b05227 | PabloSMCK/ML-AZ | /Section 7 - Multiple Linear Regression/Python/multiple_linear_regression.py | 1,676 | 3.65625 | 4 | #IMPORT LIBRARIES
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#IMPORT THE DATASET
dataset = pd.read_csv("50_Startups.csv")
X = dataset.iloc[:,:-1].values #INDEPENDET VARIABLE/S
y = dataset.iloc[:,-1].values #DEPENDENT VARIABLE/S
#TAKING CARE OF THE MISSING DATA
"""from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean')
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform( X[:, 1:3])"""
#ENCODING CATEGORICAL (TRANSFORM COLUMN TEXT VALUES TO NUMBERS)
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([("Country", OneHotEncoder(), [3])], remainder = 'passthrough')
X = ct.fit_transform(X)
"""labelencoder_y = LabelEncoder() #ALTERA LA VARIABLE y
y = labelencoder_y.fit_transform(y)#ALTERA LA VARIABLE y"""
#SPLITTING THE DF TO TRAIN AND TEST
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
#FEATURE SCALLING
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)"""
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#PREDICT THE TEST SET RESULTS
y_pred = regressor.predict(X_test) #VECTOR WITH PREDICTED VALUES
np.set_printoptions(precision=2)
print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)), 1)) #CONCATENAR LOS 2 VECTORES, RESHAPE = TRANSFORMAR LOS VECTORES A LO LARGO EN COLUMNAS, LOS 1 SON LOS AXIS
|
f791b1f21ff4209d825afd56bc7f28e3846fd062 | Anishazaidi/Chatbot | /Chatbot.py | 2,441 | 4.15625 | 4 | print("Welcome to flipkart online centre")
Name=input("enter a name:")
print("hii",Name,"how can i help you")
print("What you want know about: \n 1.About flipkart founder 1 \n 2.Branches of flipkart 2 \n 3.online shopping process 3\n 4.Payback process 4\n 5.To know about materials")
Help=int(input("please ask what you want to know?"))
if Help==1:
print("sachin bansal was the founder of flipkart")
know_more=input("know more about flipkart shopping:")
if know_more=="yes":
print("flipkart is a online shopping centre which is used to save the time")
facilities=input("to know about facility enter yes")
if facilities=="yes":
print("Facilites are good!,Here the customers felt happy to do online shopping for their needs in emergency when they do not have time to do shopping")
else:
print("thanks for connecting our online shopping centre")
else:
print("thank you")
elif Help==2:
print("there are three main branches in flipkart based on ur needs")
To_know=input("to know enter yes or no")
if To_know=="yes":
print("bangalore,hyderabad,chennai")
more_to_know=input("more to know enter yes or no")
if more_to_know=="yes":
print("bangalore,chennai,and hyderabad is available to the all cities")
else:
print("thanks for connecting us")
else:
print("thank you")
elif Help==3:
print("for doing shopping in flipkart you have to clear about the 5 steps")
steps=input("steps to know enter yes or no ")
if steps=="yes":
print("first select an item,second choose colour,third clarity about payment,fourth check which type of payment is available,and fifth clarify in how many days it will delivered")
else:
print("thanks for connecting")
elif Help==4:
print("after getting flipkart service just give ur review through the ratings")
elif Help==5:
print("the quality of material is good and it is used to you when ur going to the parties")
know_about=input("enter to know about press yes or no:")
if know_about=="yes":
print(" here every item have their unique identification like quality of cloth and richness")
else:
print("thank you")
if(True):
print("thanks for connecting us")
print("if you want to know more about flipkart visit this website.http://flipkart.com") |
fc3c8b7e636f4111d8c5ddda5c0d2874958c06e2 | davidandym/wikilinks-ned | /src/data_readers/statistics_reader.py | 1,930 | 3.53125 | 4 | """ Statistics Reader - used for candidate generation.
This class is basically just a dict of mention strings and their potential wiki
candidates.
Adapted from:
https://github.com/yotam-happy/NEDforNoisyText/blob/master/src/WikilinksStatistics.py
"""
import json
import os
import numpy as np
from random import randint
base_dir = '/Users/davidmueller/data/wikilinks_NED/wikilinksNED_dataset'
class StatisticsReader(object):
""" Statistics reader - reads the ''statistics'' output of the wikilinks
creation process.
The purpose of this class is candidate generation.
"""
def __init__(self, path_to_stats):
self._path_to_stats = path_to_stats
self._load_statistics()
def _load_statistics(self):
""" Simple helper. """
data = []
if os.path.isfile(self._path_to_stats):
f = open(self._path_to_stats, 'r')
line = f.readline()
line = f.readline()
self.stats_json = json.loads(line)
entity_count_line = f.readline()
entities_count = json.loads(entity_count_line)
self.entity_ids = entities_count.keys()
else:
raise Exception("Invalid stats file: %s" % self._path_to_stats)
def get_candidates_for_mention(self, mention):
""" Get candidate entities for a given mention string. """
try:
candidates = self.stats_json[mention.lower()]
candidates = np.array(candidates.keys(), dtype=int)
return candidates
except KeyError:
return None
def get_rand_candidate_from_pool(self, gold_id):
""" Get a random candidate which is NOT equal to 'gold_id'. """
rand_id = self.entity_ids[np.random.randint(0, len(self.entity_ids))]
while int(rand_id) == int(gold_id):
rand_id = self.entity_ids[np.random.randint(0, len(self.entity_ids))]
return rand_id
|
9f6d396a5a0fd172bd400005e46e5e0af1c3ed5b | AhmedAbdelkhalek/HackerRank-Problems | /Algorithms/Warmup/Solve Me First.py | 395 | 3.796875 | 4 | #!/bin/python3
# Easy
# https://www.hackerrank.com/challenges/solve-me-first/problem
def solveMeFirst(a, b):
return a + b
# Hint: Type return a+b below
# Input the first number, convert to int
num1 = int(input())
# input the second number in a new line, convert to int
num2 = int(input())
# Call the function and print the returning number.
res = solveMeFirst(num1, num2)
print(res)
|
0201b8959410737ae1bc86896fd008b009172e72 | Shaurya-L/Data-Structures-and-Algorithms-in-Python | /Check if given tree is BST or not.py | 1,616 | 3.625 | 4 | import queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def minTree(root):
if root == None:
return 100000
leftMin = minTree(root.left)
rightMin = minTree(root.right)
return min(leftMin, rightMin, root.data)
def maxTree(root):
if root == None:
return -100000
leftMax = maxTree(root.left)
rightMax = maxTree(root.right)
return max(leftMax, rightMax, root.data)
def isBST(root):
if root == None:
return True
leftMax = maxTree(root.left)
rightMin = minTree(root.right)
if root.data > rightMin or root.data <= leftMax:
return False
isLeftBST = isBST(root.left)
isRightBST = isBST(root.right)
return isLeftBST and isRightBST
def buildLevelTree(levelorder):
index = 0
length = len(levelorder)
if length<=0 or levelorder[0]==-1:
return None
root = BinaryTreeNode(levelorder[index])
index += 1
q = queue.Queue()
q.put(root)
while not q.empty():
currentNode = q.get()
leftChild = levelorder[index]
index += 1
if leftChild != -1:
leftNode = BinaryTreeNode(leftChild)
currentNode.left =leftNode
q.put(leftNode)
rightChild = levelorder[index]
index += 1
if rightChild != -1:
rightNode = BinaryTreeNode(rightChild)
currentNode.right =rightNode
q.put(rightNode)
return root
levelOrder = [int(i) for i in input().strip().split()]
root = buildLevelTree(levelOrder)
print(isBST(root))
|
b6bf9b3a6a170a885fc2305aeb915165560ba75e | ImwaterP/learn-Python | /Python_work/逻辑运算与优先级小问题.py | 2,668 | 4.09375 | 4 | # -*- coding: utf-8 -*-
'''
逻辑运算符包含'and', 'or', 'not'
分别表示‘逻辑与’, ‘逻辑或’, ‘逻辑非’
但是我在代码中使用or的时候却遇到了问题
因此深入探究一下逻辑运算符的用法与规则
'''
#下面这段代码是我在做用 while 循环改编字典的练习时写的
responses = {}
polling_active = True
while polling_active:
name = input('What is your name? ')
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (Yes/ No) ")
if repeat == "no" or "No" :#这里为了使'no' 和 'No'都能生效,所以采用了or运算符
polling_active = False#若if为真,则标志变为False,循环中止。
print("\n---Poll Results---")
for name, response in responses.items():
print(name.title() + ' would like to climb ' + response.title() + '.')
#运行代码,我发现即便我输入了Yes,循环依然中止。
#再次运行,我发现不管我输入什么,循环都会被中止。
#我重新查阅了逻辑运算符的定义,定义如下
a = 10
b = 20
#and
#x and y 布尔"与"
#如果 x 为 False 或者 为 0 ,x and y 返回 x,否则它返回 y 的计算值。
print(a and b) #返回 20。
#or
#x or y 布尔"或"
#如果 x 是 True 或者 非0 ,它返回 x 的值,否则它返回 y 的计算值。
print(a or b) #返回 10。
#not
#not x 布尔"非"
#如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。
print(not a) #返回 False
a = 0
b = 20#改变 a 的值
print(a and b) #返回为 0
print(a or b) #返回为20
print(not a) #返回为True
#看来逻辑运算符没什么问题
#找老师看过代码之后才找到了问题的关键所在
#关键在于运算优先级
#'no' == 'no' or 'No'中 ‘==’的优先级高于‘or’所以if判断的只是‘no’ == ‘no’
#后面的or对if语句没有影响
#例如:
if 1 == 1 or 2:
print('true')
else:
print('false')
if 1 == 2 or 1:
print('true')
else:
print('false')
#不适用if语句更加直观
1 == 1
1 == 2
#再把or放入对比
1 == 2 or 1
1 == 1 or 2
#事实证明or的优先级低于‘==’
#对于字符串同样适用
'no' == 'no'
'no' == 'No'
'no' == 'no' or 'No'
'no' == 'No' or 'no'
'no' == ('No' or 'no')
'no' == ('no' or 'No')
#回到最初的问题,若我想让比较repeat与‘no’,‘No’,‘NO’三个,
#只要与三个中的任意一个相同就可以中止循环,我该怎么办呢?
#我可以创建一个列表,用‘in’ 或者 ‘not in’来实现
|
f5697f8d581ea6bf4ee42a7a8d56765a1f60ba7d | sayspeak/PycharmProjects | /test website/testjson2.py | 292 | 3.703125 | 4 | import json
input = '''
[
{"id": "007",
"x" : "2",
"name": "rongsheng"
},
{"id": "001",
"x": "4",
"name": "ssss"
}
]'''
another_info = json.loads(input)
print('count',len(another_info))
for items in another_info:
print('Name',items['name'])
print('id',items['id']) |
ba05553021d4b2df4f72c2e8ea5a357605cb39a7 | proRamLOGO/pyTokenizer | /code.py | 194 | 3.609375 | 4 | from random import *
def main() :
a = 2
b = 3
c = a + b
for i in range(3) :
if i == 3 :
print i
elif i == 2 :
print i
main()
|
10fe2bb5e4c59a29bae0da9cd7006779d54b5a81 | gingerredjade/FirsPythontPractice | /foundation/test1.py | 3,715 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Python注释: 双引号 or 三个单引号 or 一个井号
'''
'''打印操作'''
"定义打印函数"
def print_your_name(name):
print("jianghy hadoop test,your name is", name)
print("\r\t")
return "%s, is a good student." % name
# Python2.x使用如下,注意编码
# print ("jianghy hadoop test,your name is"),name.decode("utf-8")
# return ("%s, is a good student.") % name.decode("utf-8")
"调用打印函数"
print('===================')
print(print_your_name('zhangsan'))
print('===================')
print(print_your_name('李四'))
print('===================')
'''常用的数据结构'''
# Java常用数据结构:hashmap,array,set
# Python:hashmap-->dict -->{}
# Python:array-->list -->[]
# Python:set-->set -->()
# dict字典
"color是个变量,等于一个字典"
color = {"red":0.2,"green":0.4, "blue": 0.4}
print(color)
print(color['red'])
print(color['green'])
# list列表
color_list = ['red','blue','green','yellow']
print(color_list)
print(color_list[2])
# set集合
"set不能有重复元素"
a_set = set()
a_set.add('111')
a_set.add('222')
a_set.add('333')
a_set.add('111')
print(a_set)
'''条件判断语句'''
# if
a = 1
if a > 0:
print('a gt 0')
elif a == 0:
print('a eq 0')
else:
print('a lt 0')
# for 一般对于数组操作,也可对字典、集合操作
# # 创建一个列表并追加元素
a_list = []
a_list.append('111')
a_list.append('333')
a_list.append('555')
a_list.append('222')
a_list.append('444')
for value in a_list:
print(value)
##
b_dict = {}
b_dict['aaa'] = 1
b_dict['bbb'] = 2
b_dict['ddd'] = 3
b_dict['ccc'] = 4
b_dict['eee'] = 5
for value in b_dict:
"这里的value值包含字典的key,不包含其对应的value"
print(value)
for key, value in b_dict.items():
"其输出顺序并不按照存储顺序输出的。而是针对key做了一个哈希取模"
print(key + "====>" + str(value))
##
c_set = set()
c_set.add('a')
c_set.add('b')
c_set.add('c')
c_set.add('d')
c_set.add('e')
for value in c_set:
"set背后也有哈希做了操作,输出顺序并不是add顺序"
print(value)
# # 复杂一点
sum = 0
for value in range(1,11):
sum += value
print(sum)
# while
cnt = 2
while cnt > 0:
print('i love python!')
cnt -= 1
# # print dual 输出双数
"注意:Python不支持i++"
i = 1
while i < 10:
i += 1
if i % 2 > 0:
continue
print(i)
'''字符串的简单处理'''
# len()可以对字符串、字典、列表、set进行长度的计算
str = 'abcdefg'
print(len(str))
"[2:5]中的2表示从下标2开始获取,极限是5"
print(str[2:5])
# 字母大小写转换
str1 = 'AbcDEf'
print(str1)
print(str1.lower())
print(str1.upper())
'''异常处理 exception'''
# Java: try ... catch
# except Exception相当于捕捉了所有异常
try:
a = 6
b = a / 0
except Exception as e:
print (Exception, ":", e)
# 注意:2.x按照如下写
# try:
# a = 6
# b = a / 0
# except Exception, e:
# print Exception, ":", e
## IO异常
try:
print('1111')
fh = open('testfile', 'r')
print('2222')
except IOError as e:
print('3333====', e)
else:
print('4444')
fh.close()
'''import module'''
import math
# 求2的3次方
print(math.pow(2, 3))
print(math.floor(4.9))
print(round(4.9))
# 将有序数组随机化洗牌处理
import random
items = [1, 2, 3, 4, 5, 6]
random.shuffle(items)
print(items)
# 输出随机数:输出0-3之间的数字
a = random.randint(0, 3)
print(a)
# sample就是抽样,在字符串里随机抽样,要指定抽样数据的个数
s_list = random.sample('acdfg', 3)
print(s_list)
''''''
''''''
|
f6924a878c7d654d75c990500deedd6407971a4a | KDD2018/Machine-Learning | /data_structure_algorithms/double_link_list.py | 3,224 | 4 | 4 |
class Node(object):
"""节点"""
def __init__(self, elem):
self.elem = elem
self.next = None
self.prior = None
class DoubleLinkList(object):
"""双向链表"""
def __init__(self, node=None):
self.__head = node
@property
def is_empty(self):
"""链表是否为空"""
return self.__head is None
@property
def length(self):
"""链表长度"""
# 定义游标,用于遍历链表中的节点
cur = self.__head
# 初始化节点数
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历链表节点"""
cur = self.__head
while cur is not None:
print(cur.elem, end=" ")
cur = cur.next
print("")
def add(self, item):
"""链表头部添加元素"""
node = Node(item)
node.next = self.__head
self.__head.prior = node
def append(self, item):
"""链表尾部添加元素"""
node = Node(item)
if self.is_empty:
self.__head = node
else:
cur = self.__head
while cur.next is not None:
cur = cur.next
cur.next = node
node.prior = cur
def insert(self, pos, item):
"""指定位置插入元素"""
if pos <= 0:
self.add(item)
elif pos > self.length-1:
self.append(item)
else:
cur = self.__head
count = 0
while count < pos:
count += 1
cur = cur.next
# 退出循环时,prior指向pos
node = Node(item)
node.next = cur
node.prior = cur.prior
cur.prior = node
node.prior.next = node
def remove(self, item):
"""删除指定元素"""
cur = self.__head
while cur is not None:
if cur.elem == item:
if cur == self.__head:
# 头结点
self.__head = cur.next
if cur.next:
# 判断链表是否只有一个节点
cur.next.prior = None
else:
cur.prior.next = cur.next
if cur.next:
cur.next.prior = cur.prev
break
else:
cur = cur.next
def search(self, item):
"""查找是否存在某元素"""
cur = self.__head
while cur is not None:
if cur.elem == item:
return True
else:
cur = cur.next
return False
if __name__ == '__main__':
dl = DoubleLinkList(Node(10))
print(dl.is_empty)
print(dl.length)
dl.add(100)
print(dl.is_empty)
print(dl.length)
dl.travel()
dl.append(3)
dl.append(5)
dl.add(0)
dl.travel()
dl.insert(2, 999)
dl.travel()
dl.insert(6, 77)
dl.travel()
dl.insert(-2, 666)
dl.travel()
dl.remove(0)
dl.travel()
print(dl.search(0))
print(dl.search(5)) |
da7a65b5302e5d172422ceea992794224f6950f7 | Nevermind7/codeeval | /easy/chardonnay_or_cabernet.py | 653 | 3.546875 | 4 | import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
possible = []
wines, letters = test.strip().split(' | ')
wines = wines.split()
for wine in wines:
wine_copy = wine
match = True
for letter in letters:
if letter not in wine_copy:
match = False
break
else:
wine_copy = wine_copy.replace(letter, '', 1)
if match:
possible.append(wine)
if possible:
print(' '.join(possible))
else:
print('False')
|
7811ef7d34af7efc68eb60ae6d6311deb62cf672 | JacquesBeets/python-bootcamp | /7-Dictionaries/dictionaries.py | 3,103 | 3.671875 | 4 | cat = {
"name": "Bol",
"age": 10,
"isVeryCute": True
}
cat2 = dict(name="Simba", age=8, cute=True)
# print(cat["name"])
# =================================
# ITERATING DICTIONARIES WITH LOOPS
# =================================
# for value in cat2.values():
# print(value)
# for key in cat2.keys():
# print(key)
# for key, value in cat2.items():
# print(F"{key}: {value}")
# =================================
# EXCERSIZE
# =================================
# donations = dict(sam=25.0, lena=88.99, chuck=13.0, linus=99.5, stan=150.0, lisa=50.25, harrison=10.0)
# total_donations = 0
# for value in donations.values():
# total_donations += value
# print(total_donations)
# ===================================================
# ITERATING DICTIONARIES WITH LOOPS TESTING WITH "IN"
# ===================================================
# print("name" in cat2) #tests if there is a key with "name" and retun boolean in that dictionary
# print("Bol" in cat.values) #tests if there is a value with "bol" and retun boolean in that dictionary
# =================================
# DICTIONARY METHODS
# =================================
# cat.clear() # clears dictionary
# print(cat)
# cat_copy = cat.copy()
# print(cat_copy)
# new_user = {}.fromkeys(['name', 'score', 'email', 'profile bio'], 'unknown')
# print(new_user)
# .get
# print(cat.get('name')) # when using this method it will not throw an error if it does not exist as with cat['name']
# =================================
# EXCERSIZES
# =================================
# from random import choice
# food = choice(["cheese pizza", "quiche","morning bun","gummy bear","tea cake"])
# bakery_stock = {
# "almond croissant" : 12,
# "toffee cookie": 3,
# "morning bun": 1,
# "chocolate chunk cookie": 9,
# "tea cake": 25
# }
# if food in bakery_stock:
# print(str(bakery_stock[food]) + " left")
# else:
# print("We don't make that")
# EXCERSIZE 2
# game_properties = ["current_score", "high_score", "number_of_lives", "items_in_inventory", "power_ups", "ammo", "enemies_on_screen", "enemy_kills", "enemy_kill_streaks", "minutes_played", "notications", "achievements"]
# initial_game_state = {}.fromkeys(game_properties, 0)
# print(initial_game_state)
# =================================
# DICTIONARY METHODS - PART 2
# =================================
# cat.pop("age") # Removes the key value pair
# print(cat)
# cat.popitem() #removes item randomly from dictionary
# print(cat)
# cat3 = {"city": 'Pretoria'}
# cat3.update(cat) # adds all values from both cat and cat3 into cat3
# print(cat3)
# =================================
# EXCERSIZES
# =================================
# inventory = {'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1}
# stock_list = update(inventory)
# stock_list.update({"cookie": 18})
# stock_list.pop('cake')
# print(stock_list)
# # Another Way
# stock_list = inventory.copy()
# stock_list['cookie'] = 18
# stock_list.pop('cake') |
aa34252cb4c990a15b2c55df59a2ef4839c97eae | shreyanshsaha/tictactoe-AI | /tictacRandom.py | 1,849 | 3.515625 | 4 | from random import choice, randint
import time
import sys
board=[['.','.','.'],['.','.','.'],['.','.','.']]
positions = [(x, y) for x in [0, 1, 2] for y in [0, 1, 2]]
playerPeg = ['X', 'O']
def printBoard(board):
print("\n\nBOARD")
print("-"*10)
for row in board:
for cell in row:
print(cell, end=' ')
print()
print("-"*10)
def playPlayer(playerID):
if len(positions) < 1:
return
position = choice(positions)
positions.remove(position)
board[position[0]][position[1]] = playerPeg[playerID]
def didPlayerWin(playerID):
# Check rows
for row in board:
count = 0
for cell in row:
if cell==playerPeg[playerID]:
count+=1
if count==3:
# print("Row win")
return True
# Check cols
for i in range(3):
count = 0
for j in range(3):
if board[j][i]==playerPeg[playerID]:
count+=1
if count==3:
# print("Col win")
return True
# Check left diag
count=0
for i in range(3):
if board[i][i]==playerPeg[playerID]:
count+=1
if count==3:
# print("LD win")
return True
# Check right diag
count=0
for i in range(3):
if board[i][2-i]==playerPeg[playerID]:
count+=1
if count==3:
# print("RD win")
return True
return False
if __name__=='__main__':
currentPlayer = 0
printBoard(board)
while len(positions) > 0:
print("Current player: AI", playerPeg[currentPlayer], end='')
dots = 0
while dots<3:
dots+=1
sys.stdout.write('.')
sys.stdout.flush()
time.sleep(randint(3, 8)/10)
playPlayer(currentPlayer)
printBoard(board)
if didPlayerWin(currentPlayer):
time.sleep(1)
print("Player", playerPeg[currentPlayer],"wins!")
exit(0)
currentPlayer = 1 - currentPlayer
printBoard(board)
time.sleep(1)
if didPlayerWin(0):
print("Player", playerPeg[0],"wins!")
elif didPlayerWin(1):
print("Player", playerPeg[1],"wins!")
else:
print("DRAW")
|
bc8cf860c0c93fd4c8cc8bd642c1b18b5544b89d | yhs3434/Algorithms | /baekjun/stage solve/09.math1/2775.py | 477 | 3.53125 | 4 | # 부녀회장이 될테야
# https://www.acmicpc.net/problem/2775
def solution(k, n):
answer = 0
board = [[0 for j in range(16)] for i in range(15)]
for i in range(1, 16):
board[0][i] = i
for i in range(1, 15):
for j in range(1, 15):
board[i][j] = board[i][j-1] + board[i-1][j]
answer = board[k][n]
return answer
t = int(input())
for xxx in range(t):
k = int(input())
n = int(input())
print(solution(k, n)) |
21bb47c102fd1778253d81fd034e15e9441759e0 | sergvin75/obuch2 | /cur2.py | 186 | 3.5 | 4 | n = int(input())
b = 0
if 1 <= n <= 100:
while n > 0:
m = int(input())
n -= 1
b += m
print(b)
else:
print(n, " неправильное число")
|
3ff0da29b5ebfbcea7d13e4149cc62f05070d561 | alliance-genome/agr_archive_initial_prototype | /indexer/src/files/comment_file.py | 327 | 3.53125 | 4 |
class CommentFile:
def __init__(self, f, commentstring="#"):
self.f = f
self.commentstring = commentstring
def next(self):
line = self.f.next()
while line.startswith(self.commentstring):
line = self.f.next()
return line
def __iter__(self):
return self
|
5a66df0a819ab325649425e3fc5699559d8bf57b | andrewHosna/python_techdegree_project_2 | /secret_messages.py | 6,391 | 3.96875 | 4 | from affine_cipher import Affine
from atbash_cipher import Atbash
from caesar_cipher import Caesar
from keyword_cipher import Keyword
from polybius_square_cipher import PolybiusSquare
def get_cipher():
"""Ask user to select an available cipher and return the input in lowercase."""
return input("""
Available ciphers:
1. Affine
2. Atbash
3. Caesar
4. Keyword
5. Polybius Square
Select a cipher...
-> """).lower()
def get_message():
"""Ask user for a message and return the input."""
return input("""
Enter a message...
-> """)
def get_option():
"""Ask user to select an option and return the input in lowercase."""
return input("""
Options:
1. Encrypt
2. Decrypt
Select an option...
-> """).lower()
def affine_controller():
"""Use the affine cipher.
Get a message and an option from the user.
Enter a while loop.
Ask user for keys a and b until integer values are provided.
Try to create an instance of Affine() with keys a and b until valid values of keys a and b are provided.
If the option is '1' or 'encrypt' then print the encrypted message.
If the option is '2' or 'decrypt' then print the decrypted message.
Break out of loop.
"""
message = get_message()
option = get_option()
while True:
key_a = input("Enter the first key... (Suggested value: 5)\n-> ")
key_b = input("Enter the second key... (Suggested value: 8)\n-> ")
try:
key_a = int(key_a)
key_b = int(key_b)
except ValueError:
print("Please enter a whole number")
else:
try:
affine = Affine(key_a=key_a, key_b=key_b)
except ValueError as error:
print(error)
else:
if option == '1' or option == 'encrypt':
print("->", affine.encrypt(message))
elif option == '2' or option == 'decrypt':
print("->", affine.decrypt(message))
break
def atbash_controller():
"""Use the atbash cipher.
Get a message and an option from the user.
Create an instance of Atbash().
If the option is '1' or 'encrypt' then print the encrypted message.
If the option is '2' or 'decrypt' then print the decrypted message.
"""
message = get_message()
option = get_option()
atbash = Atbash()
if option == '1' or option == 'encrypt':
print("->", atbash.encrypt(message))
elif option == '2' or option == 'decrypt':
print("->", atbash.decrypt(message))
def caesar_controller():
"""Use the caesar cipher.
Get a message and an option from the user.
Enter a while loop.
Ask user for shift until an integer value is provided.
Try to create an instance of Caesar() with shift until a valid value of shift is provided.
If the option is '1' or 'encrypt' then print the encrypted message.
If the option is '2' or 'decrypt' then print the decrypted message.
Break out of loop.
"""
message = get_message()
option = get_option()
while True:
shift = input("Choose the shift... (Suggested value: 3)\n-> ")
try:
shift = int(shift)
except ValueError:
print("Please enter a whole number")
else:
try:
caesar = Caesar(key=shift)
except ValueError as error:
print(error)
else:
if option == '1' or option == 'encrypt':
print("->", caesar.encrypt(message))
elif option == '2' or option == 'decrypt':
print("->", caesar.decrypt(message))
break
def keyword_controller():
"""Use the keyword cipher.
Get a message and an option from the user.
Enter a while loop.
Ask user for a keyword.
Try to create an instance of Keyword() with key_word until a valid keyword is provided.
If the option is '1' or 'encrypt' then print the encrypted message.
If the option is '2' or 'decrypt' then print the decrypted message.
Break out of loop.
"""
message = get_message()
option = get_option()
while True:
key_word = input("Enter a keyword...\n-> ")
try:
keyword = Keyword(key_word=key_word)
except ValueError as error:
print(error)
else:
if option == '1' or option == 'encrypt':
print("->", keyword.encrypt(message))
elif option == '2' or option == 'decrypt':
print("->", keyword.decrypt(message))
break
def polybius_square_controller():
"""Use the polybius square cipher.
Get a message and an option from the user.
Enter a while loop.
Ask user for a keyword.
Try to create an instance of PolybiusSquare() with key_word until a valid keyword is provided.
If the option is '1' or 'encrypt' then print the encrypted message.
If the option is '2' or 'decrypt' then print the decrypted message.
Break out of loop.
"""
message = get_message()
option = get_option()
while True:
key_word = ""
if input("Use keyword?... (yes/no)\n-> ") == "yes":
key_word = input("Enter a keyword...\n-> ")
try:
polybius_square = PolybiusSquare(key_word=key_word)
except ValueError as error:
print(error)
else:
if option == '1' or option == 'encrypt':
print("->", polybius_square.encrypt(message))
elif option == '2' or option == 'decrypt':
print("->", polybius_square.decrypt(message))
break
if __name__ == '__main__':
print("Welcome to Secret Messages!")
while True:
cipher = get_cipher()
if cipher == '1' or cipher == 'affine':
affine_controller()
elif cipher == '2' or cipher == 'atbash':
atbash_controller()
elif cipher == '3' or cipher == 'caesar':
caesar_controller()
elif cipher == '4' or cipher == 'keyword':
keyword_controller()
elif cipher == '5' or cipher == 'polybius square':
polybius_square_controller()
else:
print("\nYou did not select an available cipher")
if input("\nContinue?... (yes/no)\n-> ") == "no":
exit()
|
2093012fb81ad29fb55345e35eaf2d0ff5609bed | AdriGeaPY/programas1ava | /zprimero/Examenes/e33.py | 560 | 3.65625 | 4 | import random
from random import randint
import random
nom = input("Entra el teu nom: ")
pri = input("Entra el teu primer cognom: ")
seg = input("Entra el teu segon cognom: ")
l=["@","#","!"]
usuari = ""
password=""
usuari= nom[0]+nom[1]+pri[0]+pri[len(pri)-1]+seg[len(seg)-2]+seg[len(seg)-1]
password= str(random.randint(0,9))+str(random.randint(0,9))+str(random.randint(0,9))+str(random.randint(0,9))+ nom[0].upper() + pri[0].lower()
print("El teu usuari per accedir és "+usuari+" i el teu password "+ password)
#no me ha dado tiempo con la lista
|
9711e7a25b61f62098896de50c6cc8dc291c3475 | GaoPengY/python_study | /code/day03/method.py | 707 | 4.3125 | 4 | # 函数
# 具有独立功能的代码块
# 函数的定义:
"""
def 函数名():
代码块
"""
def multiplication_table():
num1 = 1
while num1 <= 9:
num2 = 1
while num2 <= num1:
print("%d X %d = %d" % (num1,num2,num1*num2),end = "\t")
num2 += 1
print("")
num1 += 1
def print_hello():
print("hello")
print("hello")
# 函数的调用
print_hello()
name = "小明"
def print_name(name):
""" 输出姓名 """
print(name)
print_name(name)
def sum(num1,num2):
"""" 计算两数之和 """
return num1 + num2
# return 的注意事项
# return 之后的代码不会再继续 执行
res = sum(10,20)
print(res)
|
038b23b739eb249fc0b37e1594173557f0aab7d1 | davidcotton/algorithm-playground | /src/text/compression/burrows_wheeler_transform.py | 2,018 | 4.28125 | 4 | """
The Burrows-Wheeler transform rearranges strings into runs of similar characters.
This is useful for compression since it tends to be easy to compress a string that has runs
of repeated characters with techniques such as move-to-front transform and run-length encoding.
Most importantly BWT is reversible.
"""
class BWT:
@staticmethod
def encode(text):
n = len(text)
table = [text[i:n] + text[0:i] for i in range(n)]
table = sorted(table)
encoded = ''.join(r[-1] for r in table)
index = table.index(text)
return index, encoded
@staticmethod
def decode(encoded, index):
n = len(encoded)
table = ['' for _ in encoded]
for i in range(n):
table = [c + table[j] for j, c in enumerate(encoded)]
# for j, c in enumerate(encoded):
# table[j] = c + table[j]
table = sorted(table)
return table[index]
if __name__ == '__main__':
# input_str = 'banana'
# input_str = 'The Burrows-Wheeler transform rearranges strings into runs of similar characters.'
input_str = 'The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character ' \
'string into runs of similar characters. This is useful for compression, since it tends to be easy ' \
'to compress a string that has runs of repeated characters by techniques such as move-to-front ' \
'transform and run-length encoding. More importantly, the transformation is reversible, without ' \
'needing to store any additional integers. The BWT is thus a "free" method of improving the efficiency ' \
'of text compression algorithms, costing only some extra computation.'
print('Input:\n {}\n'.format(input_str))
idx, enc = BWT.encode(input_str)
print('Encoded:\n {}\nIndex:\n {}\n'.format(enc, idx))
dec = BWT.decode(enc, idx)
print('Decoded:\n {}'.format(dec))
|
fbe100368512a2d8bd6178a291c33966f2d251cf | sandeepkumar8713/pythonapps | /02_string/17_bucket_sort.py | 1,463 | 4.34375 | 4 | # https://www.geeksforgeeks.org/bucket-sort-2/
# Question : Bucket sort is mainly useful when input is uniformly distributed over a range.
# For example, consider the following problem. Sort a large set of floating point numbers
# which are in range from 0.0 to 1.0 and are uniformly distributed across the range.
# How do we sort the numbers efficiently?
#
# Question Type : Generic
# Used : Make a list of buckets of size 10. Since the input is in range of 0.0 to 1.0,
# multiplying with 10 would give values between 0 to 9. Use this value as index
# and distribute the elements of input array in these 10 buckets.
# Sort each of the bucket individually.
# Index 0 bucket will contain value from 0.0 to 0.09, 1 -> 0.1 to 0.19, 2 -> 0.2 to 0.29
# Merge these buckets into the input array.
# Complexity : average : O(n + n^2/k + k) where k is number of buckets
# worst : O(n^2)
def bucketSort(arr, n):
buckets = []
bucketSize = 10
for i in range(bucketSize):
buckets.append([])
for i in range(n):
bucketIndex = int(bucketSize * arr[i])
buckets[bucketIndex].append(arr[i])
for bucket in buckets:
bucket.sort()
index = 0
for bucket in buckets:
for ele in bucket:
arr[index] = ele
index += 1
if __name__ == "__main__":
arr = [0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434]
bucketSort(arr, len(arr))
print(arr)
|
1f089315a4d61e9a50002902c0239715fced1b78 | Prathamanchan/QuizzBuzzerGUI | /Test/buttonandlabel.py | 549 | 4.0625 | 4 | from Tkinter import *
my_window=Tk()
label_1=Label(my_window,width="20",height="3",bg="white")
label_2=Label(my_window,width="20",height="3",bg="green")
label_3=Label(my_window,width="20",height="3",bg="blue")
button_1=Button(my_window,text="Click Me 1")
button_2=Button(my_window,text="Click Me 2")
button_3=Button(my_window,text="Click Me 3")
label_1.grid(row=0,column=0)
label_2.grid(row=0,column=1)
label_3.grid(row=0,column=2)
button_1.grid(row=1,column=0)
button_2.grid(row=1,column=1)
button_3.grid(row=1,column=2)
my_window.mainloop()
|
17b385cfaab67293e1750b6dc05df4078ec8cb54 | amrithadevi/array | /rev.py | 167 | 3.71875 | 4 |
num12=int(input())
num=0
array=input().split(" ")
array.sort(reverse=True)
for a in range(0,num12):
num*=10
num+=int(array[a])
print(num)
|
feac95f93808af92e7df5d429518181e763023e8 | ucsb-cs8-m18/code-from-class | /08-28/dictionaries.py | 547 | 4.375 | 4 |
# the thing you use to look up is called a key,
# the thing you look up with your key is called a value
# key: value, key: value, ...
d = {"x": "y", "a": "b"} # called a dictionary
# because you can look things up
print(d["x"]) # should print "y"
print(d["a"]) # should print "b"
# keys can be any immutable thing, like numbers, tuples, etc.
nicknames = {"Lawt": "Lawton",
"Bob": "Robert",
"Bobby": "Robert", "Rob": "Robert",
"Nick": "Nicolas",
"Daddy": "Chancellor Yang"}
print(nicknames["Daddy"])
|
54f9acb39f1bffdffe1da4c72d93467851087147 | wheejoo/PythonCodeStudy | /8주차 이분탐색,그래프/숫자카드2/김승욱.py | 330 | 3.53125 | 4 | from bisect import bisect_left, bisect_right
n = int(input())
n_value = list(map(int, input().split()))
m = int(input())
m_value = list(map(int, input().split()))
n_value.sort()
result = []
for i in m_value:
left = bisect_left(n_value, i)
right = bisect_right(n_value, i)
result.append(right - left)
print(*result) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.