blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
832c6af00dcabd3682df2be233f20bc677e8718a | SagarikaNagpal/Python-Practice | /QuesOnOops/B25.py | 385 | 4.125 | 4 | # Question B25: WAP to input two numbers and an operator and calculate the result according to the following conditions:
# Operator Result
# ‘+’ Add
# ‘-‘ Subtract
# ‘*’ Multiply
n1= int(input("n1"))
n2 = int(input("n2"))
opr = input("choice")
if(opr== '+'):
print(n1+n2)
elif(opr== '-'):
print(n1-n2)
elif (opr == '*'):
print(n1*n2)
|
2b0cb7449debeaa87b082dccc621f78bdf0719f4 | chrispy227/python_quiz_1 | /OOP_quiz_app.py | 2,776 | 4.09375 | 4 | from random import sample
class QUIZ:
"""A Customizable Quiz using a 2D list to store the questions, answer choices and answer key."""
def __init__(self, questions, topic):
self.questions = questions # Question 2D List
self.topic = topic # topic decription String
def question_randomizer(self, questions):
return sample(questions, len(questions))
def question_printer(self, questions, index):
print(questions[index][0])
print(questions[index][1])
print("\n")
def validate_input(self):
while True:
value = input(
"Please enter the letter choice for your answer: " + "\n")
validInput = value.lower().strip()
if validInput not in ('a', 'b', 'c', 'd'):
print("Sorry, your response must be A, B, C, or D. Please Try Again.\n")
continue
else:
break
return validInput
def run_quiz(self, questions):
randomized_questions = self.question_randomizer(questions)
finishedQuestions = 0
Score = 0
scoreDenominator = "/{}"
numQuestions = len(randomized_questions)
while finishedQuestions < numQuestions:
correctKey = (randomized_questions[finishedQuestions][2])
self.question_printer(randomized_questions, finishedQuestions)
valdGuess = self.validate_input()
while valdGuess:
if valdGuess == (correctKey):
print("That is Correct! Good Job!\n")
Score += 1
valdGuess = None
else:
print("Sorry, that is Wrong.\n")
valdGuess = None
break
finishedQuestions += 1
if finishedQuestions == numQuestions:
if Score == numQuestions:
print("YOU WIN WITH A PERFECT SCORE!!!!")
else:
print("You Scored: ")
print(str(Score) + scoreDenominator.format(numQuestions)+"\n")
question_bank = [
["What type of aircraft is a Helicopter?",
"A.) Fixed Wing\nB.) Rotary Wing\nC.) Hot Air Ballon\nD.) Glider", "b"],
["What type of aircraft is a Plane?",
"A.) Fixed Wing\nB.) Rotary Wing\nC.) Hot Air Ballon\nD.) Glider", "a"],
["What type of aircraft typically has no engine and must be towed initially?",
"A.) Fixed Wing\nB.) Rotary Wing\nC.) Hot Air Ballon\nD.) Glider\n", "d"],
["What type of aircraft is reliant on wind currents for direction control?",
"A.) Fixed Wing\nB.) Rotary Wing\nC.) Hot Air Ballon\nD.) Glider", "c"]
]
quiz_1 = QUIZ(question_bank, "Aircraft Types")
quiz_1.run_quiz(question_bank)
|
c59280763191995bef0ced4a13fc5cdc2f72f4b7 | sys-bio/tellurium | /tellurium/analysis/parameterestimation.py | 5,589 | 3.671875 | 4 | """
Parameter estimation in tellurium.
"""
from __future__ import print_function, absolute_import
import csv
import numpy as np
import tellurium as te
from scipy.optimize import differential_evolution
import random
class ParameterEstimation(object):
"""Parameter Estimation"""
def __init__(self, stochastic_simulation_model,bounds, data=None):
if(data is not None):
self.data = data
self.model = stochastic_simulation_model
self.bounds = bounds
def setDataFromFile(self,FILENAME, delimiter=",", headers=True):
"""Allows the user to set the data from a File
This data is to be compared with the simulated data in the process of parameter estimation
Args:
FILENAME: A Complete/relative readable Filename with proper permissions
delimiter: An Optional variable with comma (",") as default value.
A delimiter with which the File is delimited by.
It can be Comma (",") , Tab ("\t") or anyother thing
headers: Another optional variable, with Boolean True as default value
If headers are not available in the File, it can be set to False
Returns:
None but sets class Variable data with the data provided
.. sectionauthor:: Shaik Asifullah <s.asifullah7@gmail.com>
"""
with open(FILENAME,'r') as dest_f:
data_iter = csv.reader(dest_f,
delimiter = ",",
quotechar = '"')
self.data = [data for data in data_iter]
if(headers):
self.data = self.data[1:]
self.data = np.asarray(self.data, dtype = float)
def run(self,func=None):
"""Allows the user to set the data from a File
This data is to be compared with the simulated data in the process of parameter estimation
Args:
func: An Optional Variable with default value (None) which by default run differential evolution
which is from scipy function. Users can provide reference to their defined function as argument.
Returns:
The Value of the parameter(s) which are estimated by the function provided.
.. sectionauthor:: Shaik Asifullah <s.asifullah7@gmail.com>
"""
self._parameter_names = self.bounds.keys()
self._parameter_bounds = self.bounds.values()
self._model_roadrunner = te.loada(self.model.model)
x_data = self.data[:,0]
y_data = self.data[:,1:]
arguments = (x_data,y_data)
if(func is not None):
result = differential_evolution(self._SSE, self._parameter_bounds, args=arguments)
return(result.x)
else:
result = func(self._SSE,self._parameter_bounds,args=arguments)
return(result.x)
def _set_theta_values(self, theta):
""" Sets the Theta Value in the range of bounds provided to the Function.
Not intended to be called by user.
Args:
theta: The Theta Value that is set for the function defined/provided
Returns:
None but it sets the parameter(s) to the stochastic model provided
.. sectionauthor:: Shaik Asifullah <s.asifullah7@gmail.com>
"""
for theta_i,each_theta in enumerate(self._parameter_names):
setattr(self._model_roadrunner, each_theta, theta[theta_i])
def _SSE(self,parameters, *data):
""" Runs a simuation of SumOfSquares that get parameters and data and compute the metric.
Not intended to be called by user.
Args:
parameters: The tuple of theta values whose output is compared against the data provided
data: The data provided by the user through FileName or manually
which is used to compare against the simulations
Returns:
Sum of Squared Error
.. sectionauthor:: Shaik Asifullah <s.asifullah7@gmail.com>
"""
theta = parameters
x, y = data
sample_x, sample_y = data
self._set_theta_values(theta)
random.seed()
# it is now safe to use random.randint
#self._model.setSeed(random.randint(1000, 99999))
self._model_roadrunner.integrator.variable_step_size = self.model.variable_step_size
self._model_roadrunner.reset()
simulated_data = self._model_roadrunner.simulate(self.model.from_time, self.model.to_time,
self.model.step_points)
simulated_data = np.array(simulated_data)
simulated_x = simulated_data[:,0]
simulated_y = simulated_data[:,1:]
SEARCH_BEGIN_INDEX = 0
SSE_RESULT = 0
for simulated_i in range(len(simulated_y)):
y_i = simulated_y[simulated_i]
#yhat_i = sample_y[simulated_i]
x_i = simulated_x[simulated_i]
for search_i in range(SEARCH_BEGIN_INDEX+1,len(sample_x)):
if(sample_x[search_i-1] <= x_i < sample_x[search_i]):
yhat_i = sample_y[search_i-1]
break
SEARCH_BEGIN_INDEX += 1
partial_result = 0
for sse_i in range(len(y_i)):
partial_result += (float(y_i[sse_i]) - float(yhat_i[sse_i])) ** 2
SSE_RESULT += partial_result
return SSE_RESULT ** 0.5
|
e5944d3d25b846e0ba00b84150eff7620517e608 | juthy1/Python- | /e16-1.py | 1,673 | 4.28125 | 4 | # -*- coding: utf-8 -*-
#将变量传递给脚本
#from sys import argv
from sys import argv
#脚本、文件名为参数变量
#script, filename = argv
script, filename = argv
#打印“我们将建立filename的文件”%格式化字符,%r。字符串是你想要展示给别人或者从
#从程序里“导出”的一小段字符。
#print ("We're going to erase %r." % filename)
print ("We're going to erase %r." % filename)
#打印提示,如何退出,确定回车
#print ("If you don't want that, hit CTRL-C (^C).")
print ("If you don't want that, hit CTRL-C (^C).")
#print ("If you do want that, hit RETURN.")
print ("If you do want that, hit RETURN.")
#输入,用?来提示
input("?")
#print ("Opening the file...")
print ("Opening the file...")
#打开文件,‘W’目前还不懂
#target = open(filename, 'w')
target = open(filename, 'w')
#清空文件
#print ("Truncating the file. Goodbye!")
print ("Truncating the file. Goodbye!")
#清空文件的命令truncate()
#target.truncate()
target.truncate()
#打印,现在我将请求你回答这三行
#print ("Now I'm going to ask you for three lines.")
print ("Now I'm going to ask you for three lines.")
#第一行输入
#line1 = input("line 1: ")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
#打印,我把这些写入文件
print ("I'm going to write these to the file.")
#target.write(line1, "\n" line2, "\n" line3, "\n")这个是错的
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print ("I'm going to write these to the file.")
print ("And finally, we close it.")
target.close()
|
27c6843b2391f62f6705b7da4bdcd8ab3e00a7c7 | Rexzarrax/CounterClockPython | /clock_pyth-sub.py | 576 | 3.59375 | 4 | import time
import os
from clock import Clock
#clears console
def cls():
os.system('cls' if os.name=='nt' else 'clear')
#program entry point
def main():
#Set the time per increment and the maximum length the clock will run for
Sleeper = 0.1
maxLength = 86410 * 7
myClock = Clock()
print(myClock.DrawClock())
for i in range(0, maxLength):
time.sleep(Sleeper)
cls()
print("Python Clock")
myClock.IncrementClockSec()
print(myClock.DrawClock())
if __name__ == "__main__":
main()
|
adaab441216118f4623e724194bcd008c3241d9b | Anjali-225/PythonCrashCourse | /Chapter_3/Pg_93_Try_It_Yourself_3_10.py | 515 | 3.953125 | 4 | languages = ['English','Afrikaans','Spanish','German','Dutch','Latin']
print(languages[0])
print(languages[-1])
languages.append('Hindi')
print(languages)
languages.insert(0, 'French')
print(languages)
del languages[0]
print(languages)
languages.sort(reverse=True)
print(languages)
languages.reverse()
print(languages)
len(languages)
languages.sort()
print(languages)
popped_languages = languages.pop()
print(languages)
print(popped_languages)
print(sorted(languages)
|
1571c5675a0e614056cfcee317d8addcfb5c474d | Anjali-225/PythonCrashCourse | /Chapter_4/Pg_122_Try_It_Yourself_4-15.py | 1,018 | 4.15625 | 4 | #4-14 Read through it all
################################
#4-15
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(f"The first three items in the list are: {players[0:3]}")
print("")
print(f"Three items from the middle of the list are: {players[1:4]}")
print("")
print(f"The last three items in the list are: {players[-3:]}")
################################
simple_foods = ('potatoes', 'rice', 'soup', 'sandwiches', 'sauce')
for food in simple_foods:
print(food)
#simple_foods[0] = 'mash'
print("")
simple_foods = ('mash','rice','soup','pizza','sandwiches')
for food in simple_foods:
print(food)
###############################
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are: ")
for food in my_foods:
print(f"{food}")
print("")
print("My friends favorite foods are: ")
for foods in friend_foods:
print(f"{foods}") |
6c22bafc0f152bbfc9b16be1f1359b2a287ee53c | Anjali-225/PythonCrashCourse | /Chapter_4/pg_116_Try_It_Yourself_4-11+4-12.py | 729 | 3.921875 | 4 | #4-11
MyPizzas = ['Margherita', 'Chicken Tikka', 'Vegetarian']
print(f"My pizzas: {MyPizzas}")
friend_Pizzas = MyPizzas[:]
print(f"Friends pizzas: {friend_Pizzas}\n")
MyPizzas.append("BBQ")
friend_Pizzas.append("Cheese")
print(f"\nMy favourite pizzas are:")
print(MyPizzas)
print("My friend's favorite pizzas are:")
print(friend_Pizzas)
print("")
print("#4-12")
print("")
#4-12
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are: ")
for food in my_foods:
print(f"{food}")
print("")
print("My friends favorite foods are: ")
for foods in friend_foods:
print(f"{foods}") |
f9677f8d6ca5f1abf2938b43b7e4f550fe2ab600 | Anjali-225/PythonCrashCourse | /Chapter_8/greeter.py | 7,856 | 3.703125 | 4 | def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()
def greet_user(username):
"""Display a simple greeting."""
print(f"Hello, {username.title()}!")
greet_user('jesse')
######################################################################
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster', 'harry')
######################################################################
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
######################################################################
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='harry', animal_type='hamster')
######################################################################
def describe_pet(pet_name, animal_type='dog'):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')
######################################################################
def describe_pet(pet_name, animal_type='dog'):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('willie', 'cat')
######################################################################
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"\n{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
######################################################################
def get_formatted_name(first_name, middle_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {middle_name} {last_name}"
return full_name.title()
musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)
######################################################################
def get_formatted_name(first_name, last_name, middle_name=''):
"""Return a full name, neatly formatted."""
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
######################################################################
def build_person(first_name, last_name):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
######################################################################
def build_person(first_name, last_name, age=None):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)
######################################################################
'''
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!")
'''
######################################################################
def greet_users(names):
"""Print a simple greeting to each user in the list."""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
######################################################################
# Start with some designs that need to be printed.
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
# Simulate printing each design, until none are left.
# Move each design to completed_models after printing.
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
# Display all completed models.
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
######################################################################
def print_models(unprinted_design, completed_model):
"""
Simulate printing each design, until none are left.
Move each design to completed_models after printing.
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
######################################################################
def make_pizza(*toppings):
"""Print the list of toppings that have been requested."""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
######################################################################
def make_pizza(*toppings):
"""Summarize the pizza we are about to make."""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
######################################################################
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
######################################################################
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
######################################################################
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
######################################################################
######################################################################
######################################################################
######################################################################
###################################################################### |
f2006e52c4b4a5fae1cf0a321455ba575d59557f | Anjali-225/PythonCrashCourse | /Chapter_5/Pg_139_Try_It_Yourself.py | 3,940 | 4.0625 | 4 | #5-3
alien_color = 'green'
if 'green' in alien_color:
print("The player just earned 5 points")
if 'blue' in alien_color:
print("The player just earned 5 points")
#5-4
alien_color = 'green'
if 'green' in alien_color:
print("The player earned 5 points for shooting the alien")
else:
print("The player earned 10 points for shooting the alien")
alien_color = 'yellow'
if 'green' in alien_color:
print("The player earned 5 points for shooting the alien")
else:
print("The player earned 10 points for shooting the alien")
#5-5
alien_color = 'green'
if 'green' in alien_color:
print("The player earned 5 points for shooting the alien")
elif 'yellow' in alien_color:
print("The player earned 10 points for shooting the alien")
else:
print("The player earned 15 points for shooting the alien")
alien_color = 'yellow'
if 'green' in alien_color:
print("The player earned 5 points for shooting the alien")
elif 'yellow' in alien_color:
print("The player earned 10 points for shooting the alien")
else:
print("The player earned 15 points for shooting the alien")
alien_color = 'red'
if 'green' in alien_color:
print("The player earned 5 points for shooting the alien")
elif 'yellow' in alien_color:
print("The player earned 10 points for shooting the alien")
else:
print("The player earned 15 points for shooting the alien")
#5-6
age = 1
if age < 2:
print("\nPerson is a baby")
elif age >= 2 and age < 4 :
print("\nPerson is a toddler")
elif age >= 4 and age < 13 :
print("\nPerson is a kid")
elif age >= 13 and age < 20 :
print("\nPerson is a teenager")
elif age >= 20 and age < 65 :
print("\nPerson is a adult")
else:
print("\nPerson is an elder")
age = 3
if age < 2:
print("\nPerson is a baby")
elif age >= 2 and age < 4 :
print("\nPerson is a toddler")
elif age >= 4 and age < 13 :
print("\nPerson is a kid")
elif age >= 13 and age < 20 :
print("\nPerson is a teenager")
elif age >= 20 and age < 65 :
print("\nPerson is a adult")
else:
print("\nPerson is an elder")
age = 10
if age < 2:
print("\nPerson is a baby")
elif age >= 2 and age < 4 :
print("\nPerson is a toddler")
elif age >= 4 and age < 13 :
print("\nPerson is a kid")
elif age >= 13 and age < 20 :
print("\nPerson is a teenager")
elif age >= 20 and age < 65 :
print("\nPerson is a adult")
else:
print("\nPerson is an elder")
age = 15
if age < 2:
print("\nPerson is a baby")
elif age >= 2 and age < 4 :
print("\nPerson is a toddler")
elif age >= 4 and age < 13 :
print("\nPerson is a kid")
elif age >= 13 and age < 20 :
print("\nPerson is a teenager")
elif age >= 20 and age < 65 :
print("\nPerson is a adult")
else:
print("\nPerson is an elder")
age = 21
if age < 2:
print("\nPerson is a baby")
elif age >= 2 and age < 4 :
print("\nPerson is a toddler")
elif age >= 4 and age < 13 :
print("\nPerson is a kid")
elif age >= 13 and age < 20 :
print("\nPerson is a teenager")
elif age >= 20 and age < 65 :
print("\nPerson is a adult")
else:
print("\nPerson is an elder")
age = 70
if age < 2:
print("\nPerson is a baby")
elif age >= 2 and age <4 :
print("\nPerson is a toddler")
elif age >= 4 and age <13 :
print("\nPerson is a kid")
elif age >= 13 and age <20 :
print("\nPerson is a teenager")
elif age >= 20 and age <65 :
print("\nPerson is a adult")
else:
print("\nPerson is an elder")
#5-7
favourite_fruits =['Watermelon','Apples','Blueberries']
if 'Watermelon' in favourite_fruits:
print("You really like Watermelon!")
if 'Apples' in favourite_fruits:
print("You really like Apples!")
if 'Blueberries' in favourite_fruits:
print("You really like Blueberries!")
if 'Pear' in favourite_fruits:
print("You really like Pear")
else:
print("Pear is not in list")
if 'Banana' in favourite_fruits:
print("You really like Banana")
else:
print("Banana is not in list") |
0432421e007f7c65b6e1b8bf1aea0c1571a92974 | Anjali-225/PythonCrashCourse | /Chapter_7/Pg_185_TIY_7-7.py | 285 | 3.765625 | 4 | '''
7-7. Infinity: Write a loop that never ends, and run it. (To end the loop, press CTRL-C or
close the window displaying the output.)
'''
#----------------------------------------------------
x = 1
while x <= 5:
print(x)
#---------------------------------------------------- |
70b19ed1651a51b47d3452bd2369df9cd6ea3436 | Anjali-225/PythonCrashCourse | /Chapter_9/Pg_250_TIY_9_13.py | 1,604 | 4.03125 | 4 | #9-13
from random import randint
#-------------------------------------------------------------------------------
class Die():
def __init__(self, sides=6):
self.sides = sides
def roll_dice(self):
number = randint(1, self.sides)
return (number)
#-------------------------------------------------------------------------------
dice6 = Die()
#-------------------------------------------------------------------------------
results = []
#-------------------------------------------------------------------------------
for roll in range(10):
result = dice6.roll_dice()
results.append(result)
print("10 rolls of a 6-sided dice:")
print(results)
#-------------------------------------------------------------------------------
dice10 = Die(sides= 10)
#-------------------------------------------------------------------------------
results = []
#-------------------------------------------------------------------------------
for roll in range(10):
result = dice10.roll_dice()
results.append(result)
print("\n10 rolls of a 10-sided dice:")
print(results)
#-------------------------------------------------------------------------------
dice20 = Die(sides = 20)
#-------------------------------------------------------------------------------
results = []
#-------------------------------------------------------------------------------
for roll in range(10):
result = dice20.roll_dice()
results.append(result)
print("\n10 rolls of a 20-sided dice:")
print(results)
#------------------------------------------------------------------------------- |
8cbcd7f1c63bbd9fe093848de4edd1a5f80ff05b | maheshnavani/python | /Graph.py | 3,568 | 3.578125 | 4 | import abc
import numpy as np
# abc library is for Python abstract-base-class
class Graph(abc.ABC):
def __int__(self, numVertices, directed=False):
self.numVertices = numVertices
self.directed = directed
@abc.abstractmethod
def add_edge(self, v1, v2, weight=1):
pass
@abc.abstractmethod
def get_adjacent_vertices(self, v):
pass
@abc.abstractmethod
def get_indegree(self, v):
pass
@abc.abstractmethod
def get_edge_weight(self, v1, v2):
pass
@abc.abstractmethod
def display(self):
pass
class AdjacencyMatrixGraph(Graph):
def __init__(self, numVertices, directed=False):
super(AdjacencyMatrixGraph, self).__int__(numVertices, directed)
self.matrix = np.zeros((numVertices, numVertices))
def add_edge(self, v1, v2, weight=1):
if v1 >= self.numVertices or v2 >= self.numVertices or v1 < 0 or v2 < 0:
raise ValueError("Vertices % and % are out of bounts" % (v1, v2))
if weight < 1:
raise ValueError("An edge cannot have negative weight")
self.matrix[v1][v2] = weight
if not self.directed:
self.matrix[v2][v1] = weight
def get_adjacent_vertices(self, v):
adjacent_vertices = []
for i in range(self.numVertices):
if self.matrix[v][i] > 0:
adjacent_vertices.append(i)
return adjacent_vertices
def get_indegree(self, v):
indegree = 0
for i in range(self.numVertices):
if self.matrix[i][v] > 0:
indegree = indegree + 1
return indegree
def get_edge_weight(self, v1, v2):
return self.matrix[v1][v2]
def display(self):
for i in range(self.numVertices):
for v in self.get_adjacent_vertices(i):
print(i, "--->", v)
class Node:
def __init__(self, vertexId):
self.vertexId = vertexId
self.adjacency_set = set()
def add_edge(self, v):
if self.vertexId == v:
raise ValueError("The vertex %d cannot be added to itself" % v)
self.adjacency_set.add(v)
def get_adjacent_vertices(self):
return sorted(self.adjacency_set)
class AdjacencySetGraph(Graph):
def __init__(self, numVertices, directed=False):
super(AdjacencySetGraph, self).__int__(numVertices, directed)
self.vertex_list = []
for i in range(numVertices):
self.vertex_list.append(Node(i))
def add_edge(self, v1, v2, weight=1):
self.vertex_list[v1].add_edge(v2)
if not self.directed:
self.vertex_list[v2].add_edge(v1)
def get_adjacent_vertices(self, v):
return self.vertex_list[v].get_adjacent_vertices();
def get_indegree(self, v):
indegree = 0
for i in range(self.numVertices):
if v in self.get_adjacent_vertices(i):
indegree = indegree + 1
return indegree
def get_edge_weight(self, v1, v2):
return 1
def display(self):
for i in range(self.numVertices):
for v in self.get_adjacent_vertices(i):
print(i, "--->", v)
g = AdjacencySetGraph(4, False)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(2, 3)
for i in range(4):
print("Adjacent to:", i, g.get_adjacent_vertices(i))
for i in range(4):
print("Indegree: ", i, g.get_indegree(i))
for i in range(4):
for j in g.get_adjacent_vertices(i):
print("Edge Weight: ", i, " ", j, "weight:", g.get_edge_weight(i, j))
g.display()
|
3696239fa5b153fae838212c6d01305ae480b28b | Sandro-Tan/Game-2048 | /Game_2048.py | 6,355 | 3.765625 | 4 | """
2048 game
Move and merge squares using arrow keys
Get a 2048-value tile to win
Author: Sandro Tan
Date: Aug 2019
Version: 1.0
"""
import GUI_2048
import random
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0),
DOWN: (-1, 0),
LEFT: (0, 1),
RIGHT: (0, -1)}
def merge(line):
"""
Helper function that merges a single row or column in 2048
"""
# remove all zeros in original line and output into a new list
newlist = []
output = []
for item in line:
if item != 0:
newlist.append(item)
# merge the numbers
for index in range(len(newlist) - 1):
if newlist[index] == newlist[index + 1]:
newlist[index] *= 2
newlist[index + 1] = 0
for item in newlist:
if item != 0:
output.append(item)
while len(output) < len(line):
output.append(0)
return output
# helper function to return number 2 (90%) or 4 (10%)
def random_number(nums, probs):
seed = random.random()
if seed > probs[0]:
return nums[1]
else:
return nums[0]
class TwentyFortyEight:
"""
Class to run the game logic.
"""
def __init__(self, grid_height, grid_width):
self.grid_height = grid_height
self.grid_width = grid_width
# initial tiles indices
self.indices_up = [[0, col] for col in range(self.get_grid_width())]
self.indices_down = [[self.get_grid_height() - 1, col] for col in range(self.get_grid_width())]
self.indices_left = [[row, 0] for row in range(self.get_grid_height())]
self.indices_right = [[row, self.get_grid_width() - 1] for row in range(self.get_grid_height())]
self.indices_dict = {UP: self.indices_up,
DOWN: self.indices_down,
LEFT: self.indices_left,
RIGHT: self.indices_right}
self.reset()
def reset(self):
"""
Reset the game so the grid is empty except for two
initial tiles.
"""
# stores intitial values
self.cells_value = [[0 for row in range(self.grid_height)] for col in range(self.grid_width)]
for dummy_idx in range(2):
self.new_tile()
def __str__(self):
"""
Return a string representation of the grid for debugging.
"""
output = 'Height:' + str(self.get_grid_height())
output += ' Width:' + str(self.get_grid_width())
return output
def get_grid_height(self):
"""
Get the height of the board.
"""
return self.grid_height
def get_grid_width(self):
"""
Get the width of the board.
"""
return self.grid_width
def move(self, direction):
"""
Move all tiles in the given direction and add
a new tile if any tiles moved.
"""
'''
indices dictionary stores the indices of edge cells
For example, after pressing up arrow key,
edge tiles variable will store the indices of the top row
'''
edge_tiles = self.indices_dict[direction]
# Get the lines that hold values
line = []
for item in edge_tiles:
temp = []
row_index = item[0]
col_index = item[1]
temp.append(self.get_tile(row_index, col_index))
for dummy_idx in range(len(edge_tiles) - 1):
row_index += OFFSETS[direction][0]
col_index += OFFSETS[direction][1]
temp.append(self.get_tile(row_index, col_index))
line.append(temp)
# Merge the lines and put them in a new list
merged = []
for item in line:
merged.append(merge(item))
# Convert row and col in merged list to those in a grid to be painted
# Still thinking about some way to simplify these codes
if direction == UP:
for row in range(len(merged[0])):
for col in range(len(merged)):
self.set_tile(col, row, merged[row][col])
if direction == DOWN:
for row in range(len(merged[0])):
for col in range(len(merged)):
self.set_tile(self.get_grid_height() - col - 1, row, merged[row][col])
if direction == LEFT:
for row in range(len(merged)):
for col in range(len(merged[0])):
self.set_tile(row, col, merged[row][col])
if direction == RIGHT:
for row in range(len(merged)):
for col in range(len(merged[0])):
self.set_tile(row, self.get_grid_width() - col - 1, merged[row][col])
self.new_tile()
def new_tile(self):
"""
Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time.
"""
random_row = random.randint(0, self.get_grid_height() - 1)
random_col = random.randint(0, self.get_grid_width() - 1)
value = random_number((2, 4), (0.9, 0.1))
if self.get_tile(random_row, random_col) == 0:
self.set_tile(random_row, random_col, value)
# no two tiles at the same location
else:
self.new_tile()
def set_tile(self, row, col, value):
"""
Set the tile at position row, col to have the given value.
"""
self.cells_value[row][col] = value
def get_tile(self, row, col):
"""
Return the value of the tile at position row, col.
"""
return self.cells_value[row][col]
def game_win(self):
for row in range(self.get_grid_height()):
for col in range(self.get_grid_width()):
if self.get_tile(row, col) == 2048:
print("You win!")
self.reset()
game = TwentyFortyEight(4,4)
GUI_2048.run_gui(game)
|
1557048a28338cabcc7f003dd71f6649fbfae7ac | teinhonglo/leetcode | /problem/swapPairs.py | 521 | 3.625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = head
while prev:
cur = prev.next
if cur != None:
prev.val, cur.val = cur.val, prev.val
else:
break
prev = cur.next
return head |
def85ca7efbf7147eb11250af67354c85f2b4de1 | teinhonglo/leetcode | /problem/Binary-Tree-Level-Order-Traversal.py | 1,104 | 3.734375 | 4 | tion for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# check wheter value of root is empty or not
if root == None: return []
# initialize
stack = [root]
top_down = [[root.val]]
# depth first search (DFS)
# recording value of each level
while stack:
level = [[],[]]
# traversal current level
for node in stack:
if node.left:
level[0].append(node.left)
level[1].append(node.left.val)
if node.right:
level[0].append(node.right)
level[1].append(node.right.val)
# next level
stack = level[0]
# recoring value of current level
if len(level[1]) > 0: top_down.append(level[1])
return top_down
|
3f3e498ae7b843294dca0c558d97b0c020522e6c | GeekHanbin/DLAction | /tflearn/base_kn/base.py | 2,997 | 3.640625 | 4 | import tensorflow as tf
# https://blog.csdn.net/lengguoxing/article/details/78456279
# TensorFlow的数据中央控制单元是tensor(张量),一个tensor由一系列的原始值组成,这些值被形成一个任意维数的数组。一个tensor的列就是它的维度。
# Building the computational graph构建计算图
# 一个computational graph(计算图)是一系列的TensorFlow操作排列成一个节点图
node1 = tf.constant(3.0,dtype=tf.float32)
node2 = tf.constant(4.0)
print(node1,node2)
print('*'*50)
# 一个session封装了TensorFlow运行时的控制和状态,要得到最终结果要用session控制
session = tf.Session()
print(session.run([node1,node2]))
print('*'*50)
# 组合Tensor节点操作(操作仍然是一个节点)来构造更加复杂的计算
node3 = tf.add(node1,node2)
print(node3)
print(session.run(node3))
print('*'*50)
# TensorFlow提供一个统一的调用称之为TensorBoard,它能展示一个计算图的图片
# 一个计算图可以参数化的接收外部的输入,作为一个placeholders(占位符),一个占位符是允许后面提供一个值的
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
add_node = a+b
print(session.run(add_node,{a:3,b:4}))
print(session.run(add_node,{a:[1,4],b:[4,9]}))
print('*'*50)
# 我们可以增加另外的操作来让计算图更加复杂
add_and_triple = add_node * 3
print(session.run(add_and_triple,{a:3,b:4}))
print('*'*50)
# 构造线性模型输入 y = w*x+b
w = tf.Variable([.3],dtype=tf.float32)
b = tf.Variable([-.3],dtype=tf.float32)
x = tf.placeholder(dtype=tf.float32)
linner_mode = w*x + b
# 当你调用tf.constant时常量被初始化,它们的值是不可以改变的,而变量当你调用tf.Variable时没有被初始化,在TensorFlow程序中要想初始化这些变量,你必须明确调用一个特定的操作
init = tf.global_variables_initializer()
session.run(init)
print(session.run(linner_mode,{x:[1,2,3,4,8]}))
print('*'*50)
# 评估模型好坏,我们需要一个y占位符来提供一个期望值,和一个损失函数
y = tf.placeholder(dtype=tf.float32)
loss_function = tf.reduce_sum(tf.square(linner_mode - y))
print(session.run(loss_function,{x:[1,2,3,4],y:[0, -1, -2, -3]}))
# 们分配一个值给W和b(得到一个完美的值是-1和1)来手动改进这一点,一个变量被初始化一个值会调用tf.Variable,但是可以用tf.assign来改变这个值,例如:fixW = tf.assign(W, [-1.])
fixw = tf.assign(w,[-1])
fixb = tf.assign(b,[1])
session.run([fixb,fixw])
print(session.run(loss_function,{x:[1,2,3,4],y:[0, -1, -2, -3]}))
# optimizers 我们写一个优化器使得,他能慢慢改变变量来最小化损失函数,最简单的是梯度下降
optimizers = tf.train.GradientDescentOptimizer(0.01)
train = optimizers.minimize(loss_function)
session.run(init) # reset value
for i in range(1000):
session.run(train, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]})
print(session.run([w,b]))
print(session.run([w,b])) |
63ada01e7b5655945f6c1800be50015960faef95 | LuserName01/entergame | /main.py | 750 | 3.796875 | 4 | import time
time.sleep(2)
print("Welcome to my first game!")
time.sleep(1)
print("All you have to do is hold enter!")
time.sleep(2)
print("STOP AT 30 OR RESULTS.TXT WILL BE FILLED!!!")
time.sleep(3)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
input(1)
input(2)
input(3)
input(4)
input(5)
input(6)
input(7)
input(8)
input(9)
input(10)
input(11)
input(12)
input(13)
print("CHECKPOINT! YOU WILL NEED TO STOP SOON!")
input(14)
input(15)
input(16)
input(17)
input(18)
input(19)
input(20)
input(21)
input(22)
input(23)
input(24)
input(25)
input(26)
input(27)
input(28)
input(29)
input(30)
print("STOP!")
print("NOO! LOOK AT RESULTS.TXT!!!")
f = open("Results.txt", "w")
f.write("YOU FAILED TO STOP, START OVER!")
f.close()
|
fad78bd651abc58de459ca5c050cd33c4fc317e4 | laijnaloo/TheZoo | /ZooUtils.py | 2,354 | 3.59375 | 4 | __author__ = 'Lina Andersson'
# Programmeringsteknik webbcourse KTH P-task.
# Lina Andersson
# 2016-03-29
# Program for a zoo where the user can search, sort, buy, sell and get recommendations on what to buy or sell.
# This file contains helpclasses that occurs in the other files and is one of five modules in this program.
from tkinter import *
from PIL import ImageTk, Image
#Class for labels behind animal picture/objects
class AnimalLabel:
def __init__(self, anAnimal, imageName):
#animal picture
self.anAnimal = anAnimal
self.img = Image.open(imageName)
self.tkImg = ImageTk.PhotoImage(self.img)
def addAsLabel(self, tkRoot, row, column, event = lambda X: None):
#creates a label with image and adds it too root
self.imgLabel = Label(tkRoot, image = self.tkImg, borderwidth = 0)
self.imgLabel.bind("<Button-1>", event)
self.imgLabel.place(x = row, y = column)
#if no animal - make black square
if self.anAnimal != None:
self.anAnimal.addAsLabel(tkRoot, row, column, event)
#Class for animal objects
class Animal:
def __init__(self, name, age, species, gender):
self.name = name
self.age = age
self.species = species
self.gender = gender
#creates picture of animal
nameImage = self.species + ".png"
self.img = Image.open(nameImage)
self.tkImg = ImageTk.PhotoImage(self.img)
#creates a label with image and adds animal to label
def addAsLabel(self, tkRoot, row, column, event = lambda X: None):
self.imgLabel = Label(tkRoot, image = self.tkImg, borderwidth = 0)
self.imgLabel.bind("<Button-1>", event)
self.imgLabel.place(x = row + 3, y = column + 3)
#class for buttons in the program
class MyButton:
def __init__(self, name):
self.name = name
nameImage = self.name + ".png"
self.img = Image.open(nameImage)
self.tkImg = ImageTk.PhotoImage(self.img)
#creates a label with image and adds it too root
def addAsLabel(self, tkRoot, xPosition, yPosition, event = lambda X: None):
self.imgLabel = Label(tkRoot, image = self.tkImg, borderwidth = 0)
self.imgLabel.bind("<Button-1>", event)
self.imgLabel.place(x = xPosition, y = yPosition)
def destroy(self):
self.imgLabel.destroy()
|
b66a00e7bbb55c394e587942a80fb58ccb725173 | rainly/binanace_test | /Signals.py | 9,652 | 3.734375 | 4 | """
《邢不行-2020新版|Python数字货币量化投资课程》
无需编程基础,助教答疑服务,专属策略网站,一旦加入,永续更新。
课程详细介绍:https://quantclass.cn/crypto/class
邢不行微信: xbx9025
本程序作者: 邢不行
# 课程内容
币安u本位择时策略实盘框架需要的signal
"""
import pandas as pd
import random
import numpy as np
# 将None作为信号返回
def real_signal_none(df, now_pos, avg_price, para):
"""
发出空交易信号
:param df:
:param now_pos:
:param avg_price:
:param para:
:return:
"""
return None
# 随机生成交易信号
def real_signal_random(df, now_pos, avg_price, para):
"""
随机发出交易信号
:param df:
:param now_pos:
:param avg_price:
:param para:
:return:
"""
r = random.random()
if r <= 0.25:
return 0
elif r <= 0.5:
return 1
elif r <= 0.75:
return -1
else:
return None
# 布林策略实盘交易信号
def real_signal_simple_bolling(df, now_pos, avg_price, para=[200, 2]):
"""
实盘产生布林线策略信号的函数,和历史回测函数相比,计算速度更快。
布林线中轨:n天收盘价的移动平均线
布林线上轨:n天收盘价的移动平均线 + m * n天收盘价的标准差
布林线上轨:n天收盘价的移动平均线 - m * n天收盘价的标准差
当收盘价由下向上穿过上轨的时候,做多;然后由上向下穿过中轨的时候,平仓。
当收盘价由上向下穿过下轨的时候,做空;然后由下向上穿过中轨的时候,平仓。
:param df: 原始数据
:param para: 参数,[n, m]
:return:
"""
# ===策略参数
# n代表取平均线和标准差的参数
# m代表标准差的倍数
n = int(para[0])
m = para[1]
# ===计算指标
# 计算均线
df['median'] = df['close'].rolling(n).mean() # 此处只计算最后几行的均线值,因为没有加min_period参数
median = df.iloc[-1]['median']
median2 = df.iloc[-2]['median']
# 计算标准差
df['std'] = df['close'].rolling(n).std(ddof=0) # ddof代表标准差自由度,只计算最后几行的均线值,因为没有加min_period参数
std = df.iloc[-1]['std']
std2 = df.iloc[-2]['std']
# 计算上轨、下轨道
upper = median + m * std
lower = median - m * std
upper2 = median2 + m * std2
lower2 = median2 - m * std2
# ===寻找交易信号
signal = None
close = df.iloc[-1]['close']
close2 = df.iloc[-2]['close']
# 找出做多信号
if (close > upper) and (close2 <= upper2):
signal = 1
# 找出做空信号
elif (close < lower) and (close2 >= lower2):
signal = -1
# 找出做多平仓信号
elif (close < median) and (close2 >= median2):
signal = 0
# 找出做空平仓信号
elif (close > median) and (close2 <= median2):
signal = 0
return signal
# 闪闪的策略
def real_signal_shanshan_bolling(df, now_pos, avg_price, para=[200, 2]):
"""
实盘产生布林线策略信号的函数,和历史回测函数相比,计算速度更快。
布林线中轨:n天收盘价的移动平均线
布林线上轨:n天收盘价的移动平均线 + m * n天收盘价的标准差
布林线上轨:n天收盘价的移动平均线 - m * n天收盘价的标准差
当收盘价由下向上穿过上轨的时候,做多;然后由上向下穿过中轨的时候,平仓。
当收盘价由上向下穿过下轨的时候,做空;然后由下向上穿过中轨的时候,平仓。
:param df: 原始数据
:param para: 参数,[n, m]
:return:
"""
# ===策略参数
# n代表取平均线和标准差的参数
# m代表标准差的倍数
bolling_window = int(para[0])
d = para[1]
# ===计算指标
# 计算均线
df['median'] = df['close'].rolling(bolling_window).mean() # 此处只计算最后几行的均线值,因为没有加min_period参数
median = df.iloc[-1]['median']
median2 = df.iloc[-2]['median']
# 计算标准差
df['std'] = df['close'].rolling(bolling_window).std(ddof=0) # ddof代表标准差自由度,只计算最后几行的均线值,因为没有加min_period参数
std = df.iloc[-1]['std']
std2 = df.iloc[-2]['std']
m = (abs((df['close'] - df['median']) / df['std'])).rolling(bolling_window, min_periods=1).max()
# 计算上轨、下轨道
upper = median + m.iloc[-1] * std
lower = median - m.iloc[-1] * std
upper2 = median2 + m.iloc[-2] * std2
lower2 = median2 - m.iloc[-2] * std2
# ===计算KDJ指标
df['k'], df['d'] = np.float16(talib.STOCH(high = df['high'], low = df['low'], close = df['close'],
#此处三个周期(9,3,3)只是习惯取法可以作为参数更改
fastk_period = 9, # RSV值周期
slowk_period = 3, # 'K'线周期
slowd_period = 3, # 'D'线周期
slowk_matype = 1, # 'K'线平滑方式,1为指数加权平均,0 为普通平均
slowd_matype = 1))# 'D'线平滑方式,1为指数加权平均,0 为普通平均
df['j'] = df['k'] * 3 - df['d'] * 2 # 'J' 线
# 计算j值在kdj_window下的历史百分位
kdj_window = 9 # 此处的回溯周期取为上面计算kdj的fastk_period
j_max = df['j'].rolling(kdj_window, min_periods=1).max()
j_min = df['j'].rolling(kdj_window, min_periods=1).min()
df['j_exceed'] = abs(j_max - df['j']) / abs(j_max - j_min)
j_exceed = df.iloc[-1]['j_exceed']
# 计算ATR
df['atr'] = talib.ATR(high=df['high'],low=df['low'],close=df['close'],timeperiod=int(bolling_window/d))
# 计算ATR布林通道上下轨
df['atr_upper'] = df['median'] + df['atr']
df['atr_lower'] = df['median'] - df['atr']
atr_upper = df.iloc[-1]['atr_upper']
atr_lower = df.iloc[-1]['atr_lower']
# ===寻找交易信号
signal = None
close = df.iloc[-1]['close']
close2 = df.iloc[-2]['close']
# 找出做多信号
if (close > upper) and (close2 <= upper2) and (j_exceed <= 0.3) and (close >= atr_upper):
signal = 1
# 找出做空信号
elif (close < lower) and (close2 >= lower2) and (j_exceed >= 0.7) and (close <= atr_lower):
signal = -1
# 找出做多平仓信号
elif (close < median) and (close2 >= median2):
signal = 0
# 找出做空平仓信号
elif (close > median) and (close2 <= median2):
signal = 0
return signal
def real_signal_adp2boll_v2(df, now_pos, avg_price, para=[200]):
"""
实盘产生布林线策略信号的函数,和历史回测函数相比,计算速度更快。
布林线中轨:n天收盘价的移动平均线
布林线上轨:n天收盘价的移动平均线 + m * n天收盘价的标准差
布林线上轨:n天收盘价的移动平均线 - m * n天收盘价的标准差
当收盘价由下向上穿过上轨的时候,做多;然后由上向下穿过中轨的时候,平仓。
当收盘价由上向下穿过下轨的时候,做空;然后由下向上穿过中轨的时候,平仓。
:param df: 原始数据
:param para: 参数,[n, m]
:return:
"""
# ===策略参数
# n代表取平均线和标准差的参数
# m代表标准差的倍数
n = int(para[0])
# ===计算指标
# 计算均线
df['median'] = df['close'].rolling(n, min_periods=1).mean() # 此处只计算最后几行的均线值,因为没有加min_period参数
# 计算标准差
df['std'] = df['close'].rolling(n, min_periods=1).std(ddof=0) # ddof代表标准差自由度,只计算最后几行的均线值,因为没有加min_period参数
df['z'] = abs(df['close'] - df['median']) / df['std']
df['z_score'] = df['z'].rolling(window=int(n/10)).mean() # 先对z求n/10个窗口的平均值
df['m1'] = df['z_score'].rolling(window=n).max().shift(1) # 再用n个窗口内z_score的最大值当作母布林带的m
df['m2'] = df['z_score'].rolling(window=n).min().shift(1) # 再用n个窗口内z_score的最小值当作子布林带的m
df['upper'] = df['median'] + df['std'] * df['m1']
df['lower'] = df['median'] - df['std'] * df['m1']
df['up'] = df['median'] + df['std'] * df['m2']
df['dn'] = df['median'] - df['std'] * df['m2']
upper1 = df.iloc[-1]['upper']
upper2 = df.iloc[-2]['upper']
lower1 = df.iloc[-1]['lower']
lower2 = df.iloc[-2]['lower']
up1 = df.iloc[-1]['up']
up2 = df.iloc[-2]['up']
dn1 = df.iloc[-1]['dn']
dn2 = df.iloc[-2]['dn']
# ===寻找交易信号
signal = None
close1 = df.iloc[-1]['close']
close2 = df.iloc[-2]['close']
# 找出做多信号
if (close1 > upper1) and (close2 <= upper2):
signal = 1
# 找出做空信号
elif (close1 < lower1) and (close2 >= lower2):
signal = -1
# 找出做多平仓信号
elif (close1 < up1) and (close2 >= up2):
signal = 0
# 找出做空平仓信号
elif (close1 > dn1) and (close2 <= dn2):
signal = 0
print("time={}".format(df.iloc[-1]['candle_begin_time_GMT8']))
print("close={} upper={} lower={}".format(close1, upper1, lower1))
print("close2={} upper2={} lower2={}".format(close2, upper2, lower2))
print("signal={} up1={} up2={} dn1={} dn2={}".format(signal, up1, up2, dn1, dn2))
return signal
|
d2d07622e38f3cc865281e179ddd46f64f85c3f2 | RoozbehSanaei/snippets | /python/swig/numpy/test.py | 785 | 3.8125 | 4 | import numpy
from numpy.random import rand
from example import *
def makeArray(rows, cols):
return numpy.array(numpy.zeros(shape=(rows, cols)), dtype=numpy.intc)
arr2D = makeArray(4, 4)
func2(arr2D)
print ("two dimensional array")
print (arr2D)
input_array1 = rand(5)
sum = sum_array(input_array1,arr2D)
print('The sum of the array is %d' % (sum))
input_array2 = rand(5)
sum = sum_array2(input_array1,input_array2)
print('The sum of the array is %d' % (sum))
print ("get random array:")
output_array = get_rand_array(10)
print (output_array)
print ("get random list:")
output_list = list(double_list(10,input_array1))
print (input_array1)
print (output_list)
arr2D = makeArray(28, 28)
arrayFunction(arr2D)
print ("two dimensional array")
print (numpy.sum(arr2D))
|
d9dc0e1bde1e78fdac69f0c6f4a52d12eba9874a | umangsaluja/CAP930autumn | /set.py | 702 | 4.03125 | 4 | numbers={23,34,2}
name={'firstname','lastname'}
print(name)
print(type(name))
print(numbers)
empty_Set=set()
set_from_list=set([1,2,34,5])
basket={"apple","orange","banana"}
print(len(basket))
basket.add("grapes")
basket.remove("apple")#raises keyerror if "elements" is not present
basket.discard("apple")# same as remove ,except no error
print(basket)
basket.discard("mango")
basket.pop()
print(basket)
basket.clear()
print(basket)
a=set("abcadefghijk")
b=set("alacazam")
print(a)
print(b)
diff=a-b
print(diff)
union=a|b
print(union)
intersection=a&b
print(intersection)
symmetric_difference=a^b #(a-b)union(b-a)
print(symmetric_difference)
|
07af6c34d8365158a21250d6dc858399169fb80c | bharathkumarreddy19/python_loops_and_conditions | /odd_even.py | 232 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 19:00:17 2020
@author: bhara_5sejtsc
"""
num = int(input("Enter a number: "))
if num%2 == 0:
print("The given number is even")
else:
print("The given number is odd") |
ac50dc8238e1ccbcc2dd600cacbbdd58806cf719 | dlucidone/py-scripts | /LuckyVendingMachine/LuckyVendingMachine.py | 6,983 | 3.953125 | 4 | from random import randint
class player:
player_name = "Bot"
player_prizes = 10
player_money = 100
def set_player_details(self,name, prizes, money):
self.player_name = name
self.player_prizes = prizes
self.player_money = money
def get_player_details(self):
print("Name:{}\nPrizes:{}\nMoney:{}".format(self.player_name, self.player_prizes, self.player_money))
class lucky_number_generator:
def generate_number(self):
self.lucky_number = randint(1, 5)
#return lucky_number
class Game(player, lucky_number_generator):
def __init__(self):
pass
GameObj = Game()
#new_money=0
Choice = True
while Choice == True:
print("(1) Set Up New Player\n"
"(2) Guess A Prize \n"
"(3) What Have I Won So Far?\n"
"(4) Display Game Help\n"
"(5) Exit Game\n")
try:
choice = int(input("Select an option : "))
except:
print("Enter Integer")
continue
if choice == 1:
print("Enter Player details")
try:
name = input("Enter player name :" )
except:
print("Error:Enter String for name|Try Again")
continue
try:
prizes = int(input("Enter No. of Prizes : "))
except:
print("Error:Enter Number for Prizes|Try Again ")
continue
try:
money = float(input("Enter Total money player has : "))
if money<5:
print("Enter Money Greater than 5 To Play")
continue
except:
print("Error:Enter Number in Money|Try Again")
continue
GameObj.set_player_details(name,prizes,money)
fw = open('Player_Record.txt', 'w')
fw.write(GameObj.player_name)
fw.write("\n")
fw.write(str(GameObj.player_prizes))
fw.write("\n")
fw.write(str(GameObj.player_money))
fw.close()
continue
elif choice == 2:
'''print ("Do You want to enter Game - Press Y to Continue or No to Main Menu ")
choice_for_game = str(input())
if choice_for_game == "Y" or "y":
print("Lets Start the game")
break
elif choice_for_game == "N" or "n":
continue
else:
print ("Enter a valid response")'''
print("Lets Roll the ball")
print("Guess a Number Based Upon the List and It Should Be in Range[1-5]")
try:
Guess_Number = int(input())
except:
print("Enter Integer")
continue
GameObj.generate_number()
if Guess_Number<=5 and Guess_Number == GameObj.lucky_number:
print("You Selected Number {} and LuckyNumberGenerated is {}".format(Guess_Number,GameObj.lucky_number))
print("You Won",Guess_Number*10)
new_money = GameObj.player_money
new_money += Guess_Number*10-Guess_Number
#print(new_money)
print("new money",new_money)
GameObj.player_money=new_money
fw = open('Player_Record.txt', 'w')
fw.write(GameObj.player_name)
fw.write("\n")
fw.write(str(GameObj.player_prizes))
fw.write("\n")
fw.write(str(GameObj.player_money))
fw.close()
print("New Score\n",GameObj.get_player_details())
if Guess_Number == 1:
print("And You-Won a Pen")
elif Guess_Number == 2:
print("And You-Won a Book")
elif Guess_Number == 3:
print("And You-Won a DVD")
elif Guess_Number == 4:
print("And You-Won a Mouse")
elif Guess_Number == 5:
print("And You-Won a Keyboard")
elif Guess_Number>=6:
print("Enter number in Range")
else:
print("You Selected Number {} and LuckyNumberGenerated is {}".format(Guess_Number,GameObj.lucky_number))
print("You Loose",Guess_Number)
new_money = GameObj.player_money
new_money -= Guess_Number
print("new money",new_money)
GameObj.player_money=new_money
#print(new_money)
fw = open('Player_Record.txt', 'w')
fw.write(GameObj.player_name)
fw.write("\n")
fw.write(str(GameObj.player_prizes))
fw.write("\n")
fw.write(str(GameObj.player_money))
fw.close()
print("New Score\n", GameObj.get_player_details())
elif choice == 3:
GameObj.get_player_details()
elif choice == 4:
print("Help center")
fw = open('Game_help.txt', 'w')
fw.write('''
Number_Generated|Price_Won|Price_Worth|Cost_to_Player\n
=======================================================
1\t\t\tPen \t\t\t$10\t\t\t$1
2\t\t\tBook \t\t\t$20\t\t\t$2
3\t\t\tDVD \t\t\t$30\t\t\t$3
4\t\t\tMouse \t\t\t$40\t\t\t$4
5\t\t\tKeyboard \t\t\t$50\t\t\t$5
''')
fw.close()
fr = open('Game_help.txt', 'r')
text = fr.read()
print(text)
fr.close()
elif choice == 5:
exit(0)
else:
print("Enter a Valid Choice")
continue
|
d1613d1c58f62c640070de20ad563a2838594ef3 | esponja92/flaskforge | /tools/dbgen.py | 2,479 | 3.765625 | 4 | import sqlite3
def create():
nome_tabela = input("Informe o nome da tabela a ser criada: ")
criar = "s"
nomes_campo = []
tipos_campo = []
while(criar == "s"):
nome_campo = input("Informe o nome do novo campo: ")
tipo_campo = input("Informe o tipo do novo campo: (1-NULL, 2-INTEGER, 3-REAL, 4-TEXT, 5-BLOB): ")
try:
#conferindo se o usuario informou o tipo correto
if tipo_campo not in ["1","2","3","4","5"]:
raise Exception("Tipo informado não corresponde a lista dos tipos permitidos para criação de novos campos")
nomes_campo.append(nome_campo)
tipos_campo.append(tipo_campo)
except Exception as e:
print(str(e))
finally:
criar = input("Deseja criar um novo campo?: (S/n)")
if criar == "":
criar = "s"
#criando a tabela
try:
conn = sqlite3.connect('../database.db')
sql = 'CREATE TABLE ' + nome_tabela + '('
if len(nomes_campo) != len(tipos_campo):
raise Exception("A quantidade de nomes de campos e tipos informados não estão iguais")
sql = sql + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
for i in range(len(nomes_campo)):
sql = sql + nomes_campo[i] + " "
if tipos_campo[i] == "1":
sql = sql + "NULL"
if tipos_campo[i] == "2":
sql = sql + "INTEGER"
if tipos_campo[i] == "3":
sql = sql + "REAL"
if tipos_campo[i] == "4":
sql = sql + "TEXT"
if tipos_campo[i] == "5":
sql = sql + "BLOB"
if i != len(nomes_campo) - 1:
sql = sql + ","
sql = sql + ')'
conn.execute(sql)
print("Tabela criada com sucesso!")
except Exception as e:
print("Ocorreu um erro na criação da tabela:")
print(str(e))
finally:
conn.close()
if __name__ == "__main__":
print("Selecione a operação que deseja realizar:")
print("1 - criar uma nova tabela")
#print("4 - consultar registros em uma tabela criada")
#print("2 - inserir registros em uma tabela criada")
#print("3 - atualizar registros em uma tabela criada")
#print("5 - remover registros em uma tabela criada")
opcao = input("Digite a opção: ")
if opcao == "1":
create() |
81320a3170127cc515b57c40f7b8404994ddc94d | phani1995/logistic_regression | /src/binomial_logistic_regression_using_scikit_learn.py | 2,318 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# Imports
#import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Reading the Dataset
# Iris Dataset
dataset = pd.read_csv('..//data//titanic_dataset//iris.csv')
x_labels = ['sepal length', 'sepal width', 'petal length', 'petal width']
y_labels = ['iris']
# Understanding the data
if dataset.isnull().values.any():
print('There are null in the dataset')
else:
print('There are no nulls in the dataset') # In case nulls are there much more preprocessing is required by replacing nulls with appropriate values
#dataset.info() # To Know the columns in the dataset and types of values and number of values
print(dataset.describe()) # To know min,max,count standard diviation ,varience in each column which would tell us if there is any outliers,normalization or standadization required.
print(dataset.head()) # To view first five columns of the dataset
# Outlier check with the help of histogram
dataset.hist(column = x_labels,bins=20, figsize=(10,5))
# Visualizing the dataset
sns.pairplot(dataset, hue=y_labels[0], size=2.5,markers=["o", "s", "D"])
# Extracting dependent and Independent varibles
X = dataset[x_labels].values
y = dataset[y_labels].values
y = y.ravel() # we would be requiring 1-D array for processing in further code
# Test-Train Split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(y)
y_train = le.transform(y_train)
y_test = le.transform(y_test)
# Building and Training the classifier class
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression()
clf.fit(X_train, y_train) # Trainign the classifier
# Predicting the classes
y_pred = clf.predict(X_test)
# Creating Confusion matrix
y_pred = le.inverse_transform(y_pred)
y_test = le.inverse_transform(y_test)
from sklearn.metrics import confusion_matrix
classes = list(set(y))
cm = confusion_matrix(y_test,y_pred,labels=classes)
print(cm)
# Visualizing confusion matrix
df_cm = pd.DataFrame(cm,index = [i for i in classes],columns = [i for i in classes])
plt.figure(figsize = (10,7))
cm_plot = sns.heatmap(df_cm, annot=True)
cm_plot.set(xlabel='Predicted', ylabel='Actual7')
plt.show()
|
91cdf6b7b67fa470fad661736551b72f350702a5 | motovmp1/basic_python | /function_python.py | 272 | 3.65625 | 4 | # function in Python
def greet_me(name):
print("Dentro da funcao: " + name)
def add_integers(a, b):
result = a + b
#print(result)
#return result
print("Passei por este ponto")
greet_me("Vinicius Pinho")
#add_integers(10, 20)
print(add_integers(10, 20))
|
6e8706930de1075ae63c9e0c2c18bfd2f718fb84 | aaronclong/volunteer-generator | /trie.py | 1,790 | 3.921875 | 4 | """Trie implementation"""
class Trie:
""" Try structure to help sort users more quickly
Will hold a list with 27 indexes
a-z will start and end from 0-25
The 27th index (26) will be space indicating the seperation between firt and last names
"""
def __init__(self):
self.children = {}
self.value = None
def add(self, word, obj):
""" Easier API to load data
"""
return self.add_name(0, word, obj)
def add_index(self, letter):
""" Add an index to the current node
"""
if letter not in self.children:
self.children[letter] = Trie()
return self.children[letter]
def add_name(self, index, name, obj):
""" Recursive name addition
names must be in lower case though
"""
if index >= len(name):
return False
if name.islower() is False:
raise Exception('Names must be in lower case')
letter = ord(name[index])
ref = self.add_index(letter) #reference next trie node in the range
if index == len(name)-1:
ref.value = obj
return True
return ref.add_name(index+1, name, obj)
def search(self, name):
""" Search Trie
names must be in lower case though
Returns False if doesn't exist
Returns stored object once the base is found
"""
if name.islower():
cur = self #curser for node traversal
for letter in name:
num = ord(letter)
if num not in cur.children:
return None
cur = cur.children[num]
return cur.value
else:
raise Exception('Names must be in lower case')
|
88a18d9da1b8033f5aae2953aa23dc4e96171d4a | syeong0204/Python_Challenge | /jupyters_better.py | 964 | 3.59375 | 4 | import os
import csv
import sys
csvpath = os.path.join("budget_data.csv")
print(csvpath)
with open(csvpath) as csvfile:
budgetdata = csv.reader(csvfile, delimiter=",")
next(budgetdata)
budgetlist = list(budgetdata)
file =open("analysis.txt", "w")
text = "Financial analysis \n"
text += "---------------------------------------\n"
text += "Total Months: " + str(len(budgetlist)) + "\n"
totalvalue = sum([int(row[1]) for row in budgetlist])
text += "Total: $" + str(totalvalue)
newlist = [(int(budgetlist[x + 1][1]) - int(budgetlist[x][1])) for x in range(len(budgetlist) -1)]
text += "Average Change: $" + str(round(sum(newlist) / len(newlist),2)) + "\n"
text += "Greatest Increase in Profits: " + budgetlist[newlist.index(max(newlist)) + 1][0] + " $" + str(max(newlist)) + "\n"
text += "Greatest Decrease in Profits: " + budgetlist[newlist.index(min(newlist)) + 1][0] + " $" + str(min(newlist)) + "\n"
file.write(text)
file.close() |
5909e815fa3c0572f4df5d03c64d8a8c08de8e0b | JinleiZhao/note | /threadings/threads.py | 1,370 | 3.71875 | 4 | #线程
import time, threading
lock = threading.Lock()
def loop():
print('Thread %s is running...'%threading.current_thread().name)
for i in range(5):
print('Thread %s >> %s'%(threading.current_thread().name, i))
time.sleep(1)
print('Thread %s ended.'%threading.current_thread().name)
print('Thread %s is running...' %threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('Thread %s ended.' % threading.current_thread().name)
'''666666666666666666666666666666666666666666666666666666666'''
import threading
# 创建全局ThreadLocal对象:
local_school = threading.local()
def process_student():
# 获取当前线程关联的student:
std = local_school.student
print('Hello, %s (in %s)%s' % (std, threading.current_thread().name, time.time()))
def process_thread(name):
# 绑定ThreadLocal的student:
local_school.student = name
time.sleep(1)
process_student()
a = time.time()
thread = []
for i in range(10):
t1 = threading.Thread(target=process_thread, args=('Alice',), name='Thread-%s'%i)
# t2 = threading.Thread(target=process_thread, args=('Bob',), name='Thread-B')
thread.append(t1)
for i in thread:
i.start()
for i in thread:
i.join()
print('end-time:%s'%(time.time()-a))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
|
0f708b95d21e5ca068c4ec39aca0483404629632 | christophmeise/OOP | /lol.py | 373 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 11 09:18:26 2018
@author: D062400
"""
def collatz(n):
liste = []
for i in range(1, n):
innerListe = []
while i > 1:
if (i % 2) == 0:
i = i / 2
else:
i = i*3 + 1
innerListe.append(i)
liste.append(innerListe)
return liste
|
1fde8c17db645850ebcab985c19ba9e5955d3081 | matheuskolln/URI | /Python 3/1146.py | 173 | 3.828125 | 4 | while True:
x = int(input())
if x == 0:
break
for n in range(1, x+1):
if n == x:
print(n)
else:
print(n, end=' ') |
70efc1a488e86fcec6f76db989fd97f468fe5997 | matheuskolln/URI | /Python 3/1049.py | 376 | 3.828125 | 4 | x = input()
y = input()
z = input()
if x == 'vertebrado':
if y == 'ave':
if z == 'carnivoro':
s = 'aguia'
else:
s = 'pomba'
else:
if z == 'onivoro':
s = 'homem'
else:
s = 'vaca'
else:
if y == 'inseto':
if z == 'hematofago':
s = 'pulga'
else:
s = 'lagarta'
else:
if z == 'hematofago':
s = 'sanguessuga'
else:
s = 'minhoca'
print(s) |
fec2bf34d375fd7cf022ccdbfa391ad64940616a | matheuskolln/URI | /Python 3/1045.py | 487 | 3.75 | 4 | a, b, c = map(float, input().split(' '))
aux = 0
if a < c:
aux = a
a = c
c = aux
if a < b:
aux = a
a = b
b = aux
if a >= b + c:
print('NAO FORMA TRIANGULO')
else:
if a ** 2 == b ** 2 + c ** 2:
print('TRIANGULO RETANGULO')
if a ** 2 > b ** 2 + c ** 2:
print('TRIANGULO OBTUSANGULO')
if a ** 2 < b ** 2 + c ** 2:
print('TRIANGULO ACUTANGULO')
if a == b == c:
print('TRIANGULO EQUILATERO')
if a == b != c or a == c != b or b == c != a:
print('TRIANGULO ISOSCELES') |
b3ea1e7ef0acfb8d2f5bbd2b61f45c3f465dde31 | esentemov/hw_python_18 | /calculator_testing/calculator.py | 1,286 | 4.09375 | 4 | class Calculator(object):
"""Класс калькулятора """
def addition(self, x, y):
types_numbers = (int, float, complex)
if isinstance(x, types_numbers) and isinstance(y, types_numbers):
return x + y
else:
return ValueError
def subtraction(self, x, y):
types_numbers = (int, float, complex)
if isinstance(x, types_numbers) and isinstance(y, types_numbers):
return x - y
else:
return ValueError
def multiplication(self, x, y):
types_numbers = (int, float, complex)
if isinstance(x, types_numbers) and isinstance(y, types_numbers):
return x * y
else:
return ValueError
def division(self, x, y):
types_numbers = (int, float, complex)
if isinstance(x, types_numbers) and isinstance(y, types_numbers):
try:
return x / y
except ZeroDivisionError:
return "На ноль делить нельзя"
else:
return ValueError
print(Calculator.addition(Calculator, 7, 6))
print(Calculator.subtraction(Calculator, 10, 2))
print(Calculator.multiplication(Calculator, 10, ' '))
print(Calculator.division(Calculator, 10, 0))
|
f8087e5bf4e1234b7dddf18f6cd7f3612b4563c4 | ElminaIusifova/week1-ElminaIusifova | /04-Swap-Variables**/04.py | 371 | 4.15625 | 4 | # # Write a Python program to swap two variables.
#
# Python: swapping two variables
#
# Swapping two variables refers to mutually exchanging the values of the variables. Generally, this is done with the data in memory.
#
#
# ### Sample Output:
# ```
# Before swap a = 30 and b = 20
# After swaping a = 20 and b = 30
# ```
a=30
b=20
print(a,b)
c=a
a=b
b=c
print(a,b) |
da4cf09617b4a09e36a1afa5ebcb28ae049331fe | ElminaIusifova/week1-ElminaIusifova | /01-QA-Automation-Testing-Program/01.py | 968 | 4.28125 | 4 | ## Create a program that asks the user to test the pages and automatically tests the pages.
# 1. Ask the user to enter the domain of the site. for example `example.com`
# 2. After entering the domain, ask the user to enter a link to the 5 pages to be tested.
# 3. Then display "5 pages tested on example.com".
# 4. Add each page to a variable of type `list` called` tested_link_list`.
# 5. Finally, display `tested pages:` and print the links in the `tested_link_list` list.
siteDomain=input("Please enter domain of the site:")
link1 =input ("Please enter link 1 to be tested:")
link2 =input ("Please enter link 2 to be tested:")
link3 =input ("Please enter link 3 to be tested:")
link4 =input ("Please enter link 4 to be tested:")
link5 =input ("Please enter link 5 to be tested:")
tested_link_list = [link1, link2, link3, link4, link5]
print(siteDomain)
print(tested_link_list)
print("5 pages tested on", siteDomain)
print("tested pages: ", tested_link_list) |
9df66d83233065fb320ae2f5f3a9ef80434055ee | aayushi0402/Python365 | /Day 1.py | 3,189 | 4.53125 | 5 | #What are Python Lists?
#A a valid list can contain Data Types of the following types : Strings, Lists, Tuples, Dictionaries, Sets, Numeric
#How to create Python Lists?
#Following are the ways to create Python Lists
#Method 1:
my_list = ["Hello","Strings",12,99.9,(1,"Tuple"),{"a": "dictionary"}, ["another","list"],{"a","set"}]
print(type(my_list))
#Method 2:
#Using list() function
#From a tuple
my_list2 = list(("a","list","from","tuple"))
print(type(my_list2))
#From a set
#Note that the order of the elements might or might not change randomly
#The abstract concept of a set does not enforce order, so the immplementation is not required to maintain order.
my_list3 = list({"from","a","set","dtype"})
print(type(my_list3))
print(my_list3)
#From a dictionary
my_list4 = list({"only":"dictionary","keys_of_dict":"value","are":"used","list_values":"YEAH!"})
print(type(my_list4))
print(my_list4)
#Question 1:
#Write a Python program to sum all the items in a list
marks_list = [90,91,98,79,68,90,99,87,69]
marks_sum = 0
for item in marks_list:
marks_sum = item + marks_sum
print("Sum of every item in the list:", marks_sum)
#Question 2:
#Write a Python program to multiply all the items in a list.
marks_list = [90,91,98,79,68,90,99,87,69]
marks_prod = 1
for item in marks_list:
marks_prod = marks_prod * item
print("Product of every item in the list:", marks_prod)
#Question 3:
#Write a Python program to get the largest number from a list.
list_items = [1233,4566,789,345,6770,7896,23455,9064,2334]
largest = list_items[0]
for item in list_items:
if item > largest:
largest = item
print("Largest item in the list is:", largest)
#Question 4:
#Write a Python program to get the smallest number from a list.
list_items = [1233,4566,789,345,6770,7896,23455,9064,2334]
smallest = list_items[0]
for item in list_items:
if item < smallest:
smallest = item
print("Smallest item in the list is:", smallest)
#Question 5:
#Write a Python program to count the number of strings where the string length is 2 or more
#and the first and last character are same from a given list of strings.
#Sample List : ['abc', 'xyz', 'aba', '1221']
#Expected Result : 2
stri = "Malayalam"
alist = ["Length","of","strings","Hippopotamus","Dinosaurs","Malayalam","1221"]
count = 0
for item in alist:
if (len(item) > 2) and (item[0].lower() == item[len(item) - 1].lower()):
count = count + 1
print(count)
#Question 6:
#Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.
#Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
#Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
unsort = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
first = []
second = []
sort_list = []
for item in unsort:
first.append(item[0])
second.append(item[1])
for item in unsort:
sort_list.append((first[second.index(min(second))],min(second)))
del first[second.index(min(second))]
del second[second.index(min(second))]
print(sort_list)
#Alternate way of doing it
print(sorted(unsort,key=lambda x:x[1])) |
090ce23803d6268131fbd6bcefa9774a702a368e | gauravdal/write_config_in_csv | /python_to_csv.py | 1,199 | 3.875 | 4 | import json
import csv
#making columns for csv files
csv_columns = ['interface','mac']
#Taking input from json file and converting it into dictionary data format
with open('mac_address_table_sw1','r') as read_mac_sw1:
fout = json.loads(read_mac_sw1.read())
print(fout)
#naming a csv file
csv_file = 'names.csv'
try:
with open(csv_file,'w') as csvfile:
#DictWriter function creates an object and maps dictionary onto output rows.
# fieldnames fieldnames parameter is a sequence of keys that identify the
# order in which values in the dictionary passed to the writerow() method are written to file "csv_file"
# extrasaction : If the dictionary passed to the writerow() method contains a key not found in fieldnames,
# the optional extrasaction parameter indicates what action to take. If it is set to 'raise', the default
# value, a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored.
writer = csv.DictWriter(csvfile, fieldnames=csv_columns, extrasaction='ignore')
writer.writeheader()
for data in fout:
writer.writerow(data)
except IOError:
print('I/O error') |
a2229d5d7d63fa271fd365af5b4891f6c9412ea5 | scriptclump/algorithms | /small-program/prime_number.py | 213 | 4.0625 | 4 | def primeNumber(num):
if (num > 1):
for i in range(2, num):
if(num % i == 0):
print('{0} is prime number'.format(num))
break
else:
print('{0} is not a prime number'.format(num))
primeNumber(6) |
9c333b3055ed6e776404509c97e70998e389804d | scriptclump/algorithms | /sortings/recurssive_bubble_sort.py | 389 | 3.921875 | 4 | def bubble_sort(arr):
for i, val in enumerate(arr):
try:
if arr[i+1] < val:
arr[i] = arr[i+1]
arr[i+1] = val
bubble_sort(arr)
except IndexError:
pass
return arr
arr = [12,11,44,23,55,1,4,54]
print("Unsorted array", arr)
sorted_arr = bubble_sort(arr)
print("Sorted array", sorted_arr)
|
7e0a2b6644640412aceefb06af083539e083bdf3 | Dilan/projecteuler-net | /problem-051.py | 2,187 | 3.890625 | 4 | # By replacing the 1st digit of the 2-digit number *3,
# it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
# By replacing the 3rd and 4th digits of 56**3 with the same digit,
# this 5-digit number is the first example having seven primes among the ten generated numbers,
# yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993.
# Consequently 56003, being the first member of this family, is the smallest prime with this property.
# Find the smallest prime which, by replacing part of the number
# (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.
import time
ti=time.time()
def primes(limit):
list = [False, False] + map(lambda x: True, range(2, limit))
for i, is_prime in enumerate(list):
if is_prime:
yield i
for n in range(i*i, limit, i):
list[n] = False
class Num():
val = None
arr = None
size = None
def __init__(self, val):
self.val = val
self.arr = list(str(val))
self.size = len(self.arr)
class Statistics():
storage = {}
def to_storage(self, mask, num):
if mask in self.storage:
self.storage[mask]["counter"] += 1
self.storage[mask]["items"].append(num)
else:
self.storage[mask] = { "counter": 1, "items": [num] }
def add(self, num, n=0, digit=None, mask=None):
if mask is None:
mask = num.arr[:]
for i in range(n, num.size-1):
if n == 0 or digit == num.arr[i]:
mask[i] = '*'
self.to_storage(''.join(mask), num.val)
if (i+1) < num.size:
self.add(num, i+1, num.arr[i], mask)
mask[i] = num.arr[i]
def solution():
stat = Statistics()
for prime in primes(1000000):
stat.add(Num(prime))
for k in stat.storage:
if stat.storage[k]['counter'] == 8:
return stat.storage[k]['items'][0]
return None
print 'Answer is:', solution(), '(time:', (time.time()-ti), ')'
|
0d284f9890525066151f05669956630987970410 | Dilan/projecteuler-net | /problem-058.py | 2,265 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
# 37 36 35 34 33 32 31
# 38 17 16 15 14 13 30
# 39 18 5 4 3 12 29
# 40 19 6 1 2 11 28
# 41 20 7 8 9 10 27
# 42 21 22 23 24 25 26
# 43 44 45 46 47 48 49
# It is interesting to note that the odd squares lie along the bottom right diagonal,
# but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime;
# that is, a ratio of 8/13 ≈ 62%.
# If one complete new layer is wrapped around the spiral above,
# a square spiral with side length 9 will be formed.
# If this process is continued, what is the side length of the square spiral
# for which the ratio of primes along both diagonals first falls below 10%?
import numpy
import time
ti=time.time()
def prime_list(n):
sieve = numpy.ones(n/3 + (n%6==2), dtype=numpy.bool)
for i in xrange(1,int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k/3 ::2*k] = False
sieve[k*(k-2*(i&1)+4)/3::2*k] = False
return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]
def build_primes(limit):
hm = { }
for prime in prime_list(limit):
hm[int(prime)] = True
return hm
def solution():
primes = build_primes(800000000)
total_in_diagonals = 1
primes_in_diagonals = 0
last_num = 1
side = 1
ratio = 1.0
while float(ratio) >= float(1.0/10.0):
corner_1 = last_num + (side + 1)
corner_2 = corner_1 + (side + 1)
corner_3 = corner_2 + (side + 1)
last_num = corner_3 + (side + 1)
total_in_diagonals += 4
side += 2
if corner_1 in primes:
primes_in_diagonals += 1
if corner_2 in primes:
primes_in_diagonals += 1
if corner_3 in primes:
primes_in_diagonals += 1
if last_num in primes:
primes_in_diagonals += 1
ratio = float(primes_in_diagonals)/float(total_in_diagonals)
# print 'ratio:', ratio, primes_in_diagonals, '/', total_in_diagonals
# print 'last_num:', last_num
return side
print 'Answer is:', solution(), '(time:', (time.time()-ti), ')' |
563c9c6658a045bee7b35b510f706a1ae17039b8 | Dilan/projecteuler-net | /problem-057.py | 1,482 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# It is possible to show that the square root of two can be expressed as an infinite continued fraction.
# √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
# By expanding this for the first four iterations, we get:
# 1 + 1/2 = 3/2 = 1.5
# 1 + 1/(2 + 1/2) = 7/5 = 1.4
# 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
# 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
# The next three expansions are 99/70, 239/169, and 577/408,
# but the eighth expansion, 1393/985, is the first example where
# the number of digits in the numerator exceeds the number of digits in the denominator.
# In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
import time
ti=time.time()
def sum_up(a, fraction): # a + b/c
# print a, '+', b, '/', c, ' = ', (c * a + b), '/', c
b = fraction[0]
c = fraction[1]
return ((c * a + b), c)
def plus1(fraction): # a + b/c
return sum_up(1, fraction)
def swap(fraction): # a + b/c
return (fraction[1], fraction[0])
def is_length_different(x, y):
return len(str(x)) != len(str(y))
def solution(length):
counter = 0
prev = (3, 2)
while length > 0:
# 1 + 1 / (prev)
prev = sum_up(1, swap(plus1(prev)))
if is_length_different(prev[0], prev[1]):
counter += 1
length -= 1
return counter
print 'Answer is:', solution(1000), '(time:', (time.time()-ti), ')'
|
b73e5e51e531658b2fc6e778652cca63651e6dc9 | Dilan/projecteuler-net | /problem-050.py | 1,557 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The prime 41, can be written as the sum of six consecutive primes:
#
# 41 = 2 + 3 + 5 + 7 + 11 + 13
# This is the longest sum of consecutive primes that adds to a prime below one-hundred.
#
# The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
#
# Which prime, below one-million, can be written as the sum of the most consecutive primes?
def sieve_of_eratosthenes(limit):
list = [False,False] + [True for i in range(2,limit)]
for i, is_prime in enumerate(list):
if is_prime:
yield i
for i in range(i*i, limit, i):
list[i] = 0
# consecutive_primes_sum
# [5, 7, 11, 13]:
# (5, 5+7, 5+7+11, 5+7+11+13)
# ( 7, 7+11, 7+11+13)
# ( 11, 11+13)
# ( 13)
def consecutive_sums(l):
result = {}
prev = []
for num in l:
tail = prev[:]
prev = [num]
result[num] = 1
for i, x in enumerate(tail):
result[num + x] = i + 2
prev.append(num + x)
return result
def solve():
prime_numbers = list(sieve_of_eratosthenes(1000000))
sums = consecutive_sums(prime_numbers[0:550]) # max sum ~ 1.000.000
answer = None
max_sequence = 0
for num in prime_numbers[::-1]:
if num < 100000:
break
if num in sums:
if max_sequence < sums[num]:
max_sequence = sums[num]
answer = num
return answer
print solve() |
5b75f751142a34486e920527e7bd0ec0d0de4727 | LieutenantDanDan/snake | /snake.py | 3,380 | 3.65625 | 4 | import random
import time
class Snake:
snake = []
board = []
width = 0
height = 0
food = (None, None)
def __init__(self, height, width):
random.seed(555)
self.height = height
self.width = width
for i in range(height):
self.board.append([' '] * width)
self.snake.append((random.randrange(width), random.randrange(height)))
self.food = (random.choice([x for i, x in enumerate(range(height)) if i != self.snake[0][1]]),random.choice([x for i, x in enumerate(range(height)) if i != self.snake[0][0]]) )
self.board[self.snake[0][1]][self.snake[0][0]] = 's'
self.board[self.food[1]][self.food[0]] = 'f'
def __str__(self):
string = '-' * (self.width + 2) + '\n'
for line in self.board:
string += '|'
string += ''.join(line)
string += '|\n'
string += '-' * (self.width + 2)
return string
def update_board(self):
board = []
for i in range(self.height):
board.append([' '] * self.width)
for segments in self.snake:
board[segments[1]][segments[0]] = 's'
board[self.food[1]][self.food[0]] = 'f'
self.board = board
def next_state(self, new_head):
if self.game_over(new_head):
print('uh oh! snake ded')
return False
self.snake.insert(0, new_head)
if new_head == self.food:
self.new_food()
else:
self.snake.pop()
print(self.snake)
self.update_board()
return True
def trigger_move(self, direction):
if direction not in list(self.directions().keys()):
print("invalid move!")
return True
new_head = self.move(direction)
return self.next_state(new_head)
def random_move(self):
direction = random.choice(list(self.directions().keys()))
print("randomly moving " + direction)
new_head = self.move(direction)
return self.next_state(new_head)
def directions(self):
return {
'up': (0, -1),
'down': (0, +1),
'left': (-1, 0),
'right': (1, 0),
'w': (0, -1),
's': (0, +1),
'a': (-1, 0),
'd': (1, 0)
}
def move(self, direction):
head = self.snake[0]
return (head[0] + self.directions()[direction][0], head[1] + self.directions()[direction][1])
def game_over(self, new_head):
if new_head in self.snake:
return True
if new_head[0] < 0 or new_head[1] < 0:
return True
if new_head[0] > self.width or new_head[1] > self.height:
return True
return False
def new_food(self):
valid = []
for i in range(self.width):
for j in range(self.height):
valid.append((i, j))
valid = set(valid)
snake = set(self.snake)
valid = valid - snake
self.food = random.choice(list(valid))
def eat_block(self):
return
if __name__ == "__main__":
s = Snake(10, 20)
print(s)
print(s.snake)
play = True
while play:
direction = input()
print("you input: " + str(direction))
play = s.trigger_move(direction)
print(s)
|
f197017c4a97aa27b19770e4db6bb93f3186d12b | klimarichard/project_euler | /src/problems_51-75/53_combinatoric_selections.py | 844 | 3.640625 | 4 | def find_combinations(upper, lower=1, threshold=1):
"""
Find all combinatoric selections within given range.
:param upper: upper bound
:param lower: optional lower bound (default=1)
:param threshold: optional, only list selections greater than threshold (default=1)
:return: list of combinatoric selections
"""
selections = []
for n in range(lower, upper + 1):
for k in range(1, n + 1):
current = factorials[n] // (factorials[k] * factorials[n - k])
if current > threshold:
selections.append(current)
return selections
factorials = [1, 1]
# building the list of factorials, so we don't need to recompute them every time
for i in range(2, 101):
factorials.append(i * factorials[-1])
print(len(find_combinations(100, lower=23, threshold=1000000)))
|
428e563df3b6db99b2b4f78bf3e9a62bc807fc24 | klimarichard/project_euler | /src/problems_51-75/68_magic_5-gon_ring.py | 2,325 | 3.796875 | 4 | from itertools import combinations, permutations
def find_magic_5gons(numbers):
"""
Find all 5-gons containing numbers from the set.
:param numbers: a set of numbers
:return: all possible 5-gons
"""
five_gons = []
combs = combinations(numbers, 5)
for c in combs:
# we want the largest possible outer ring, so we want
# all small numbers in the inner ring
if max(c) != 5:
continue
# inner ring of the 5-gon, starting at the top
# and going clockwise
perms1 = permutations(c)
for j in perms1:
ring = []
for i in range(5):
ring.append(j[i])
remaining = numbers - set(ring)
perms = permutations(remaining)
for p in perms:
# outer ring of the 5-gon, starting at the top left
# and going clockwise
outer = []
for i in range(5):
outer.append(p[i])
if validate_ring(ring, outer):
five_gons.append(construct_string(ring, outer))
return five_gons
def validate_ring(ring, outer):
"""
Checks, if given 5-gon ring is magic, meaning that each line adds
to the same number.
:param ring: inner ring of the 5-gon
:param outer: outer ring of the 5-gon
:return: True, if 5-gon ring is magic, False, otherwise
"""
first_sum = outer[0] + ring[0] + ring[1]
# three middle lines
for i in range(1, len(ring) - 1):
if outer[i] + ring[i] + ring[i + 1] != first_sum:
return False
# last line
if outer[len(ring) - 1] + ring[len(ring) - 1] + ring[0] != first_sum:
return False
return True
def construct_string(ring, outer):
"""
Construct unique string for given 5-gon ring.
:param ring: inner ring of the 5-gon
:param outer: outer ring of the 5-gon
:return: string representation of 5-gon ring
"""
ls = []
min_index = outer.index(min(outer))
for i in range(5):
ls.append(outer[(min_index + i) % 5])
ls.append(ring[(min_index + i) % 5])
ls.append(ring[(min_index + (i + 1)) % 5])
return ''.join([str(x) for x in ls])
numbers = {i for i in range(1, 11)}
print(max(find_magic_5gons(numbers)))
|
d4ad193e97126530ae6c33104ca43670894c97b5 | klimarichard/project_euler | /src/problems_51-75/75_singular_integer_right_triangles.py | 1,344 | 4.03125 | 4 | # we can generate primitive Pythagorean triples and their multiples,
# until we reach the limit
# we will use Euclid's formula for generating the primitive triples:
# - we have m, n coprimes, where m > n, exactly one of m, n is even, then
# - a = m^2 - n^2
# - b = 2mn
# - c = m^2 + n^2
# - perimeter p = a + b + c = m^2 - n^2 + 2mn + m^2 + n^2 = 2m(m + n)
#
# - this means, that p >= 2m(m + 1), so when 2m(m + 1) reaches the limit,
# we can stop searching
from algorithms import gcd
def find_triples(limit):
"""
Find Pythagorean triples with perimeters up to given limit.
:param limit: limit for the perimeter
:return: a list containing information about how many Pythagorean triples
were found for each perimeter below the limit
"""
perimeters = [0 for _ in range(limit + 1)]
m = 2
while 2 * m * (m + 1) < limit:
for n in range(1, m):
if (m + n) % 2 == 1 and gcd(m, n) == 1:
p = 2 * m * (m + n)
i = 1
# generating non-primitive triples (multiples of this triple)
while p * i < limit:
perimeters[i * (2 * m * (m + n))] += 1
i += 1
m += 1
return perimeters
perimeters = find_triples(1500000)
print(len([1 for i in perimeters if i == 1]))
|
04e3feede860b7798f1cccf2548dae6a37001027 | klimarichard/project_euler | /src/problems_51-75/65_convergents_of_e.py | 848 | 3.96875 | 4 | def compute_nth_iteration(n):
"""
Computes n-th iteration of continued fraction for e,
2 + (1 / (1 + 1 / (2 + 1 / (1 + 1 / (1 + 1 / (4 + ...))))))
:param n: an integer
:return: numerator and denominator of n-th iteration
"""
# generating sequence for continued fraction of e
# [1, 2, 1, 1, 4, 1, 1, 6, 1, ..., 1, 2k, 1, ...]
e_sequence = [1 for _ in range(n)]
for i in range(n):
if i % 3 == 1:
e_sequence[i] = (i // 3 + 1) * 2
num = 1
denom = e_sequence[n - 1]
# we have to compute the fraction from inside out
for i in range(n - 1):
num = denom * e_sequence[n - (i + 2)] + num
num, denom = denom, num
# add the final two
num = denom * 2 + num
return num, denom
num, _ = compute_nth_iteration(99)
print(sum([int(x) for x in str(num)]))
|
d7579f80023f2fe443bff2c8fbd43e3243ca388b | klimarichard/project_euler | /src/problems_76-100/87_prime_power_triples.py | 793 | 3.734375 | 4 | from algorithms import eratosthenes
def prime_power_triples(n):
"""
Find all numbers in given range, that can be written as a sum of a squared prime,
a cubed prime and a prime to the power of four.
:param n: upper limit
:return: list of numbers that can be written in such way
"""
primes = eratosthenes(int(n ** 0.5) + 1)
squares = [p ** 2 for p in primes if p ** 2 < n]
cubes = [p ** 3 for p in primes if p ** 3 < n]
fourths = [p ** 4 for p in primes if p ** 4 < n]
satisfying = set()
for s in squares:
for c in cubes:
for f in fourths:
if s + c + f > n:
break
satisfying |= {s + c + f}
return sorted(set(satisfying))
print(len(prime_power_triples(50000000)))
|
93d5e72b4a15da9a9be4f6a1ff219cf1314ee392 | klimarichard/project_euler | /src/problems_51-75/62_cubic_permutations.py | 534 | 3.6875 | 4 | from algorithms import gen_powers
cubes = gen_powers(3)
perms = {}
found = False
while not found:
current = next(cubes)
# find largest permutation of current cube (used as key in dictionary)
current_largest = ''.join(sorted([x for x in str(current)], reverse=True))
if current_largest not in perms.keys():
perms[current_largest] = [1, current]
else:
perms[current_largest][0] += 1
if perms[current_largest][0] == 5:
print(perms[current_largest][1])
found = True
|
4ae3ee90a0eb7d7dc3c8132e77d912eebbb42986 | klimarichard/project_euler | /src/problems_1-25/02_even_fibonacci_numbers.py | 439 | 3.9375 | 4 | from algorithms import gen_fibs
def sum_of_even_fibs(n):
"""
Returns sum of all even Fibonacci numbers up to given bound.
:param n: upper bound
:return: sum of even Fibonacci numbers lesser than n
"""
f = gen_fibs()
next_fib = next(f)
sum = 0
while next_fib < n:
if next_fib % 2 == 0:
sum += next_fib
next_fib = next(f)
return sum
print(sum_of_even_fibs(4000000))
|
34517033c09ac9a5553694024233868fde06d06b | klimarichard/project_euler | /src/problems_76-100/80_square_root_digital_expansion.py | 704 | 3.765625 | 4 | from decimal import Decimal, getcontext
from algorithms import gen_powers
def compute_decimal_digits(n, k):
"""
Computes first k digits of square root of n.
:param n: an integer
:param k: number of decimal digits
:return: first k decimal digits of square root of n
"""
digits = str(Decimal(n).sqrt()).replace('.', '')[:100]
return map(int, digits)
getcontext().prec = 102
gen_squares = gen_powers(2)
squares = [next(gen_squares)]
while squares[-1] < 100:
squares.append(next(gen_squares))
sum_of_digits = 0
for i in range(100):
if i not in squares:
digits = compute_decimal_digits(i, 100)
sum_of_digits += sum(digits)
print(sum_of_digits)
|
a95e569efdb37dbe4fbb974ac652d74170a59624 | klimarichard/project_euler | /src/problems_26-50/34_digit_factorials.py | 526 | 4 | 4 | from algorithms import fact
def find_digit_factorials():
"""
Find all numbers which are equal to the sum of the factorial of their digits.
:return: list of all such numbers
"""
df = []
factorials = [fact(i) for i in range(10)]
# upper bound is arbitrary, but I couldn't find it analytically
for i in range(10, 1000000):
fact_digits = [factorials[int(x)] for x in str(i)]
if sum(fact_digits) == i:
df.append(i)
return df
print(sum(find_digit_factorials()))
|
f3c5ec72cdba045f43d657d5b30cf2ae51a1c293 | klimarichard/project_euler | /src/problems_26-50/36_double-base_palindromes.py | 462 | 3.9375 | 4 | from algorithms import palindrome
def find_double_based_palindromes(n):
"""
Find double-based palindromes in given range.
:param n: upper bound
:return: list of all double-based palindromes
"""
dbp = []
for i in range(n):
if i % 10 == 0:
continue
if palindrome(i):
if palindrome(bin(i)[2:]):
dbp.append(i)
return dbp
print(sum(find_double_based_palindromes(1000000)))
|
a9ab45d85f900abace366094ffcdae724664ed2a | NasBeru/IRS_PROJECT | /recommendation_system/data_lnsert.py | 6,169 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import pymysql
class BookSqlTools:
# 链接MYSQL数据库
# 读取出来转化成pandas的dataframe格式
def LinkMysql(self, sql):
print('正在连接====')
try:
connection = pymysql.connect(user="root",
password="19980420",
port=3306,
host="127.0.0.1", # 本地数据库 等同于localhost
db="Book",
charset="utf8")
cur = connection.cursor()
except Exception as e:
print("Mysql link fail:%s" % e)
try:
cur.execute(sql)
except Exception as e:
print("dont do execute sql")
try:
result1 = cur.fetchall()
title1 = [i[0] for i in cur.description]
Main = pd.DataFrame(result1)
Main.columns = title1
except Exception as e:
print(" select Mysql error:{}".format(e))
return Main
# 数据库中的表插入数据
def UpdateMysqlTable(self, data, sql_qingli, sql_insert):
try:
connection = pymysql.connect(user="root",
password="19980420",
port=3306,
host="127.0.0.1", # 本地数据库 等同于localhost
db="Book",
charset="utf8")
cursor = connection.cursor()
except Exception as e:
print("Mysql link fail:%s" % e)
try:
cursor.execute(sql_qingli)
except:
print("dont do created table sql")
try:
for i in data.index:
x = list(pd.Series(data.iloc[i,].astype(str)))
sql = sql_insert.format(tuple(x)).encode(encoding='utf-8')
print(sql)
try:
cursor.execute(sql)
except Exception as e:
print("Mysql insert fail%s" % e)
except Exception as e:
connection.rollback()
print("Mysql insert fail%s" % e)
connection.commit()
cursor.close()
connection.close()
connection = pymysql.connect(user="root",
password="19980420",
port=3306,
host="127.0.0.1", # 本地数据库 等同于localhost
charset="utf8")
cur = connection.cursor()
cur.execute('DROP DATABASE if exists Book')
cur.execute('CREATE DATABASE if not exists Book')
connection.commit()
cur.close()
# 创建购物车表
connection = pymysql.connect(user="root",
password="19980420",
port=3306,
db="Book",
host="127.0.0.1",
charset="utf8")
cur = connection.cursor()
createCartSql = '''CREATE TABLE Cart
(Id int primary key not null auto_increment,
UserID VARCHAR(100) ,
BookID VARCHAR(100))'''
cur.execute(createCartSql)
connection.commit()
cur.close()
connection.close()
BookInfoInsert = BookSqlTools()
# --------------------------------------------------------------------------
# 读取本地的book1-100k.csv文件 在数据库中建一个Books表 将book.csv内容插入到数据库中
# --------------------------------------------------------------------------
path = '../data/book1-100k.csv'
Book = pd.read_csv(path, sep=",", encoding="ISO-8859-1", error_bad_lines=False)
createBooksSql = ''' CREATE TABLE Books
(Id INT PRIMARY KEY,
Name VARCHAR(999) ,
RatingDist1 VARCHAR(999) ,
pagesNumber INT ,
RatingDist4 VARCHAR(999) ,
RatingDistTotal VARCHAR(999) ,
PublishMonth INT ,
PublishDay INT ,
Publisher VARCHAR(999) ,
CountsOfReview INT ,
PublishYear INT ,
Language VARCHAR(999) ,
Authors VARCHAR(999) ,
Rating FLOAT,
RatingDist2 VARCHAR(999) ,
RatingDist5 VARCHAR(999) ,
ISBN VARCHAR(999) ,
RatingDist3 VARCHAR(999));'''
BooksSql_insert = 'insert into Books (Id,Name,RatingDist1,pagesNumber,RatingDist4,RatingDistTotal,PublishMonth,PublishDay,Publisher,CountsOfReview,PublishYear,Language,Authors,Rating,RatingDist2,RatingDist5,ISBN,RatingDist3) values {}'
BookInfoInsert.UpdateMysqlTable(Book, createBooksSql, BooksSql_insert)
del Book
# --------------------------------------------------------------------------
# 读取本地的ratings_csv文件 在数据库中建一个Bookrating表 将bookrating.csv内容插入到数据库中
# --------------------------------------------------------------------------
path = '../data/ratings_csv.csv'
Rating = pd.read_csv(path, sep=",", encoding="ISO-8859-1", error_bad_lines=False)
createBookratingSql = '''CREATE TABLE Bookrating
(Id int primary key not null auto_increment,
User_Id INT ,
Name INT,
Rating INT);'''
BookratingSql_insert = 'insert into Bookrating (User_Id, Name, Rating) values {}'
BookInfoInsert.UpdateMysqlTable(Rating, createBookratingSql, BookratingSql_insert)
del Rating
|
a6f3a4c377816302913a0b15d534cf09490395e9 | ymdt142/Search-files-and-folder-using-python | /fns.py | 614 | 3.953125 | 4 | import os
def searchfolder(a):
c=input("Search in")
os.chdir(c)
for path, dirnames, files in os.walk(c):
for file in dirnames:
if file==a:
print("found file")
print(path)
def searchfile(a):
c=input("Search in")
os.chdir(c)
for path, dirnames, files in os.walk(c):
for file in files:
if file==a:
print("found file")
print(path)
b=input("1:search folder OR 2:Search files:-")
a=input("Enter name")
if b=="1":
searchfolder(a)
elif b=="2":
searchfile(a)
|
1233fb6db537375f7fee234f54f3c67bb6012933 | bereczb/trial-exam-python | /2.py | 797 | 3.78125 | 4 | # Create a function that takes a filename as string parameter,
# and counts the occurances of the letter "a", and returns it as a number.
# It should not break if the file does not exist, just return 0.
def counter(name_of_file):
try:
f = open(name_of_file, 'r')
text_list = f.readlines()
f.close()
except:
return 0
letter_a_in_file = 0
for i in range(len(text_list)):
for j in range(len(text_list[i])):
if text_list[i][j] == 'a':
letter_a_in_file += 1
return letter_a_in_file
# letter_a_in_filename = 0
#
# for i in range(len(name_of_file)):
# if name_of_file[i] == 'a':
# letter_a_in_filename += 1
#
# return letter_a_in_filename
print(counter('test_a.txt'))
|
08d99476bdc41ba3da11a293aee6d8236285bde3 | isaacmm110/Projeto01 | /Translator.py | 630 | 3.890625 | 4 |
def translate(phrase):
letter1 = input("Enter the letter which all the vocals will turn on: ")
letter2 = input("Enter the letter which all the r will be changed: ")
translation2 = ""
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
translation = translation + letter1
else:
translation = translation + letter
for letter in translation:
if letter in "Rr":
translation2 = translation2 + letter2
else:
translation2 = translation2 + letter
return translation2
print(translate(input("")))
|
fee7b252fcbfa29968ec94308e5f4040ef67381f | nytaoxu/Flask_API | /code/models/user.py | 1,090 | 3.609375 | 4 | import sqlite3
DATABASE_NAME = "data.db"
class UserModel:
def __init__(self, _id, username, password):
self.id = _id
self.username = username
self.password = password
@classmethod
def find_by_username(cls, username):
with sqlite3.connect(DATABASE_NAME) as connection:
cursor = connection.cursor()
find_username_query = "SELECT * FROM users WHERE username=?"
result = cursor.execute(find_username_query, (username, ))
row = result.fetchone()
if row:
user = cls(*row)
else:
user = None
return user
@classmethod
def find_by_id(cls, _id):
with sqlite3.connect(DATABASE_NAME) as connection:
cursor = connection.cursor()
find_id_query = "SELECT * FROM users WHERE id=?"
result = cursor.execute(find_id_query, (_id, ))
row = result.fetchone()
if row:
user = cls(*row)
else:
user = None
return user
|
3c8802f63b9ff336168a750a2d82e7e42c6ee7ec | Chou-Qingyun/Python006-006 | /week06/p5_1classmethod.py | 2,320 | 4.25 | 4 | # 让实例的方法成为类的方法
class Kls1(object):
bar = 1
def foo(self):
print('in foo')
# 使用类属性、方法
@classmethod
def class_foo(cls):
print(cls.bar)
print(cls.__name__)
cls().foo()
# Kls1.class_foo()
########
class Story(object):
snake = 'python'
# 初始化函数,并非构造函数。构造函数: __new__()
def __init__(self, name):
self.name = name
# 类的方法
@classmethod
def get_apple_to_eve(cls):
return cls.snake
s = Story('anyone')
# get_apple_to_eve 是bound方法,查询顺序先找s的__dict__是否有get_apple_to_eve,如果没有,查类Story
print(s.get_apple_to_eve)
# 类和实例都可以使用
print(s.get_apple_to_eve())
print(Story.get_apple_to_eve())
#####################
class Kls2():
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def print_name(self):
print(f'first name is {self.fname}')
print(f'last name is {self.lname}')
me = Kls2('qingyun','chow')
me.print_name()
# 修改输入为 qingyun-chow
# 解决方法1:修改__init__()
# 解决方法2: 增加__new__构造函数
# 解决方法3: 增加 提前处理的函数
def pre_name(obj,name):
fname, lname = name.split('-')
return obj(fname, lname)
me2 = pre_name(Kls2, 'qingyun-chow')
#####
class Kls3():
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
@classmethod
def pre_name(cls,name):
fname, lname = name.split('-')
return cls(fname, lname)
def print_name(self):
print(f'first name is {self.fname}')
print(f'last name is {self.lname}')
me3 = Kls3.pre_name('qingyun-chow')
me3.print_name()
#########
class Fruit(object):
total = 0
@classmethod
def print_total(cls):
print(cls.total)
print(id(Fruit.total))
print(id(cls.total))
@classmethod
def set(cls, value):
print(f'calling {cls}, {value}')
cls.total = value
class Apple(Fruit):
pass
class Orange(Fruit):
pass
Apple.set(100)
# calling <class '__main__.Apple'>, 100
Orange.set(200)
org = Orange()
org.set(300)
# calling <class '__main__.Orang'>, 300
Apple.print_total()
Orange.print_total()
|
87033b460c1943e78a137d2bc0caae0c51f9293c | jmflynn81/advent-of-code-2020 | /01/calculate_expense.py | 691 | 3.8125 | 4 | import itertools
def add_em(a):
sum = 0
for item in list(a):
sum = sum + int(item)
return sum
def multiply_em(a):
product = 1
for item in list(a):
product = product * int(item)
return product
def get_values(size_of_set, expense_list):
combinations = itertools.combinations(expense_list, size_of_set)
for item in combinations:
if add_em(item) == 2020:
print(item)
print(multiply_em(item))
def get_expense_list():
with open('expense') as f:
expense_list = f.read().splitlines()
return expense_list
expense_list = get_expense_list()
get_values(2, expense_list)
get_values(3, expense_list)
|
e9b5367c1302a02b9323458f2c6e6747f485248a | ljs-cxm/algorithm | /select_sort.py | 331 | 3.5625 | 4 | from check import check_func
def select_sort_func(nums):
n = len(nums)
for i in range(n-1):
min = i
for j in range(i+1, n):
if nums[min] > nums[j]:
min = j
nums[i], nums[min] = nums[min], nums[i]
return nums
if __name__ == '__main__':
check_func(select_sort_func) |
3570330e75fab9747d1865f6298163ead45b8263 | uwhwan/python_study | /test/selectionSort.py | 428 | 3.640625 | 4 | #选择排序
from randomList import randomList
iList = randomList(20)
def selectionsort(iList):
if len(iList) <= 1:
return iList
for i in range(0,len(iList)-1):
if iList[i] != min(iList[i:]):
minIndex = iList.index(min(iList[i:]))
iList[i],iList[minIndex] = iList[minIndex],iList[i]
return iList
if __name__ == '__main__':
print(iList)
print(selectionsort(iList)) |
9c6ab989761682252642271f09bcb45a62266476 | sunny0212452/CodingTraining | /s.py | 895 | 3.75 | 4 | # -*- coding:utf-8 -*-
#将字符串中的空格替换成%20
def replaceSpace(s):
# write code here
l = len(s)
print 'l:',l
num_blank=0
for i in s:
if i==' ':
num_blank+=1
l_new = l+num_blank*2
print 'l_new:',l_new
index_old = l-1
index_new = l_new
s_new=[' ']*l_new
while(index_old >= 0 and index_new > index_old):
if s[index_old]==' ':
#index_new-=1
s_new[index_new-1]='0'
#index_new-=1
s_new[index_new-2]='2'
#index_new-=1
s_new[index_new-3]='%'
index_new-=3
else:
print index_new
s_new[index_new-1]=s[index_old]
index_new-=1
index_old-=1
ss=''
print s_new
for i in s_new:
ss+=str(i)
return ss
s='We are happy.'
print "s:",s
s1=replaceSpace(s)
print "s1:",s1 |
fba35b9f3c384df1768ce9f0500536a3dc0c1e2d | AshutoshInfy/Python_Selector | /list_sorting.py | 215 | 3.875 | 4 | # sorting the list
def sort_list(sam_list):
# sort the list
sam_list.sort()
return sam_list
# print new sorted list
new_list = [1,2,8,9,4,3,2]
sorted_list = sort_list(new_list)
print('Sorted list:', sorted_list) |
3f2e1e7f00004e07ed45b0499bfcacb873d6ef92 | CodedQuen/python_begin1 | /simple_database.py | 809 | 4.34375 | 4 | # A simple database
people = {
'Alice': {
'phone': '2341',
'addr': 'Foo drive 23'
},
'Beth': {
'phone': '9102',
'addr': 'Bar street 42'
},
'Cecil': {
'phone': '3158',
'addr': 'Baz avenue 90'
}
}
# Descriptive lables for the phone number and address.
labels = {
'phone': 'phone number',
'addr': 'address'
}
name = input('Name:')
# Are we looking for a phone number or an address?
request = input('Phone number (p) or address (a)?')
# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Only try to print information if the name is a valid key in our dictionary:
if name in people:
print ("%s's %s is %s." % (name, labels[key], people[name][key]))
|
d16499e85a3ce89f60adaff02b043075e876b308 | ArnthorDadi/Kattis | /NumberFun.py | 368 | 3.921875 | 4 | n = int(input(""))
for i in range(n):
x, y, z = input("").split(" ")
x = int(x)
y = int(y)
z = int(z)
if(x+y == z):
print("Possible")
elif(x-y == z or y-x == z):
print("Possible")
elif(x/y == z or y/x == z):
print("Possible")
elif(x*y == z):
print("Possible")
else:
print("Impossible") |
fb49ab4a7a2703dd82c68819f2862444954776f2 | kininge/Algoritham-Study | /matrixMultiplication.py | 826 | 3.625 | 4 | def bruteForceWay(matrixA, matrixB):
rowsA= len(matrixA)
rowsB= len(matrixB)
columns= len(matrixB[0])
matrixAnswer= []
#For loop to choose row of matrixA
for index in range(rowsA):
row= []
#For loop to choose columns in matrixB
for index_ in range(columns):
answerElement= 0
# For loop to choose rows of matrixB
for index__ in range(rowsB):
answerElement+= matrixA[index][index__]* matrixB[index__][index_]
row.append(answerElement)
matrixAnswer.append(row)
return matrixAnswer
if __name__== '__main__':
matrixA= [[2, 1, 4, 4], [0, 1, 1, 2], [0, 4, -1, 2]]
matrixB= [[6, 1], [3, 1], [-1, 0], [-1, -2]]
answer= bruteForceWay(matrixA, matrixB)
print(answer) |
2c217215bc105cf3622113c0ee457b89409ed8ce | johnhuzhy/MyPythonExam | /src/junior/practice_forth.py | 1,312 | 4.0625 | 4 | """
1.正整数を入力して、それが素数かどうかを判別します。
素数は、1とそれ自体でのみ除算できる1より大きい整数を指します。
"""
from math import sqrt
print('*'*33)
num = int(input('正整数を入力してください:'))
if num > 0:
is_prime = True
end = int(sqrt(num))
for i in range(2, end+1):
if(num % i == 0):
is_prime = False
break
if is_prime:
print(('{0}は素数です').format(num))
else:
print(('{0}は素数ではない').format(num))
else:
print('正整数ではない')
"""
2.2つの正の整数を入力し、それらの最大公約数と最小公倍数を計算します。
"""
print('*'*33)
print('2つの正の整数を入力してください。')
x = int(input('x = '))
y = int(input('y = '))
if y > x:
# 通过下面的操作将y的值赋给x, 将x的值赋给y
(x, y) = (y, x)
for i in range(y, 0, -1):
if x % i == 0 and y % i == 0:
print(('{0}と{1}の最大公約数は{2}').format(x, y, i))
break
# print(('{0}と{1}の最小公倍数は{2}').format(x, y, x * y / i))
for j in range(x, x * y + 1, i):
if j % x == 0 and j % y == 0:
print(('{0}と{1}の最小公倍数は{2}').format(x, y, j))
break
print('*'*33)
|
c98d8baa7b0837b19dbf13304cc3c64da6541da7 | akanksha0202/pythonexercise | /input.py | 139 | 3.953125 | 4 | name = input('What is your name? ')
favorite_color = input('What is your fav. color ')
print('Hi ' + name + ' likes ' + favorite_color)
|
36a19156307e70367bcce02584e85405c85ac586 | hew123/python_debug | /scanInput.py | 813 | 3.65625 | 4 | def main():
'''
while(1):
try:
line = int(input())
print(line)
except EOFError:
break
'''
numOfID = int(input())
numOftrxn = int(input())
counter1 = 0
ids = []
while counter1 < numOfID:
id = int(input())
ids.append(id)
counter1 += 1
counter2 = 0
while counter2 < numOftrxn:
counter2 += 1
line = input()
#map(int, line.split(' '))
n , identity = [int(i) for i in line.split()]
#print(identity)
#identity = line[1]
if identity in ids:
index = ids.index(identity)
ids.pop(index)
#print(ids)
string = ' '.join([str(x) for x in ids])
print(string)
if __name__ == "__main__":
main()
|
40094cc34343b6b87869d0a8bcc1cfa196b28237 | RELNO/RELNO.github.io | /tools/folder_resize.py | 2,709 | 3.578125 | 4 | import os
from PIL import Image
def process_images(folder_path, rename=False):
# Create "raw" folder if it doesn't exist
raw_folder = os.path.join(folder_path, "raw")
os.makedirs(raw_folder, exist_ok=True)
# Get all file names in the folder
file_names = os.listdir(folder_path)
image_counter = 1 # Counter for the new image names
for file_name in file_names:
file_path = os.path.join(folder_path, file_name)
# Check if the file is an image
if is_image(file_path):
try:
# Open the image using PIL
image = Image.open(file_path)
# Calculate the resized dimensions while maintaining the aspect ratio
resized_dimensions = calculate_resized_dimensions(image.size)
# Resize the image
resized_image = image.resize(resized_dimensions)
# Save the original image in the "raw" folder
os.rename(file_path, os.path.join(raw_folder, file_name))
if rename:
# Create a new file name for the processed image
new_file_name = f"{image_counter}.jpg"
image_counter += 1
# Save the resized image as JPEG with the new file name
resized_image.save(os.path.join(
folder_path, new_file_name), "JPEG")
else:
# Save the resized image as JPEG with the original file name
resized_image.save(os.path.join(
folder_path, file_name), "JPEG")
print(f"Processed: {file_name}")
except Exception as e:
print(f"Error processing {file_name}: {str(e)}")
def is_image(file_path):
# Check if the file has an image extension
image_extensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp"]
return any(file_path.lower().endswith(ext) for ext in image_extensions)
def calculate_resized_dimensions(size):
max_width = 1200
max_height = 1200
width, height = size
# Calculate the resizing factor based on the maximum dimensions
width_ratio = max_width / width
height_ratio = max_height / height
resizing_factor = min(width_ratio, height_ratio)
# Calculate the new dimensions
new_width = int(width * resizing_factor)
new_height = int(height * resizing_factor)
return new_width, new_height
# Example usage
# get the folder path from the user
folder_path = input("Enter the folder path: ")
# ask the user if they want to rename the images
rename = input("Rename images? (y/n): ").lower() == "y"
process_images(folder_path, rename)
|
07c959fbafe8a7d2498e6fa022485029a6a3dc13 | RabbitUTSA/Rabbit | /HW2.py | 1,908 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 14:16:58 2018
@author: Rabbit/Joshua Crisp
"""
def trap(f, lower, upper, numberOfPoly):
"""code (upper and lower)
and (n) number of polygons
Trapaziod Rule calculations
return approx area and error
inputs upper-bound, lower-bound,
number of polygons
find number of polygons gives error less than
1e-5 (round n to nearest polygon)"""
def f(x):
return 3*(x**2)
h = (upper-lower)/numberOfPoly
print(h)
result = (0.5*(f(lower))) + (0.5*(f(upper)))
print(result)
for i in range (1, int(numberOfPoly)):
result += f(lower + i*h)
result *= h
print('result = %f' % result)
return result
def exact():
from math import exp
def f(x):
return 3*(x**2)
var = lambda t: f(t) * exp(t**3)
n = float(input('Please enter the number of Polygons: '))
upper = float(input('Please enter upper: '))
lower = float(input('Please enter lower: '))
#upper = 5.0
#lower = 1.0
"""h = float(upper-lower)/n
result = 0.5*(var(lower) + var(upper))
for i in range (1, int(n)):
result += var(lower + i*h)
result2 = h * result
print('result = %f' % result2)"""
num = trap(var, lower, upper, n)
print('num: %f' % num)
Va = lambda v: exp(v**3)
exact = trap(Va, lower, upper, n)
error = exact - num
print(var)
print('exact = %f' % (exact))
print ('n=%d: %.16f, error: %g' % (n, num, error))
return error
#trap(1.0, 5.0, 23500000)
exact()
"""for i in range(23400000, 23500000):
n = i
error = exact(n)
if error == 0.00001:
print ('Number: %s'% (n))
else:
++i
"""
"""Found the error gets closer to .00001 around 23.5 to
24 million poly""" |
08008169f146b72c3d28627b05022bd51c0d2128 | Tigul/pycram | /src/pycram/designator.py | 9,145 | 3.515625 | 4 | """Implementation of designators.
Classes:
DesignatorError -- implementation of designator errors.
Designator -- implementation of designators.
MotionDesignator -- implementation of motion designators.
"""
from inspect import isgenerator, isgeneratorfunction
from pycram.helper import GeneratorList
from threading import Lock
from time import time
class DesignatorError(Exception):
"""Implementation of designator errors."""
def __init__(self, *args, **kwargs):
"""Create a new designator error."""
Exception.__init__(self, *args, **kwargs)
class Designator:
"""Implementation of designators.
Designators are objects containing sequences of key-value pairs. They can be resolved which means to generate real parameters for executing actions from these pairs of key and value.
Instance variables:
timestamp -- the timestamp of creation of reference or None if still not referencing an object.
Methods:
equate -- equate the designator with the given parent.
equal -- check if the designator describes the same entity as another designator.
first -- return the first ancestor in the chain of equated designators.
current -- return the newest designator.
reference -- try to dereference the designator and return its data object
next_solution -- return another solution for the effective designator or None if none exists.
solutions -- return a generator for all solutions of the designator.
copy -- construct a new designator with the same properties as this one.
make_effective -- create a new effective designator of the same type as this one.
newest_effective -- return the newest effective designator.
prop_value -- return the first value matching the specified property key.
check_constraints -- return True if all the given properties match, False otherwise.
make_dictionary -- return the given parameters as dictionary.
"""
def __init__(self, properties, parent = None):
"""Create a new desginator.
Arguments:
properties -- a list of tuples (key-value pairs) describing this designator.
parent -- the parent to equate with (default is None).
"""
self._mutex = Lock()
self._parent = None
self._successor = None
self._effective = False
self._data = None
self.timestamp = None
self._properties = properties
if parent is not None:
self.equate(parent)
def equate(self, parent):
"""Equate the designator with the given parent.
Arguments:
parent -- the parent to equate with.
"""
if self.equal(parent):
return
youngest_parent = parent.current()
first_parent = parent.first()
if self._parent is not None:
first_parent._parent = self._parent
first_parent._parent._successor = first_parent
self._parent = youngest_parent
youngest_parent._successor = self
def equal(self, other):
"""Check if the designator describes the same entity as another designator, i.e. if they are equated.
Arguments:
other -- the other designator.
"""
return other.first() is self.first()
def first(self):
"""Return the first ancestor in the chain of equated designators."""
if self._parent is None:
return self
return self._parent.first()
def current(self):
"""Return the newest designator, i.e. that one that has been equated last to the designator or one of its equated designators."""
if self._successor is None:
return self
return self._successor.current()
def _reference(self):
"""This is a helper method for internal usage only.
This method is to be overwritten instead of the reference method.
"""
pass
def reference(self):
"""Try to dereference the designator and return its data object or raise DesignatorError if it is not an effective designator."""
with self._mutex:
ret = self._reference()
self._effective = True
if self.timestamp is None:
self.timestamp = time()
return ret
def next_solution(self):
"""Return another solution for the effective designator or None if none exists. The next solution is a newly constructed designator with identical properties that is equated to the designator since it describes the same entity."""
pass
def solutions(self, from_root = None):
"""Return a generator for all solutions of the designator.
Arguments:
from_root -- if not None, the generator for all solutions beginning from with the original designator is returned (default is None).
"""
if from_root is not None:
desig = self.first()
else:
desig = self
def generator(desig):
while desig is not None:
try:
yield desig.reference()
except DesignatorError:
pass
desig = desig.next_solution()
return generator(desig)
def copy(self, new_properties = None):
"""Construct a new designator with the same properties as this one. If new properties are specified, these will be merged with the old ones while the new properties are dominant in this relation.
Arguments:
new_properties -- a list of new properties to merge into the old ones (default is None).
"""
properties = self._properties.copy()
if new_properties is not None:
for key, value in new_properties:
replaced = False
for i in range(len(properties)):
k, v = properties[i]
if k == key:
properties[i] = (key, value)
replaced = True
# break
if not replaced:
properties.append((key, value))
return self.__class__(properties)
def make_effective(self, properties = None, data = None, timestamp = None):
"""Create a new effective designator of the same type as this one. If no properties are specified, this ones are used.
Arguments:
new_properties -- a list of properties (default is None).
data -- the low-level data structure the new designator describes (default is None).
timestamp -- the timestamp of creation of reference (default is the current).
"""
if properties is None:
properties = self._properties
desig = self.__class__(properties)
desig._effective = True
desig._data = data
if timestamp is None:
desig.timestamp = time()
else:
desig.timestamp = timestamp
return desig
def newest_effective(self):
"""Return the newest effective designator."""
def find_effective(desig):
if desig is None or desig._effective:
return desig
return find_effective(desig._parent)
return find_effective(self.current())
def prop_value(self, key):
"""Return the first value matching the specified property key.
Arguments:
key -- the key to return the value of.
"""
for k, v in self._properties:
if k == key:
return v
return None
def check_constraints(self, properties):
"""Return True if all the given properties match, False otherwise.
Arguments:
properties -- the properties which have to match. A property can be a tuple in which case its first value is the key of a property which must equal the second value. Otherwise it's simply the key of a property which must be not None.
"""
for prop in properties:
if type(prop) == tuple:
key, value = prop
if self.prop_value(key) != value:
return False
else:
if self.prop_value(prop) is None:
return False
return True
def make_dictionary(self, properties):
"""Return the given properties as dictionary.
Arguments:
properties -- the properties to create a dictionary of. A property can be a tuple in which case its first value is the dictionary key and the second value is the dictionary value. Otherwise it's simply the dictionary key and the key of a property which is the dictionary value.
"""
dictionary = {}
for prop in properties:
if type(prop) == tuple:
key, value = prop
dictionary[key] = value
else:
dictionary[prop] = self.prop_value(prop)
return dictionary
class MotionDesignator(Designator):
"""
Implementation of motion designators.
Variables:
resolvers -- list of all motion designator resolvers.
"""
resolvers = []
"""List of all motion designator resolvers. Motion designator resolvers are functions which take a designator as argument and return a list of solutions. A solution can also be a generator."""
def __init__(self, properties, parent = None):
self._solutions = None
self._index = 0
Designator.__init__(self, properties, parent)
def _reference(self):
if self._solutions is None:
def generator():
for resolver in MotionDesignator.resolvers:
for solution in resolver(self):
if isgeneratorfunction(solution):
solution = solution()
if isgenerator(solution):
while True:
try:
yield next(solution)
except StopIteration:
break
else:
yield solution
self._solutions = GeneratorList(generator)
if self._data is not None:
return self._data
try:
self._data = self._solutions.get(self._index)
return self._data
except StopIteration:
raise DesignatorError('Cannot resolve motion designator')
def next_solution(self):
try:
self.reference()
except DesignatorError:
pass
if self._solutions.has(self._index + 1):
desig = MotionDesignator(self._properties, self)
desig._solutions = self._solutions
desig._index = self._index + 1
return desig
return None
|
264f8f4f27f31ecdd317fac502200a839ac884bc | OuYangMinOa/linebot | /RSA.py | 1,583 | 3.71875 | 4 | def make_rsa_(n):
out = [2]
for i in range(3,n,2):
if (check(i)):
out.append(i)
return out
def check(num):
if (num%2==0):
return False
for i in range(3,int(num**0.5),2):
if (num%i==0):
return False
return True
lib = make_rsa_(500)
# 生成 小於 10000以所有的質數
import random
def RSA(num ):
print("對",num,"加密\n")
p = int(random.choices(lib)[0])
q = int(random.choices(lib)[0])
while p==q:
q = random.choices(lib)
# 找到兩個大質數 p,q
r = (p-1)*(q-1)
e = random.randint(2,r)
flag = check(r,e)
while not flag:
e = random.randint(2,r)
flag = check(r,e)
# 找到一個e 跟 r 互質
# 找到一個d
# ed - 1 = r的倍數
for ti in range(1,r):
if ((e*ti-1)%r ==0):
d =ti
break
N = p*q
print("公鑰: N=",N,", e =",e)#,"私鑰: N=",N,", d=",d)
this_ = num**e
for i in range(0,(this_+1)):
if ( (this_- i) %N == 0):
c = i
break
print("加密後文本:",c)
decrption(N,d,c)
def decrption(N,d,c):
f = c**d
print("\n私鑰",d,"慾解密:",c)
for i in range(0,c**d+1):
if ((f-i) %N == 0):
print("解密後文本:",i)
break
def check(n_1,n_2):
for i in range(min(n_1,n_2),1,-1):
if (n_1%i ==0 and n_2%i ==0):
return False
return True
for i in range(20):
RSA(random.randint(10,50))
print("="*100)
|
369649dce4a898825618f0ff807ccf228b2c124f | james-roden/google-foobar | /level1/Guard_Game.py | 2,161 | 3.84375 | 4 | # -----------------------------------------------
# Google-Foobar
# Name: Guard Game aka adding_digits
# Level: 1
# Challenge: 1
# Author: James M Roden
# Created: 11th August 2016
# Python Version 2.6
# PEP8
# -----------------------------------------------
"""
Guard game
==========
You're being held in a guarded room in Dr. Boolean's mad science lab. How can
you escape? Beta Rabbit, a fellow captive and rabbit, notices a chance. The
lab guards are always exceptionally bored, and have made up a game for
themselves. They take the file numbers from the various specimens in the
Professors lab, and see who can turn them into single digit numbers the
fastest. "I've observed them closely," Beta says. "For any number, the way
they do this is by taking each digit in the number and adding them all
together, repeating with the new sum until the result is a single digit.
For example, when a guard picks up the medical file for Rabbit #1235,
she would first add those digits together to get 11, then add those together
to get 2, her final sum." See if you can short circuit this game entirely
with a clever program, thus driving the guards back to severe boredom. That
way they will fall asleep and allow you to sneak out! Write a function
answer(x), which when given a number x, returns the final digit resulting
from performing the above described repeated sum process on x. x will be 0 or
greater, and less than 2^31 -1 (or 2147483647), and the answer should be 0 or
greater, and a single integer digit.
==========
Test cases
==========
Inputs:
(long) x = 13
Output:
(int) 4
Inputs:
(long) x = 1235
Output:
(int) 2
"""
def answer(x):
"""
As specified
"""
def recursive_sum(n):
"""
Recursively adds each digit together from n
n -- Integer
"""
# Base case - return n if single digit
if n < 10:
return n
else:
return n % 10 + recursive_sum(n / 10)
# Run recursive function once
total = recursive_sum(x)
# Repeat final time if total is still more than 1 digit.
if total > 9:
total = recursive_sum(total)
return total
|
92ab0a09b8eab1d3a27beab9c4093d3acd30991b | JunaidRana/MLStuff | /Advanced Python/Virtual Functions/File.py | 364 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 19:51:27 2018
@author: Junaid.raza
"""
class Dog:
def say(self):
print ("hau")
class Cat:
def say(self):
print ("meow")
pet = Dog()
pet.say() # prints "hau"
another_pet = Cat()
another_pet.say() # prints "meow"
my_pets = [pet, another_pet]
for a_pet in my_pets:
a_pet.say() |
959b8244e952ce4f393004b7c8730987fdc08ed5 | darshita1603/testing | /operators.py | 192 | 3.96875 | 4 | # x=3>2
# print(x)
w=int(input("enter your weight: "))
unit=input("(K)g or(L)bs :")
if unit.lower()=="k":
print(str(w//0.45))
elif unit.lower()=="l":
print(str(w*0.45))
print("hh") |
b3e1d545b107f607cc46e42a9e281af98cf4626c | psychotechnik/esq-currencies | /money/moneyd_classes.py | 24,252 | 3.734375 | 4 | # -*- coding: utf-8 -*-
from decimal import Decimal
import locale
# NOTE: this sets the default locale to the local environment's (and
# something other than the useless 'C' locale), but possibly it should
# be set/changed depending on the Currency country. However that will
# require a lookup: given the currency code, return the locale code;
# the pycountry package may provide a way to do that. Revisit this
# later. KW 1/2011.
DEFAULT_LOCALE = (
"%s.%s"
% (locale.getdefaultlocale()[0],
locale.getdefaultlocale()[1].lower()))
locale.setlocale(locale.LC_ALL, DEFAULT_LOCALE)
class Currency(object):
"""
A Currency represents a form of money issued by governments, and
used in one or more states/countries. A Currency instance
encapsulates the related data of: the ISO currency/numeric code, a
canonical name, countries the currency is used in, and an exchange
rate - the last remains unimplemented however.
"""
code = 'XYZ'
country = ''
countries = []
name = ''
numeric = '999'
exchange_rate = Decimal('1.0')
def __init__(self, code='', numeric='999', name='', countries=[]):
self.code = code
self.countries = countries
self.name = name
self.numeric = numeric
def __repr__(self):
return self.code
def set_exchange_rate(self, rate):
# This method could later use a web-lookup of the current
# exchange rate; currently it's just a manual field
# setting. 7/2010
if not isinstance(rate, Decimal):
rate = Decimal(str(rate))
self.exchange_rate = rate
# With Currency class defined, setup some needed module globals:
CURRENCIES = {}
CURRENCIES['XYZ'] = Currency(code='XYZ', numeric='999')
DEFAULT_CURRENCY = CURRENCIES['XYZ']
def set_default_currency(code='XYZ'):
global DEFAULT_CURRENCY
DEFAULT_CURRENCY = CURRENCIES[code]
class MoneyComparisonError(TypeError):
# This exception was needed often enough to merit its own
# Exception class.
def __init__(self, other):
assert not isinstance(other, Money)
self.other = other
def __str__(self):
# Note: at least w/ Python 2.x, use __str__, not __unicode__.
return "Cannot compare instances of Money and %s" \
% self.other.__class__.__name__
class Money(object):
"""
A Money instance is a combination of data - an amount and a
currency - along with operators that handle the semantics of money
operations in a better way than just dealing with raw Decimal or
($DEITY forbid) floats.
"""
amount = Decimal('0.0')
currency = DEFAULT_CURRENCY
def __init__(self, amount=Decimal('0.0'), currency=None):
if not isinstance(amount, Decimal):
amount = Decimal(str(amount))
self.amount = amount
if not currency:
self.currency = DEFAULT_CURRENCY
else:
if not isinstance(currency, Currency):
currency = CURRENCIES[str(currency).upper()]
self.currency = currency
def __unicode__(self):
return "%s %s" % (
locale.currency(self.amount, grouping=True),
self.currency)
__repr__ = __unicode__
def __pos__(self):
return Money(
amount=self.amount,
currency=self.currency)
def __neg__(self):
return Money(
amount=-self.amount,
currency=self.currency)
def __add__(self, other):
if not isinstance(other, Money):
raise TypeError('Cannot add a Money and non-Money instance.')
if self.currency == other.currency:
return Money(
amount=self.amount + other.amount,
currency=self.currency)
else:
this = self.convert_to_default()
other = other.convert_to_default()
return Money(
amount=(this.amount + other.amount),
currency=DEFAULT_CURRENCY)
def __sub__(self, other):
return self.__add__(-other)
def __mul__(self, other):
if isinstance(other, Money):
raise TypeError('Cannot multiply two Money instances.')
else:
return Money(
amount=(self.amount * Decimal(str(other))),
currency=self.currency)
def __div__(self, other):
if isinstance(other, Money):
if self.currency != other.currency:
raise TypeError('Cannot divide two different currencies.')
return self.amount / other.amount
else:
return Money(
amount=self.amount / Decimal(str(other)),
currency=self.currency)
def __rmod__(self, other):
"""
Calculate percentage of an amount. The left-hand side of the
operator must be a numeric value.
Example:
>>> money = Money(200, 'USD')
>>> 5 % money
USD 10.00
"""
if isinstance(other, Money):
raise TypeError('Invalid __rmod__ operation')
else:
return Money(
amount=(Decimal(str(other)) * self.amount / 100),
currency=self.currency)
def convert_to_default(self):
return Money(
amount=(self.amount * self.currency.exchange_rate),
currency=DEFAULT_CURRENCY)
def convert_to(self, currency):
"""
Convert from one currency to another.
"""
return None # TODO
__radd__ = __add__
__rsub__ = __sub__
__rmul__ = __mul__
__rdiv__ = __div__
# _______________________________________
# Override comparison operators
def __eq__(self, other):
if not isinstance(other, Money):
raise MoneyComparisonError(other)
return (self.amount == other.amount) \
and (self.currency == other.currency)
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result
def __lt__(self, other):
if not isinstance(other, Money):
raise MoneyComparisonError(other)
if (self.currency == other.currency):
return (self.amount < other.amount)
else:
raise TypeError('Cannot compare different currencies (yet).')
def __gt__(self, other):
if not isinstance(other, Money):
raise MoneyComparisonError(other)
if (self.currency == other.currency):
return (self.amount > other.amount)
else:
raise TypeError('Cannot compare different currencies (yet).')
def __le__(self, other):
return self < other or self == other
def __ge__(self, other):
return self > other or self == other
# ____________________________________________________________________
# Definitions of ISO 4217 Currencies
# Source: http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm
CURRENCIES['BZD'] = Currency(code='BZD', numeric='084', name='Belize Dollar', countries=['BELIZE'])
CURRENCIES['YER'] = Currency(code='YER', numeric='886', name='Yemeni Rial', countries=['YEMEN'])
CURRENCIES['XBA'] = Currency(code='XBA', numeric='955', name='Bond Markets Units European Composite Unit (EURCO)', countries=[])
CURRENCIES['SLL'] = Currency(code='SLL', numeric='694', name='Leone', countries=['SIERRA LEONE'])
CURRENCIES['ERN'] = Currency(code='ERN', numeric='232', name='Nakfa', countries=['ERITREA'])
CURRENCIES['NGN'] = Currency(code='NGN', numeric='566', name='Naira', countries=['NIGERIA'])
CURRENCIES['CRC'] = Currency(code='CRC', numeric='188', name='Costa Rican Colon', countries=['COSTA RICA'])
CURRENCIES['VEF'] = Currency(code='VEF', numeric='937', name='Bolivar Fuerte', countries=['VENEZUELA'])
CURRENCIES['LAK'] = Currency(code='LAK', numeric='418', name='Kip', countries=['LAO PEOPLES DEMOCRATIC REPUBLIC'])
CURRENCIES['DZD'] = Currency(code='DZD', numeric='012', name='Algerian Dinar', countries=['ALGERIA'])
CURRENCIES['SZL'] = Currency(code='SZL', numeric='748', name='Lilangeni', countries=['SWAZILAND'])
CURRENCIES['MOP'] = Currency(code='MOP', numeric='446', name='Pataca', countries=['MACAO'])
CURRENCIES['BYR'] = Currency(code='BYR', numeric='974', name='Belarussian Ruble', countries=['BELARUS'])
CURRENCIES['MUR'] = Currency(code='MUR', numeric='480', name='Mauritius Rupee', countries=['MAURITIUS'])
CURRENCIES['WST'] = Currency(code='WST', numeric='882', name='Tala', countries=['SAMOA'])
CURRENCIES['LRD'] = Currency(code='LRD', numeric='430', name='Liberian Dollar', countries=['LIBERIA'])
CURRENCIES['MMK'] = Currency(code='MMK', numeric='104', name='Kyat', countries=['MYANMAR'])
CURRENCIES['KGS'] = Currency(code='KGS', numeric='417', name='Som', countries=['KYRGYZSTAN'])
CURRENCIES['PYG'] = Currency(code='PYG', numeric='600', name='Guarani', countries=['PARAGUAY'])
CURRENCIES['IDR'] = Currency(code='IDR', numeric='360', name='Rupiah', countries=['INDONESIA'])
CURRENCIES['XBD'] = Currency(code='XBD', numeric='958', name='European Unit of Account 17(E.U.A.-17)', countries=[])
CURRENCIES['GTQ'] = Currency(code='GTQ', numeric='320', name='Quetzal', countries=['GUATEMALA'])
CURRENCIES['CAD'] = Currency(code='CAD', numeric='124', name='Canadian Dollar', countries=['CANADA'])
CURRENCIES['AWG'] = Currency(code='AWG', numeric='533', name='Aruban Guilder', countries=['ARUBA'])
CURRENCIES['TTD'] = Currency(code='TTD', numeric='780', name='Trinidad and Tobago Dollar', countries=['TRINIDAD AND TOBAGO'])
CURRENCIES['PKR'] = Currency(code='PKR', numeric='586', name='Pakistan Rupee', countries=['PAKISTAN'])
CURRENCIES['XBC'] = Currency(code='XBC', numeric='957', name='European Unit of Account 9(E.U.A.-9)', countries=[])
CURRENCIES['UZS'] = Currency(code='UZS', numeric='860', name='Uzbekistan Sum', countries=['UZBEKISTAN'])
CURRENCIES['XCD'] = Currency(code='XCD', numeric='951', name='East Caribbean Dollar', countries=['ANGUILLA', 'ANTIGUA AND BARBUDA', 'DOMINICA', 'GRENADA', 'MONTSERRAT', 'SAINT KITTS AND NEVIS', 'SAINT LUCIA', 'SAINT VINCENT AND THE GRENADINES'])
CURRENCIES['VUV'] = Currency(code='VUV', numeric='548', name='Vatu', countries=['VANUATU'])
CURRENCIES['KMF'] = Currency(code='KMF', numeric='174', name='Comoro Franc', countries=['COMOROS'])
CURRENCIES['AZN'] = Currency(code='AZN', numeric='944', name='Azerbaijanian Manat', countries=['AZERBAIJAN'])
CURRENCIES['XPD'] = Currency(code='XPD', numeric='964', name='Palladium', countries=[])
CURRENCIES['MNT'] = Currency(code='MNT', numeric='496', name='Tugrik', countries=['MONGOLIA'])
CURRENCIES['ANG'] = Currency(code='ANG', numeric='532', name='Netherlands Antillian Guilder', countries=['NETHERLANDS ANTILLES'])
CURRENCIES['LBP'] = Currency(code='LBP', numeric='422', name='Lebanese Pound', countries=['LEBANON'])
CURRENCIES['KES'] = Currency(code='KES', numeric='404', name='Kenyan Shilling', countries=['KENYA'])
CURRENCIES['GBP'] = Currency(code='GBP', numeric='826', name='Pound Sterling', countries=['UNITED KINGDOM'])
CURRENCIES['SEK'] = Currency(code='SEK', numeric='752', name='Swedish Krona', countries=['SWEDEN'])
CURRENCIES['AFN'] = Currency(code='AFN', numeric='971', name='Afghani', countries=['AFGHANISTAN'])
CURRENCIES['KZT'] = Currency(code='KZT', numeric='398', name='Tenge', countries=['KAZAKHSTAN'])
CURRENCIES['ZMK'] = Currency(code='ZMK', numeric='894', name='Kwacha', countries=['ZAMBIA'])
CURRENCIES['SKK'] = Currency(code='SKK', numeric='703', name='Slovak Koruna', countries=['SLOVAKIA'])
CURRENCIES['DKK'] = Currency(code='DKK', numeric='208', name='Danish Krone', countries=['DENMARK', 'FAROE ISLANDS', 'GREENLAND'])
CURRENCIES['TMM'] = Currency(code='TMM', numeric='795', name='Manat', countries=['TURKMENISTAN'])
CURRENCIES['AMD'] = Currency(code='AMD', numeric='051', name='Armenian Dram', countries=['ARMENIA'])
CURRENCIES['SCR'] = Currency(code='SCR', numeric='690', name='Seychelles Rupee', countries=['SEYCHELLES'])
CURRENCIES['FJD'] = Currency(code='FJD', numeric='242', name='Fiji Dollar', countries=['FIJI'])
CURRENCIES['SHP'] = Currency(code='SHP', numeric='654', name='Saint Helena Pound', countries=['SAINT HELENA'])
CURRENCIES['ALL'] = Currency(code='ALL', numeric='008', name='Lek', countries=['ALBANIA'])
CURRENCIES['TOP'] = Currency(code='TOP', numeric='776', name='Paanga', countries=['TONGA'])
CURRENCIES['UGX'] = Currency(code='UGX', numeric='800', name='Uganda Shilling', countries=['UGANDA'])
CURRENCIES['OMR'] = Currency(code='OMR', numeric='512', name='Rial Omani', countries=['OMAN'])
CURRENCIES['DJF'] = Currency(code='DJF', numeric='262', name='Djibouti Franc', countries=['DJIBOUTI'])
CURRENCIES['BND'] = Currency(code='BND', numeric='096', name='Brunei Dollar', countries=['BRUNEI DARUSSALAM'])
CURRENCIES['TND'] = Currency(code='TND', numeric='788', name='Tunisian Dinar', countries=['TUNISIA'])
CURRENCIES['SBD'] = Currency(code='SBD', numeric='090', name='Solomon Islands Dollar', countries=['SOLOMON ISLANDS'])
CURRENCIES['GHS'] = Currency(code='GHS', numeric='936', name='Ghana Cedi', countries=['GHANA'])
CURRENCIES['GNF'] = Currency(code='GNF', numeric='324', name='Guinea Franc', countries=['GUINEA'])
CURRENCIES['CVE'] = Currency(code='CVE', numeric='132', name='Cape Verde Escudo', countries=['CAPE VERDE'])
CURRENCIES['ARS'] = Currency(code='ARS', numeric='032', name='Argentine Peso', countries=['ARGENTINA'])
CURRENCIES['GMD'] = Currency(code='GMD', numeric='270', name='Dalasi', countries=['GAMBIA'])
CURRENCIES['ZWD'] = Currency(code='ZWD', numeric='716', name='Zimbabwe Dollar', countries=['ZIMBABWE'])
CURRENCIES['MWK'] = Currency(code='MWK', numeric='454', name='Kwacha', countries=['MALAWI'])
CURRENCIES['BDT'] = Currency(code='BDT', numeric='050', name='Taka', countries=['BANGLADESH'])
CURRENCIES['KWD'] = Currency(code='KWD', numeric='414', name='Kuwaiti Dinar', countries=['KUWAIT'])
CURRENCIES['EUR'] = Currency(code='EUR', numeric='978', name='Euro', countries=['ANDORRA', 'AUSTRIA', 'BELGIUM', 'FINLAND', 'FRANCE', 'FRENCH GUIANA', 'FRENCH SOUTHERN TERRITORIES', 'GERMANY', 'GREECE', 'GUADELOUPE', 'IRELAND', 'ITALY', 'LUXEMBOURG', 'MARTINIQUE', 'MAYOTTE', 'MONACO', 'MONTENEGRO', 'NETHERLANDS', 'PORTUGAL', 'R.UNION', 'SAINT PIERRE AND MIQUELON', 'SAN MARINO', 'SLOVENIA', 'SPAIN'])
CURRENCIES['CHF'] = Currency(code='CHF', numeric='756', name='Swiss Franc', countries=['LIECHTENSTEIN'])
CURRENCIES['XAG'] = Currency(code='XAG', numeric='961', name='Silver', countries=[])
CURRENCIES['SRD'] = Currency(code='SRD', numeric='968', name='Surinam Dollar', countries=['SURINAME'])
CURRENCIES['DOP'] = Currency(code='DOP', numeric='214', name='Dominican Peso', countries=['DOMINICAN REPUBLIC'])
CURRENCIES['PEN'] = Currency(code='PEN', numeric='604', name='Nuevo Sol', countries=['PERU'])
CURRENCIES['KPW'] = Currency(code='KPW', numeric='408', name='North Korean Won', countries=['KOREA'])
CURRENCIES['SGD'] = Currency(code='SGD', numeric='702', name='Singapore Dollar', countries=['SINGAPORE'])
CURRENCIES['TWD'] = Currency(code='TWD', numeric='901', name='New Taiwan Dollar', countries=['TAIWAN'])
CURRENCIES['USD'] = Currency(code='USD', numeric='840', name='US Dollar', countries=['AMERICAN SAMOA', 'BRITISH INDIAN OCEAN TERRITORY', 'ECUADOR', 'GUAM', 'MARSHALL ISLANDS', 'MICRONESIA', 'NORTHERN MARIANA ISLANDS', 'PALAU', 'PUERTO RICO', 'TIMOR-LESTE', 'TURKS AND CAICOS ISLANDS', 'UNITED STATES MINOR OUTLYING ISLANDS', 'VIRGIN ISLANDS (BRITISH)', 'VIRGIN ISLANDS (U.S.)'])
CURRENCIES['BGN'] = Currency(code='BGN', numeric='975', name='Bulgarian Lev', countries=['BULGARIA'])
CURRENCIES['MAD'] = Currency(code='MAD', numeric='504', name='Moroccan Dirham', countries=['MOROCCO', 'WESTERN SAHARA'])
CURRENCIES['XYZ'] = Currency(code='XYZ', numeric='999', name='The codes assigned for transactions where no currency is involved are:', countries=[])
CURRENCIES['SAR'] = Currency(code='SAR', numeric='682', name='Saudi Riyal', countries=['SAUDI ARABIA'])
CURRENCIES['AUD'] = Currency(code='AUD', numeric='036', name='Australian Dollar', countries=['AUSTRALIA', 'CHRISTMAS ISLAND', 'COCOS (KEELING) ISLANDS', 'HEARD ISLAND AND MCDONALD ISLANDS', 'KIRIBATI', 'NAURU', 'NORFOLK ISLAND', 'TUVALU'])
CURRENCIES['KYD'] = Currency(code='KYD', numeric='136', name='Cayman Islands Dollar', countries=['CAYMAN ISLANDS'])
CURRENCIES['KRW'] = Currency(code='KRW', numeric='410', name='Won', countries=['KOREA'])
CURRENCIES['GIP'] = Currency(code='GIP', numeric='292', name='Gibraltar Pound', countries=['GIBRALTAR'])
CURRENCIES['TRY'] = Currency(code='TRY', numeric='949', name='New Turkish Lira', countries=['TURKEY'])
CURRENCIES['XAU'] = Currency(code='XAU', numeric='959', name='Gold', countries=[])
CURRENCIES['CZK'] = Currency(code='CZK', numeric='203', name='Czech Koruna', countries=['CZECH REPUBLIC'])
CURRENCIES['JMD'] = Currency(code='JMD', numeric='388', name='Jamaican Dollar', countries=['JAMAICA'])
CURRENCIES['BSD'] = Currency(code='BSD', numeric='044', name='Bahamian Dollar', countries=['BAHAMAS'])
CURRENCIES['BWP'] = Currency(code='BWP', numeric='072', name='Pula', countries=['BOTSWANA'])
CURRENCIES['GYD'] = Currency(code='GYD', numeric='328', name='Guyana Dollar', countries=['GUYANA'])
CURRENCIES['XTS'] = Currency(code='XTS', numeric='963', name='Codes specifically reserved for testing purposes', countries=[])
CURRENCIES['LYD'] = Currency(code='LYD', numeric='434', name='Libyan Dinar', countries=['LIBYAN ARAB JAMAHIRIYA'])
CURRENCIES['EGP'] = Currency(code='EGP', numeric='818', name='Egyptian Pound', countries=['EGYPT'])
CURRENCIES['THB'] = Currency(code='THB', numeric='764', name='Baht', countries=['THAILAND'])
CURRENCIES['MKD'] = Currency(code='MKD', numeric='807', name='Denar', countries=['MACEDONIA'])
CURRENCIES['SDG'] = Currency(code='SDG', numeric='938', name='Sudanese Pound', countries=['SUDAN'])
CURRENCIES['AED'] = Currency(code='AED', numeric='784', name='UAE Dirham', countries=['UNITED ARAB EMIRATES'])
CURRENCIES['JOD'] = Currency(code='JOD', numeric='400', name='Jordanian Dinar', countries=['JORDAN'])
CURRENCIES['JPY'] = Currency(code='JPY', numeric='392', name='Yen', countries=['JAPAN'])
CURRENCIES['ZAR'] = Currency(code='ZAR', numeric='710', name='Rand', countries=['SOUTH AFRICA'])
CURRENCIES['HRK'] = Currency(code='HRK', numeric='191', name='Croatian Kuna', countries=['CROATIA'])
CURRENCIES['AOA'] = Currency(code='AOA', numeric='973', name='Kwanza', countries=['ANGOLA'])
CURRENCIES['RWF'] = Currency(code='RWF', numeric='646', name='Rwanda Franc', countries=['RWANDA'])
CURRENCIES['CUP'] = Currency(code='CUP', numeric='192', name='Cuban Peso', countries=['CUBA'])
CURRENCIES['XFO'] = Currency(code='XFO', numeric='Nil', name='Gold-Franc', countries=[])
CURRENCIES['BBD'] = Currency(code='BBD', numeric='052', name='Barbados Dollar', countries=['BARBADOS'])
CURRENCIES['PGK'] = Currency(code='PGK', numeric='598', name='Kina', countries=['PAPUA NEW GUINEA'])
CURRENCIES['LKR'] = Currency(code='LKR', numeric='144', name='Sri Lanka Rupee', countries=['SRI LANKA'])
CURRENCIES['RON'] = Currency(code='RON', numeric='946', name='New Leu', countries=['ROMANIA'])
CURRENCIES['PLN'] = Currency(code='PLN', numeric='985', name='Zloty', countries=['POLAND'])
CURRENCIES['IQD'] = Currency(code='IQD', numeric='368', name='Iraqi Dinar', countries=['IRAQ'])
CURRENCIES['TJS'] = Currency(code='TJS', numeric='972', name='Somoni', countries=['TAJIKISTAN'])
CURRENCIES['MDL'] = Currency(code='MDL', numeric='498', name='Moldovan Leu', countries=['MOLDOVA'])
CURRENCIES['MYR'] = Currency(code='MYR', numeric='458', name='Malaysian Ringgit', countries=['MALAYSIA'])
CURRENCIES['CNY'] = Currency(code='CNY', numeric='156', name='Yuan Renminbi', countries=['CHINA'])
CURRENCIES['LVL'] = Currency(code='LVL', numeric='428', name='Latvian Lats', countries=['LATVIA'])
CURRENCIES['INR'] = Currency(code='INR', numeric='356', name='Indian Rupee', countries=['INDIA'])
CURRENCIES['FKP'] = Currency(code='FKP', numeric='238', name='Falkland Islands Pound', countries=['FALKLAND ISLANDS (MALVINAS)'])
CURRENCIES['NIO'] = Currency(code='NIO', numeric='558', name='Cordoba Oro', countries=['NICARAGUA'])
CURRENCIES['PHP'] = Currency(code='PHP', numeric='608', name='Philippine Peso', countries=['PHILIPPINES'])
CURRENCIES['HNL'] = Currency(code='HNL', numeric='340', name='Lempira', countries=['HONDURAS'])
CURRENCIES['HKD'] = Currency(code='HKD', numeric='344', name='Hong Kong Dollar', countries=['HONG KONG'])
CURRENCIES['NZD'] = Currency(code='NZD', numeric='554', name='New Zealand Dollar', countries=['COOK ISLANDS', 'NEW ZEALAND', 'NIUE', 'PITCAIRN', 'TOKELAU'])
CURRENCIES['BRL'] = Currency(code='BRL', numeric='986', name='Brazilian Real', countries=['BRAZIL'])
CURRENCIES['RSD'] = Currency(code='RSD', numeric='941', name='Serbian Dinar', countries=['SERBIA'])
CURRENCIES['XBB'] = Currency(code='XBB', numeric='956', name='European Monetary Unit (E.M.U.-6)', countries=[])
CURRENCIES['EEK'] = Currency(code='EEK', numeric='233', name='Kroon', countries=['ESTONIA'])
CURRENCIES['SOS'] = Currency(code='SOS', numeric='706', name='Somali Shilling', countries=['SOMALIA'])
CURRENCIES['MZN'] = Currency(code='MZN', numeric='943', name='Metical', countries=['MOZAMBIQUE'])
CURRENCIES['XFU'] = Currency(code='XFU', numeric='Nil', name='UIC-Franc', countries=[])
CURRENCIES['NOK'] = Currency(code='NOK', numeric='578', name='Norwegian Krone', countries=['BOUVET ISLAND', 'NORWAY', 'SVALBARD AND JAN MAYEN'])
CURRENCIES['ISK'] = Currency(code='ISK', numeric='352', name='Iceland Krona', countries=['ICELAND'])
CURRENCIES['GEL'] = Currency(code='GEL', numeric='981', name='Lari', countries=['GEORGIA'])
CURRENCIES['ILS'] = Currency(code='ILS', numeric='376', name='New Israeli Sheqel', countries=['ISRAEL'])
CURRENCIES['HUF'] = Currency(code='HUF', numeric='348', name='Forint', countries=['HUNGARY'])
CURRENCIES['UAH'] = Currency(code='UAH', numeric='980', name='Hryvnia', countries=['UKRAINE'])
CURRENCIES['RUB'] = Currency(code='RUB', numeric='643', name='Russian Ruble', countries=['RUSSIAN FEDERATION'])
CURRENCIES['IRR'] = Currency(code='IRR', numeric='364', name='Iranian Rial', countries=['IRAN'])
CURRENCIES['BMD'] = Currency(code='BMD', numeric='060', name='Bermudian Dollar (customarily known as Bermuda Dollar)', countries=['BERMUDA'])
CURRENCIES['MGA'] = Currency(code='MGA', numeric='969', name='Malagasy Ariary', countries=['MADAGASCAR'])
CURRENCIES['MVR'] = Currency(code='MVR', numeric='462', name='Rufiyaa', countries=['MALDIVES'])
CURRENCIES['QAR'] = Currency(code='QAR', numeric='634', name='Qatari Rial', countries=['QATAR'])
CURRENCIES['VND'] = Currency(code='VND', numeric='704', name='Dong', countries=['VIET NAM'])
CURRENCIES['MRO'] = Currency(code='MRO', numeric='478', name='Ouguiya', countries=['MAURITANIA'])
CURRENCIES['NPR'] = Currency(code='NPR', numeric='524', name='Nepalese Rupee', countries=['NEPAL'])
CURRENCIES['TZS'] = Currency(code='TZS', numeric='834', name='Tanzanian Shilling', countries=['TANZANIA'])
CURRENCIES['BIF'] = Currency(code='BIF', numeric='108', name='Burundi Franc', countries=['BURUNDI'])
CURRENCIES['XPT'] = Currency(code='XPT', numeric='962', name='Platinum', countries=[])
CURRENCIES['KHR'] = Currency(code='KHR', numeric='116', name='Riel', countries=['CAMBODIA'])
CURRENCIES['SYP'] = Currency(code='SYP', numeric='760', name='Syrian Pound', countries=['SYRIAN ARAB REPUBLIC'])
CURRENCIES['BHD'] = Currency(code='BHD', numeric='048', name='Bahraini Dinar', countries=['BAHRAIN'])
CURRENCIES['XDR'] = Currency(code='XDR', numeric='960', name='SDR', countries=['INTERNATIONAL MONETARY FUND (I.M.F)'])
CURRENCIES['STD'] = Currency(code='STD', numeric='678', name='Dobra', countries=['SAO TOME AND PRINCIPE'])
CURRENCIES['BAM'] = Currency(code='BAM', numeric='977', name='Convertible Marks', countries=['BOSNIA AND HERZEGOVINA'])
CURRENCIES['LTL'] = Currency(code='LTL', numeric='440', name='Lithuanian Litas', countries=['LITHUANIA'])
CURRENCIES['ETB'] = Currency(code='ETB', numeric='230', name='Ethiopian Birr', countries=['ETHIOPIA'])
CURRENCIES['XPF'] = Currency(code='XPF', numeric='953', name='CFP Franc', countries=['FRENCH POLYNESIA', 'NEW CALEDONIA', 'WALLIS AND FUTUNA'])
|
44afcb87371f25b5edc54fbf47a794d9287f6fd5 | huynhminhtruong/py | /utils/python_games.py | 1,630 | 3.875 | 4 | import turtle
# Setup Screen
screen = turtle.Screen()
screen.title("Game 1")
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.tracer(0)
# Setup Paddle A
player_a = turtle.Turtle()
player_a.speed(0)
player_a.shape("square")
player_a.color("white")
player_a.penup()
player_a.goto(-350, 0)
# Setup Paddle B
player_b = turtle.Turtle()
player_b.speed(0)
player_b.shape("square")
player_b.color("white")
player_b.penup()
player_b.goto(350, 0)
# Setup Ball
ball = turtle.Turtle()
ball.speed(10)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
ball.dy = 2
# Moving
def player_a_moving_up():
y = player_a.ycor()
y += 20
player_a.sety(y)
def player_a_moving_down():
y = player_a.ycor()
y -= 20
player_a.sety(y)
def player_b_moving_up():
y = player_b.ycor()
y += 20
player_b.sety(y)
def player_b_moving_down():
y = player_b.ycor()
y -= 20
player_b.sety(y)
# Handle keyboard input
screen.listen()
screen.onkeypress(player_a_moving_up, "w")
screen.onkeypress(player_a_moving_down, "s")
screen.onkeypress(player_b_moving_up, "Up")
screen.onkeypress(player_b_moving_down, "Down")
# Main game loop
while True:
screen.update()
# Moving ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.xcor() > 390:
ball.setx(390)
ball.dx *= -1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
if ball.xcor() < -390:
ball.setx(-390)
ball.dx *= -1 |
cb67a222b923e0b9810f2867ce8ca87aef4cbeb7 | huynhminhtruong/py | /interview/closure_decorator.py | 1,565 | 3.90625 | 4 | # First class function
# Properties of first class functions:
# - A function is an instance of the Object type.
# - You can store the function in a variable.
# - You can pass the function as a parameter to another function.
# - You can return the function from a function.
# - You can store them in data structures such as hash tables, lists
import logging
import functools as ft
logging.basicConfig(filename="output.log", level=logging.INFO)
def square(n):
return n * n
def mapping(func, a):
n = len(a)
for i in range(n):
a[i] = func(a[i])
return a
def sum_numbers(*args):
a = args # receive params as a tuples
print(a)
def add(*args):
return sum(args)
def product(*args) -> int:
return ft.reduce(lambda x, y: x * y, args)
def sub(*args) -> int:
return ft.reduce(lambda x, y: x - y, args)
def div(*args) -> int:
return ft.reduce(lambda x, y: x // y, args)
def logger(func):
def wrapper(*args):
logging.info("Running function {0} with args: {1}".format(func.__name__, args))
print(func(*args))
return wrapper
@logger
def factor(*args) -> int:
return ft.reduce(lambda x, y: x * y, args, 1)
if __name__ == "__main__":
# n = int(input())
# a = mapping(square, [int(i) for i in input().split()]) # custom mapping
# sum_numbers(*a) # pass params as a tuples
add_n = logger(add)
product_n = logger(product)
sub_n = logger(sub)
div_n = logger(div)
add_n(1, 2)
product_n(1, 2)
sub_n(1, 2)
div_n(10, 2)
factor(1, 2, 3) |
b13834533bd1aa99aa659f69cfa1e591e4177572 | tzontzy13/IN3063-TASK1 | /task1.py | 18,935 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
# import datetime to check time spent running script
# makes script as efficent as possible
import datetime
class Game:
# GAMEMODE IS NUMBER ON THE CELL IS COST
def __init__(self, height, width):
# initialize the width and height of the grid
self.height = height
self.width = width
def generateGrid(self):
# generates a Height x Width 2d array with random elements from 0 - 9
grid = np.random.randint(low=0, high=9, size=(self.height, self.width))
# returns the generated grid
return grid
# Wikipedia. 2020.
# Dijkstra's algorithm - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Algorithm
# [Accessed 19 December 2020].
# Vaidehi Joshi. 2017.
# Finding The Shortest Path, With A Little Help From Dijkstra | by Vaidehi Joshi | basecs | Medium.
# [ONLINE] Available at: https://medium.com/basecs/finding-the-shortest-path-with-a-little-help-from-dijkstra-613149fbdc8e
# [Accessed 19 December 2020].
def dijkstra(self, grid, start):
# row and col are the lengths of our 2d array (grid is the 2d array)
row = len(grid)
col = len(grid[0])
# cost to each "node" FROM STARTING NODE!. updates as we go through "nodes"
# 2d array mirroring our grid
# at first, the cost to get to each node is 99999999 (a lot)
distance = np.full((row, col), 99999999)
# the cost to our start node is 0
distance[start] = 0
# visited and unvisited nodes
# 2d array mirroring our grid
# visited node is a 1
# unvisited node is a 0
# at first, all nodes are unvisited, so 0
visited = np.zeros((row, col), dtype=int)
# set for holding nodes to check in smallestUnvisited function, so we dont check all nodes every time
# if we had a M x N grid, we would check M x N values for the smallest unvisited one
# with this, we improve the total time of running this script by only checking neightbours of visited nodes
nodesToCheck = set()
nodesToCheck.add((0, 0))
# function to find the smallest distance node, from the unvisited nodes
def smallestUnvisited(distance, nodesToCheck):
# smallest distance node i coordinate
sm_i = -1
# smallest distance node j coordinate
sm_j = -1
# smallest distance node value (initial)
sm = 99999999
# we check every node for the smallest value
for node in nodesToCheck:
i, j = node
if (distance[i][j] < sm):
sm = distance[i][j]
sm_i = i
sm_j = j
# we return the coordinates of our smallest distance unvisited node
return (sm_i, sm_j)
# start going through all nodes in our grid and updating distances
# while there exists nodes to go through (see function declaration above)
while(len(nodesToCheck) != 0):
# get the i and j of smallest distance unvisited node
i, j = smallestUnvisited(distance, nodesToCheck)
# for south, east, norths, west we check if there exists an unvisited node
# we then compare the current distance for that node with
# the distance of the current node plus the cost
# (cost is the number of the next node)
# if the current distance is greater, i change it to the lower value i just computed
# south
# if there exists a node to the south that is UNVISITED
if i+1 < len(distance) and visited[i+1][j] == 0:
# add node to set, to be checked later when we compute the smallest value form unvisited nodes
nodesToCheck.add((i+1, j))
# compute distance
if distance[i+1][j] > grid[i+1][j] + distance[i][j]:
distance[i+1][j] = grid[i+1][j] + distance[i][j]
# east
# if there exists a node to the east that is UNVISITED
if j+1 < len(distance[0]) and visited[i][j+1] == 0:
# add node to set, to be checked later when we compute the smallest value form unvisited nodes
nodesToCheck.add((i, j+1))
# compute distance
if distance[i][j+1] > grid[i][j+1] + distance[i][j]:
distance[i][j+1] = grid[i][j+1] + distance[i][j]
# north
if i-1 >= 0 and visited[i-1][j] == 0:
# add node to set, to be checked later when we compute the smallest value form unvisited nodes
nodesToCheck.add((i-1, j))
# compute distance
if distance[i-1][j] > grid[i-1][j] + distance[i][j]:
distance[i-1][j] = grid[i-1][j] + distance[i][j]
# west
if j-1 >= 0 and visited[i][j-1] == 0:
# add node to set, to be checked later when we compute the smallest value form unvisited nodes
nodesToCheck.add((i, j-1))
# compute distance
if distance[i][j-1] > grid[i][j-1] + distance[i][j]:
distance[i][j-1] = grid[i][j-1] + distance[i][j]
# mark node as visited
visited[i][j] = 1
# remove current node from nodesToCheck, so we dont check it again, causing errors in the flow
nodesToCheck.remove((i, j))
# returning distance to bottom right cornet of 2d array
return distance[row-1][col-1]
# Wikipedia. 2020.
# Breadth-first search - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Breadth-first_search
# [Accessed 19 December 2020].
def BFS(self, grid, start):
# BFS is similar to dijskras except it only checks south and east and
# doesnt have a way of picking which node to visit next
# it always picks the first node in the queue
# row and col are the lengths of our 2d array (grid is the 2d array)
row = len(grid)
col = len(grid[0])
# cost to each "node" FROM STARTING NODE!!!!!!!!!!. updates as we go through "nodes"
# 2d array mirroring our grid
# at first, the cost to get to each node is 99999999 (a lot)
distance = np.full((row, col), 99999999)
# the cost to our start node is 0
distance[start] = 0
# data structure for keeping visited nodes, so we dont visit more than once and go into an infinite loop
visited = np.zeros((row, col))
# queue for checking nodes
queue = []
# we add first node to queue
queue.append((0, 0))
# while queue is not empty
while(len(queue) != 0):
# get coordinates of first node in queue
i, j = queue[0]
# remove first node from queue
queue.pop(0)
# mark it as visited
visited[i][j] = 1
# if South node exists, is not visited and not already in the queue
if(i+1 < row and visited[i+1][j] == 0 and (i+1,j) not in queue):
# add node to queue
queue.append((i+1, j))
# compute distance
if distance[i+1][j] > grid[i+1][j] + distance[i][j]:
distance[i+1][j] = grid[i+1][j] + distance[i][j]
# if East node exists
if(j+1 < col and visited[i][j+1] == 0 and (i,j+1) not in queue):
# add node to queue
queue.append((i, j+1))
# compute distance
if distance[i][j+1] > grid[i][j+1] + distance[i][j]:
distance[i][j+1] = grid[i][j+1] + distance[i][j]
# return distance to bottom right corner (calculated only with right and down movements)
return distance[row-1][col-1]
# Ali Mirjalili. 2018.
# Inspiration of Ant Colony Optimization - YouTube.
# [ONLINE] Available at: https://www.youtube.com/watch?v=1qpvpOHGRqA&ab_channel=AliMirjalili
# [Accessed 19 December 2020].
# Ali Mirjalili. 2018.
# How the Ant Colony Optimization algorithm works - YouTube.
# [ONLINE] Available at: https://www.youtube.com/watch?v=783ZtAF4j5g&t=235s&ab_channel=AliMirjalili
# [Accessed 19 December 2020].
# Wikipedia. 2020.
# Ant colony optimization algorithms - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Ant_colony_optimization_algorithms#Algorithm_and_formulae
# [Accessed 19 December 2020].
# Wikipedia. 2020.
# Fitness proportionate selection - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Fitness_proportionate_selection
# [Accessed 19 December 2020].
def ant_colony(self, grid, start):
# row and col are the lengths of our 2d array (grid is the 2d array)
row = len(grid)
col = len(grid[0])
# end node
end = (row - 1, col - 1)
# initialize pheromones (similar to weights from neural networks)
pheromones = np.ones(shape=(row, col))
# constant that gets divided by a distance when updating pheromones
# used for updateing pheromones
q_constant = 1.1
# constant that "fades out" the pheromones
evaporation_rate = 0.55
# set number of generations (epochs) and ants
ants = 256*3+32+8+16+32+128+32
gens = 32+16+8+4+8
# initial shortest path
shortest_path = 99999999
# helper functions
# selects a node for the ant to visit
def roulette_select(current_node, nodes_to_check):
# nodes to check contains the neighbours of current node that meet a specific criteria (exist, not in current path)
# n = probability
n = np.random.uniform(0, 1)
# sum of all activations (a)
s = 0
# list for nodes and probability of nodes
prob = []
nodes = []
# for each node
for node in nodes_to_check:
# add it to nodes
nodes.append(node)
# create activation (a) based on distance and pheromones
# if the pheromones are low, the activation will be low
# if the distance is low, the activation will be high
if(distance(current_node, node) != 0):
a = (1 / distance(current_node, node)) * \
pheromone(current_node, node)
else:
a = pheromone(current_node, node)
# add activation to sum
s += a
# add activation to probability list
prob.append(a)
prob = np.array(prob, dtype='float64')
# divide the probability list by the sum
# prob now contains the probability of each node to be picked
# sum of probability list is now 1
prob = prob / s
# choose a node based on the probability list generated above and n
cumulative_sum = 0
chosen = 0
# developed this code using the pseudocode from Wikipedia and a YouTube video
# Wikipedia. 2020.
# Fitness proportionate selection - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Fitness_proportionate_selection
# [Accessed 19 December 2020].
# Ali Mirjalili. 2018.
# How the Ant Colony Optimization algorithm works - YouTube.
# [ONLINE] Available at: https://www.youtube.com/watch?v=783ZtAF4j5g&t=235s&ab_channel=AliMirjalili
# [Accessed 19 December 2020].
# adapted pseudocode for my project
for i in range(len(prob)):
if cumulative_sum < n:
chosen = i
cumulative_sum += prob[i]
return nodes[chosen]
# returns the pheromone levels between 2 points
def pheromone(p1, p2):
pher = pheromones[p2[0]][p2[1]]
return pher
# distance between 2 points using "The time spent on a cell is the number on this cell"
def distance(p1, p2):
dist = grid[p2[0]][p2[1]]
return dist
# update pheromones after each generation
def update_pheromones(paths):
# apply evaporation rate
# the pheromones "lose" power after each generation
new_pheromones = (1 - evaporation_rate) * pheromones
# update each pheromone manually
# formula found in Wikipedia
for hist, dist in paths:
for node in hist:
i = node[0]
j = node[1]
# i changed this because I cant divide by 0
if (dist == 0):
dist = 0.75
# update pheromones at a specific node
# pheromone after evaporation + a constant divided by distance traveled by the ant
new_node_pher = new_pheromones[i][j] + (q_constant / dist)
new_pheromones[i][j] = new_node_pher
# return pheromones
return new_pheromones
# starting from node, return a set of new nodes for the the ant to choose from
def update_nodes_to_check(node, path):
i = node[0]
j = node[1]
new_nodes_to_check = set()
# if node exists
# if node not already visited
if((i+1 < row) and ((i+1, j) not in path)):
new_nodes_to_check.add((i+1, j))
if((i-1 >= 0) and ((i-1, j) not in path)):
new_nodes_to_check.add((i-1, j))
if((j+1 < col) and ((i, j+1) not in path)):
new_nodes_to_check.add((i, j+1))
if((j-1 >= 0) and ((i, j-1) not in path)):
new_nodes_to_check.add((i, j-1))
# return the new set of nodes for roulette selection
return new_nodes_to_check
# if a shorter path exists, update the distance of the shortest path
def update_shortest_path(paths):
current_shortest = shortest_path
# check each valid path
# i say valid because sometimes the ant doesnt reach the end node
# that path is not added in the paths list
for hist, dist in paths:
if dist < current_shortest:
# update shortest distance
current_shortest = dist
return current_shortest
# for each generation
for g in range(gens):
# list for storing paths of that generation
paths = []
# for each ant
for a in range(ants):
# start point
current_node = (0, 0)
current_distance = 0
# path of ant
path = set()
path.add(current_node)
# path of ant, in the order of nodes
path_in_order = []
path_in_order.append(current_node)
# nodes to check with roulette selection
nodes_to_check = set()
nodes_to_check.add((1, 0))
nodes_to_check.add((0, 1))
# if there are nodes to check and the current node is not the end node
while (len(nodes_to_check) != 0) and (current_node != end):
# select next node
next_node = roulette_select(current_node, nodes_to_check)
# compute distance to next node from START of path to next node
current_distance += distance(current_node, next_node)
# create a new set of nodes to check in the next while loop
nodes_to_check = update_nodes_to_check(next_node, path)
# set current node to next node
current_node = next_node
# add node to path
path.add(next_node)
path_in_order.append(next_node)
# the ant doesnt always reach the end node (gets lost or trapped), so we check if it found a viable path before adding to paths list
if(end in path):
paths.append([path_in_order, current_distance])
# update pheromones and shortest path for next generation
pheromones = update_pheromones(paths)
shortest_path = update_shortest_path(paths)
# returns the shortest path to end node
return shortest_path
# testing starts here
grid2 = [[1, 9, 9, 9],
[1, 9, 9, 9],
[1, 9, 9, 9],
[1, 1, 1, 1]]
grid6 = [[1, 9, 9],
[1, 9, 9],
[1, 1, 1]]
grid3 = [[1, 4, 1],
[1, 2, 1]]
grid4 = [[0, 9, 9, 9, 9],
[0, 9, 0, 0, 0],
[0, 9, 0, 9, 0],
[0, 9, 0, 9, 0],
[0, 0, 0, 9, 0]]
grid5 = [[0, 9, 0, 0, 0, 0],
[0, 9, 0, 9, 9, 0],
[0, 9, 0, 0, 9, 0],
[0, 9, 9, 0, 9, 0],
[0, 0, 0, 0, 9, 0]]
grid7 = [[0, 6, 4, 5, 1, 4, 3, 5, 6, 8, 7],
[1, 3, 3, 9, 1, 4, 3, 5, 6, 2, 1],
[4, 1, 9, 1, 1, 4, 3, 5, 6, 5, 3],
[9, 6, 1, 2, 1, 4, 3, 5, 6, 2, 1],
[1, 3, 5, 4, 1, 4, 3, 5, 6, 8, 4],
[8, 7, 2, 9, 1, 4, 3, 5, 6, 7, 5],
[1, 6, 3, 5, 1, 4, 3, 5, 6, 2, 2],
[8, 7, 2, 9, 1, 4, 3, 5, 6, 7, 5],
[1, 6, 3, 5, 1, 4, 3, 5, 6, 2, 2],
[8, 7, 2, 9, 1, 4, 3, 5, 6, 7, 5],
[1, 6, 3, 5, 1, 4, 3, 5, 6, 2, 2]]
grid8 = [[1, 9, 9, 9, 9, 9],
[1, 1, 9, 1, 1, 1],
[9, 1, 9, 1, 9, 1],
[9, 1, 9, 1, 9, 1],
[9, 1, 9, 1, 9, 1],
[9, 1, 9, 1, 9, 1],
[9, 1, 1, 1, 9, 1]]
grid9 = [[0, 6, 4, 5],
[1, 3, 3, 9],
[4, 9, 2, 1],
[9, 6, 1, 2],
[2, 3, 4, 5]]
game = Game(14, 14)
grid_genrated = game.generateGrid()
grid = grid_genrated
print('\n')
# compute distance with Dijkstra
begin_time = datetime.datetime.now()
distance = game.dijkstra(grid, (0, 0))
print("time - Dijkstra ", datetime.datetime.now() - begin_time)
print("distance - Dijkstra ", distance)
print('\n')
print("ACO started")
# compute distance with ant colony
begin_time = datetime.datetime.now()
distance3 = game.ant_colony(grid, (0, 0))
print("time - ant_colony ", datetime.datetime.now() - begin_time)
print("distance - ant_colony ", distance3)
print('\n')
# compute distance with BFS
begin_time = datetime.datetime.now()
distance2 = game.BFS(grid, (0, 0))
print("time - BFS ", datetime.datetime.now() - begin_time)
print("distance - BFS ", distance2) |
360d9c21dbf5a48dcc918e4a37edccb36e754e84 | kolbychien/Big_Fish_HW | /text_to_html/file_reader.py | 229 | 3.6875 | 4 |
class FileReader:
def read_file(self, file):
try:
data = open(file, "r")
return data
except FileNotFoundError:
print('{} File Not Found'.format(file))
return '' |
37bcd2c5af0266085fd1f92a598a7c938b7459b9 | sjandro/Python_Projects | /worms.py | 988 | 3.71875 | 4 | # The numbers 1 to 9999 (decimal base) were written on a paper.
# Then the paper was partially eaten by worms. It happened that just those parts of paper
# with digit "0" were eaten.
# Consequently the numbers 1200 and 3450 appear as 12 and 345 respectively,
# whilst the number 6078 appears as two separate numbers 6 and 78.
# What is the sum of the numbers appearing on the worm-eaten paper?
###### WHAT ARE WE LOOKING FOR
# to see your ability to :
# 1) write readable clean code
# 2) problem solving using (if/else/loops/etc ... )
# 3) use parsing, string/numbers dancing
# the "main" function is provided to get you started.
def worms(param):
total = 0
for num in param:
str_num = str(num)
if "0" in str_num:
parts = [int(i) for i in str_num.split("0") if i != ""]
total += sum(parts)
else:
total += num
return total
def main():
print(worms(range(1, 1001)))
if __name__ == '__main__':
main()
|
67b18f00fa58479afbadc342c857a9dcf3dca4f6 | sjandro/Python_Projects | /spiralMatrix.py | 2,990 | 3.828125 | 4 | # n = int(raw_input().split(',')[0])
# matrix = ""
# for i in xrange(1, n + 1):
# if matrix == "":
# matrix = raw_input()
# elif i % 2 == 0:
# row = raw_input().split(',')
# row.reverse()
# #print row
# matrix = matrix + "," + ",".join(row)
# else:
# matrix = matrix + "," + raw_input()
# print matrix
import itertools
arr = [['0','1','2','3'],
['4','5','6','7'],
['8','9','10','11'],
['12','13','14','15']]
def shift(seq, n):
n = n % len(seq)
return seq[n:] + seq[:n]
def buildMatrix(matrix, lst, x, y, start, end):
for num in lst:
print "x: " + str(x) + " y: " + str(y)
matrix[x][y] = num
if x == start and y < end:
y += 1
elif y == end and x < end:
x += 1
elif x == end and y > start:
y -= 1
elif x > start and y == start:
x -= 1
return matrix
def buildSquence(matrix, x, y, start, end, parameter):
l = []
for i in range(parameter):
print "x: " + str(x) + " y: " + str(y)
l.append(matrix[x][y])
if x == start and y < end:
y += 1
elif y == end and x < end:
x += 1
elif x == end and y > start:
y -= 1
elif x > start and y == start:
x -= 1
return l
def transpose_and_yield_top(arr):
# count = 0
while arr:
# if(count == 4):
# break
yield arr[0]
#print arr[0]
#count += 1
l = list(zip(*arr[1:]))
print l
arr = list(reversed(l))
# def outerLayerSize(n):
# if n == 1:
# return 1
# else:
# return n * 4 - 4
# test = ",".join(list(itertools.chain(*transpose_and_yield_top(arr))))
# mlist = [list(i) for i in list(transpose_and_yield_top(arr))]
# final_sque = []
# for i in range(len(mlist)):
# for j in range(len(mlist[i])):
# final_sque.append(mlist[i][j])
# print final_sque
#spiral_matrix = list(itertools.chain(*transpose_and_yield_top(arr)))
#spiral_matrix = final_sque
matrix = [[0 for i in range(len(arr))] for i in range(len(arr))]
#layers = []
params_length = len(arr)
#index = 0
x = 0
y = 0
start = 0
end = len(arr) - 1
while params_length > 0:
#size = outerLayerSize(params_length)
size = 1 if params_length == 1 else params_length * 4 - 4
params_length -= 2
print size
#layers.append(spiral_matrix[index:size+index])
layers = buildSquence(arr, x, y, start, end, size)
print buildMatrix(matrix,shift(layers, -2),x,y,start,end)
#index = size
x += 1
y += 1
start += 1
end -= 1
#print layers
# l = shift(test.split(","), -2)
# print l
# matrix = [[0 for i in range(len(arr))] for i in range(len(arr))]
# print matrix
# x = 0
# y = 0
# start = 0
# end = len(arr) - 1
# for i in range(len(layers)):
# print buildMatrix(matrix,shift(layers[i], -2),x,y,start,end)
# x += 1
# y += 1
# start += 1
# end -= 1
|
6c6b663994ce1242ed06b87b9ed761dcc7952a5a | anitha-mahalingappa/myprograms | /add_sub.py | 340 | 3.796875 | 4 |
def my_add(arg1,arg2):
add = arg1+arg2
print(add)
return add
def my_sub(arg3,arg4):
sub = arg3-arg4
print(sub)
return sub
#main prog
my_num1 = int(input(" enter the number : "))
my_num2 = int(input(" enter the number : "))
var1 = my_add(my_num1,my_num2)
var2 = my_sub(my_num1,my_num2)
print(var1,var2) |
140f58ab33359d4f2fee71db14309ea689af34a1 | luandadantas/100diasdecodigo | /Dia62-laços_while/ingressos_para_o_cinema.py | 240 | 4 | 4 |
while True:
idade = int(input("Qual a sua idade: "))
if idade < 3:
print("Entrada gratuita.")
elif 3 <= idade <= 12:
print("O ingresso é 10 reais.")
elif idade > 12:
print("O ingresso é 15 reais.") |
c8d57ee25e8e01dff8ba1513e2da416a8b9d32e5 | luandadantas/100diasdecodigo | /Dia3-Trabalhando_com_listas/trabalhando_com_listas.py | 655 | 3.578125 | 4 | magicians = ["alice", "david", "carolina"]
for magician in magicians:
print(magician.title() + ", that was a great trick")
print("I can't wait to see yout next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!\n\n")
# Pizzas
sabores_pizzas = ["Marguerita", "Quatro queijos", "Brócolis"]
for pizza in sabores_pizzas:
print("Gosto de Pizza de " + pizza + ".")
print("\n")
# Animais
animais = ["papagaio", "cachorro", "gato"]
for animal in animais:
print("O " + animal + " é um ótimo animal de estimação")
print("Qualquer um desses animais seria um ótimo animal de estimação.\n") |
900339c6573b404e2d1a9baab95ebab83ff0d77f | luandadantas/100diasdecodigo | /Dia5-Tuplas/tuplas.py | 424 | 3.546875 | 4 | #Buffet
pratos = ("file com fritas", "Macarrão a bolonhesa", "Feijoada", "Batata frita", "Arroz de Leite")
for prato in pratos:
print(prato)
print("\n")
#Certificando de que python rejeita a mudança de uma tupla
#pratos[0] = "Salada"
#print(pratos)
#Sobrescrevendo uma tupla
pratos = ("salada", "Torta de Limão", "Feijoada", "Batata Frita", "Arroz de Leite")
for novos_pratos in pratos:
print(novos_pratos) |
f7b899552df22c76e14b57078c14f7b79db9a93d | luandadantas/100diasdecodigo | /Dia25-Sintaxe_if-elif-else/alien_color.py | 235 | 3.59375 | 4 | alien_color = "vermelho"
if alien_color == verde:
print("O jogador acabou de ganhar 5 pontos")
elif alien_color == amarelo
print("O jogador acabou de ganhar 10 pontos")
else:
print("O jogador acabou de ganhar 15 pontos")
|
c9e94907bcc0cd80b129b6af08d2ada91f73a757 | luandadantas/100diasdecodigo | /Dia51-URI/1070_seis_numeros_impares.py | 122 | 3.65625 | 4 | X = int(input())
cont = 0
while (cont < 6):
if X % 2 != 0:
print(X)
cont = cont + 1
X = X + 1 |
99f8af2cfad89ccad08ff5d2add5f27608d13241 | luandadantas/100diasdecodigo | /Dia6-URI/1019_conversao_de_tempo.py | 550 | 3.890625 | 4 |
'''
Leia um valor inteiro, que é o tempo de duração em segundos de um determinado evento em uma fábrica,
e informe-o expresso no formato horas:minutos:segundos.
Entrada: O arquivo de entrada contém um valor inteiro N.
Saída: Imprima o tempo lido no arquivo de entrada (segundos), convertido para horas:minutos:segundos.
Exemplo de entrada: 556
Exemplo de Saída: 0:9:16
'''
tempo = int(input())
hora = tempo//3600
resto_hora = tempo%3600
minuto = resto_hora//60
segundo = tempo%60
print(str(hora) + ":" + str(minuto) + ":" + str(segundo)) |
18fb3450295c77c92240542858e9f6ac1eda0aff | luandadantas/100diasdecodigo | /Dia17-URI/1013_O_Maior.py | 166 | 3.609375 | 4 | A, B, C = input().split(" ")
A = int(A)
B= int(B)
C = int(C)
AB = (A+B+abs(A-B))/2
maior = (AB+C+abs(AB-C))/2
maior = int(maior)
print(str(maior) + " eh o maior") |
276d376cb90bd570b184389be4b53942cc1349a8 | luandadantas/100diasdecodigo | /Dia27-Finalizando_capitulo5/ingredientes_varias_listas.py | 464 | 3.65625 | 4 | ingredientes_disponíveis = ['tomate', 'brócolis', 'queijo', 'cebola', 'molho']
ingredientes_solicitados = ['tomate', 'batata frita', 'queijo']
for ingrediente_solicitados in ingredientes_solicitados:
if ingrediente_solicitados in ingredientes_disponíveis:
print("Adicionando " + ingrediente_solicitados + ".")
else:
print("Desculpa, nós não temos o ingrediente " + ingrediente_solicitados + ".")
print("\nA pizza está finalizada.")
|
89922c88bab0ebb36e7662ac8af16c974b5ff543 | a-lexgon-z/Alexander_Gonzalez_TE19D | /variabler/variabler.py | 356 | 3.8125 | 4 | name = "Alexander" # har skapat variablen name och tilldelat det värdet "Alexander"
age = 17 # skapat variabeln age och tilldelat det värdet 17
print(f"Hej {name} du är {age} år gammal")
side = float(input("Ange kvadratens sida: "))
area = side**2
omkrets = 4*side
print(f"Kvadratens area är {area} a.e. och lvadratens omkrets är {omkrets} l.e.") |
2690d3485c14aa778f7385128237aabfa345556d | apr-fue/python | /Term 1/hagnman.py | 2,055 | 4.09375 | 4 | #hangman game
#april fuentes
#10/19
#just a game of hangman
#computer picks a word
#player guesses it one letter at a time
#cant guess the word in time
#the stick figure dies
#imports
import random
#constants
HANGMAN = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\\ |
|
|
=========''', '''
+---+
| |
O |
/|\\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\\ |
/ \ |
|
=========''']
MAX_WRONG = len(HANGMAN) - 1
WORDS = ("BRUH", "YEET", "JELLYFISH", "JOE")
#initialize variables
word = random.choice(WORDS)
so_far = "-" * len(word)
wrong = 0
used = []
print("Welcome to Hangman.")
while wrong < MAX_WRONG and so_far != word:
print(HANGMAN[wrong])
print("\nYou've used the following letters:\n", used)
print("\nSo far, the word is:\n", so_far)
guess = input("\nEnter your guess: ")
guess = guess.upper()
while guess in used:
print("You've already guessed the letter", guess)
guess = input("\nEnter your guess: ")
guess = guess.upper()
used.append(guess)
if guess in word:
print("\nYes!", guess, "is in the word!")
new = " "
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[1]
so_far = new
else:
print("\nSorry,",guess, "isn't in the word")
wrong +=1
if wrong == MAX_WRONG:
print(HANGMAN[wrong])
print("\You've been hanged!")
else:
print("nYou guessed it!")
print("\nThe word was", word)
input("\n\nPress the enter key to exit")
|
5f433c76732e66e4e4ca6677488e717baaf4656f | rjayswal-pythonista/OOP_Python | /Library.py | 2,747 | 4.09375 | 4 | class Library:
def __init__(self, availableBooks):
self.availableBooks = availableBooks
def displaybook(self):
print('List of Available Books in Library are:')
for books in self.availableBooks:
print(books)
def lendbook(self, requestedbook):
if requestedbook in self.availableBooks:
print()
print(f"You have now borrowed book name {requestedbook} from Library")
self.availableBooks.remove(requestedbook)
else:
print(f"Sorry, {requestedBook} is not available in Library now")
def addbook(self, returnedbook):
self.availableBooks.append(returnedbook)
print()
print(f"Thank you for returning book name {returnedbook} to Library")
print()
class Customer:
def requestbook(self):
print('Enter the name of book which you want to borrow from Library: ')
self.book = str(input())
return self.book
def returnbook(self):
print('Enter the name of book which you want to return to Library: ')
self.book = str(input())
return self.book
if __name__ == "__main__":
availableBooks = ['The Lord of the Rings', 'Harry Potter series', 'The Little Prince', 'Think and Grow Rich']
library = Library(availableBooks)
customer = Customer()
print('##########################################################################################################')
print(" Welcome to Roshan Jayswal Library ")
print('##########################################################################################################')
print()
print('Enter your choice: ')
while True:
print()
print('Enter 1 to display available books in Library')
print('Enter 2 to borrow book from Library')
print('Enter 3 to return book to Library')
print('Enter 4 to quit')
userchoice = int(input())
if userchoice == 1:
library.displaybook()
elif userchoice == 2:
requestedBook = customer.requestbook()
library.lendbook(requestedBook)
elif userchoice == 3:
returnedBook = customer.returnbook()
library.addbook(returnedBook)
elif userchoice == 4:
print('#########################################################################################################')
print(' Thank you for visiting Roshan Jayswal Library. See you soon... ')
print('#########################################################################################################')
quit()
|
db4896b8597a48ba911b60c418a20ef74a87648d | Juanmarin444/python_practice | /hello_world.py | 514 | 3.75 | 4 | words = "It's thanksgiving day. It's my birthday, too!"
print words
print words.find('day')
print words.replace("day", "month")
print words
x = [2,54,-2,7,12,98]
print min(x)
print max(x)
y = ["hello",2,54,-2,7,12,98,"world"]
print y[0]
print y[len(y)-1]
new_y = [y[0], y[len(y) - 1]]
print new_y
list_2 = [19,2,54,-2,7,12,98,32,10,-3,6]
print list_2
list_2.sort()
print list_2
half_length = len(list_2)/2
lst = []
for ele in list_2 [:5]:
lst.append(int(ele))
list_2.insert(5, lst)
print list_2[5:]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.