blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
49d3fbe78c86ab600767198110c6022be77fefe9 | SagarikaNagpal/Python-Practice | /QuesOnOops/F-9.py | 507 | 4.1875 | 4 | # : Write a function that has one character argument and displays that it’s a small letter, capital letter, a digit or a special symbol.
# 97-122 65-90 48-57 33-47
def ch(a):
if(a.isupper()):
print("upper letter")
elif(a.islower()):
print("lower letter")
elif (a.isdigit()):
print("is digit")
else:
print("Special")
a=input("ch is: ")
print(ch(a)) |
fe87fda53fd053e70d978d0204461c0aeb69058a | SagarikaNagpal/Python-Practice | /QuesOnOops/A-25.py | 137 | 3.8125 | 4 | a=int(input("a is: "))
b=int(input("b is: "))
print("before swapping")
print(a)
print(b)
print("After Swaping")
a,b=b,a
print(a)
print(b) |
7099d78eb77a62ea5960a55130123ca386f261e1 | SagarikaNagpal/Python-Practice | /QuesOnOops/B-39.py | 105 | 3.953125 | 4 | num = int(input("Num for its table: "))
for i in range(1,11):
print("table of",num,"*",i,"=",num*i) |
934c3fb94a7536650b6810b5a50467f84faf2952 | SagarikaNagpal/Python-Practice | /tiny_progress/list/Python program to print odd numbers in a List.py | 402 | 3.875 | 4 | def listCreate():
n = int(input('Number of elements in list: '))
l =[]
for i in range(n):
l.append(int(input('element is: ')))
return l
def odd(l):
odd = []
for i in l:
if i%2 ==1:
odd.append(i)
return odd
def main():
first = listCreate()
second= odd(l=first)
print(f'odd num is {second}')
if __name__ == '__main__':
main()
|
a131bce1690e9cef62f40819824fd3e6c7cf0d51 | SagarikaNagpal/Python-Practice | /QuesOnOops/C-15.py | 430 | 4.03125 | 4 | # to check a string for palindrome.
# also work with b-79
# String="aIbohPhoBiA"
# String1=String.casefold()
# Rev_String=reversed(String1)
# if(list(String1)==list(Rev_String)):
# print("The string is palindrome")
# else:
# print("no its not")
s= input("string: ")
s1 = s.casefold()
print(s1)
rev = reversed(s)
print("rev",rev)
if(list(s1)==list(rev)):
print("string is palindrome")
else:
print("no its not")
|
3aa25f3fba06beaa6fecf9403e4de839549e2660 | SagarikaNagpal/Python-Practice | /QuesOnOops/A-5.py | 132 | 4.15625 | 4 | radius= int(input("radius is:"))
circu= 2*3.14*radius
area=3.14*radius
print("circumfrence is: ",circu)
print("area is: ",area)
|
e0675cb6771465070dbd479f662a7e3e8f9eef2a | SagarikaNagpal/Python-Practice | /QuesOnOops/B30.py | 181 | 3.90625 | 4 | # Question B30: WAP to print counting from 10 to 1.
# Question B31: WAP to print counting from 51 to 90.
for i in range(10,0,-1):
print(i)
for f in range(50,91):
print(f) |
696000f189c565377613191ebbaf86299cf6614f | SagarikaNagpal/Python-Practice | /tiny_progress/basic/A1.py | 302 | 3.890625 | 4 | # Question A1: WAP to input roll number, name, marks and phone of a student and display the values.
from tokenize import Name
rollNum = int(input("RollNumber : "))
name = (input("Name: "))
marks = int(input("Marks: "))
phone = int(input("Phone: "))
print(rollNum,name,marks,phone)
print(type(Name)) |
fc996b4899875fbf48ca5b5e4da4a4f194cbef70 | SagarikaNagpal/Python-Practice | /QuesOnOops/B8.py | 452 | 3.640625 | 4 | # Question B8: WAP to input the salary of a person and calculate the hra and da according to the following conditions:
# Salary HRA DA
# 5000-10000 10% 5%
# 10001-15000 15% 8%
name = str(input("name"))
sal = int(input("sal is: "))
HRA = 1
DA = 1
if((sal>5000 and sal< 1000)):
HRA = (0.1*sal)
DA = (0.5 *sal)
if((sal>10001 and sal <15000)):
HRA = (1.5*sal)
DA = (0.8*sal)
print()
print("HRA", HRA)
print("DA", DA)
|
43462ac259650bcea0c4433ff1d27d90bbc7a09e | SagarikaNagpal/Python-Practice | /QuesOnOops/C-4.py | 321 | 4.40625 | 4 | # input a multi word string and produce a string in which first letter of each word is capitalized.
# s = input()
# for x in s[:].split():
# s = s.replace(x, x.capitalize())
# print(s)
a1 = input("word1: ")
a2 = input("word2: ")
a3 = input("word3: ")
print(a1.capitalize(),""+a2.capitalize(),""+a3.capitalize()) |
c56fecfa02ec9637180348dd990cf646ad00f77f | SagarikaNagpal/Python-Practice | /QuesOnOops/B-78.py | 730 | 4.375 | 4 | # Write a menu driven program which has following options:
# 1. Factorial of a number.
# 2. Prime or Not
# 3. Odd or even
# 4. Exit.
n = int(input("n: "))
menu = int(input("menu is: "))
factorial = 1
if(menu==1):
for i in range(1,n+1):
factorial= factorial*i
print("factorial of ",n,"is",factorial)
elif(menu==2):
if(n>1):
for i in range (2,n):
if(n%i)==0:
print("num ",n,"is not prime")
break
else:
print("num", n ,"is prime")
break
else:
print("num is not prime")
elif(menu==3):
if(n%2 ==0):
print(n,"is even")
else:
print(n, "is odd")
else:
print("exit!")
|
7b8acefe0e74bdd25c9e90f869009c2e3a24a4fc | SagarikaNagpal/Python-Practice | /QuesOnOops/C-13.py | 213 | 4.40625 | 4 | # to input two strings and print which one is lengthier.
s1 = input("String1: ")
s2 = input("String2: ")
if(len(s1)>len(s2)):
print("String -",s1,"-is greater than-", s2,"-")
else:
print(s2,"is greater") |
96e4195413797d376b936e6b5d1b04aaa8c01cac | SagarikaNagpal/Python-Practice | /QuesOnOops/C-14.py | 61 | 4.15625 | 4 | # to reverse a string.
s = input("string: ")
print(s[::-1])
|
e09aad9458b0eceb8a8acfc23db8a78637e3ebfe | SagarikaNagpal/Python-Practice | /tiny_progress/list/Python program to swap two elements in a list.py | 809 | 4.25 | 4 | # Python program to swap two elements in a list
def appendList():
user_lst = []
no_of_items = int(input("How many numbers in a list: "))
for i in range(no_of_items):
user_lst.append(int(input("enter item: ")))
return user_lst
def swapPos(swap_list):
swap_index_1 = int(input("Enter First Index for swapping: "))
swap_index_2 = int(input("Enter Second Index for swapping: "))
swap_list[swap_index_1], swap_list[swap_index_2] = swap_list[swap_index_2], swap_list[swap_index_1]
return swap_list
def main():
saga_list = appendList()
print("List Before Swapping: ", saga_list)
print("List Sorted: ", sorted(saga_list))
swapped_list = swapPos(swap_list=saga_list)
print("List After Swapping: ", swapped_list)
if __name__ == '__main__':
main()
|
04ac72941293d872cecb6d12f3cf1ba2d8747452 | SagarikaNagpal/Python-Practice | /QuesOnOops/Removing_Duplicates.py | 511 | 3.984375 | 4 | # Question: Complete the script so that it removes duplicate items from list a .
#
# a = ["1", 1, "1", 2]-- "1 is duplicate here"
# Expected output:
#
# ['1', 2, 1]
# ********************Diifferent Approach***********************
# a = ["1",1,"1",2]
# b = []
# for i in a:
# if i not in b:
# b.append(i)
# print(list(set(a)))
# ********************Diifferent Approach***********************
from collections import OrderedDict
a = ["1", 1, "1", 2]
a = list(OrderedDict.fromkeys(a))
print(a)
|
a33e791b4fc099c4e607294004888f145071e6ff | SagarikaNagpal/Python-Practice | /QuesOnOops/A22.py | 254 | 4.34375 | 4 | #Question A22: WAP to input a number. If the number is even, print its square otherwise print its cube.
import math
a=int(input("num: "))
sq = int(math.pow(a,2))
cube =int (math.pow(a,3))
if a%2==0:
print("sq of a num is ",sq)
else:
print(cube) |
cd04469d80121d7c9f10221c30f0bf4963d888d1 | SagarikaNagpal/Python-Practice | /QuesOnOops/D-7.py | 83 | 3.9375 | 4 | # Question D7: WAP to reverse an array of floats.
arr = [1,2,3,4]
print(arr[::-1]) |
470e9fa497bef6af068fa708ac1c2fb68569c71c | SagarikaNagpal/Python-Practice | /QuesOnOops/C-11.py | 140 | 4.1875 | 4 | # WAP to count all the occurrences of a character in a given string.
st = "belief"
ch = input("chk: ")
times = st.count(ch)
print(times) |
0cdf4fb881b84941e0ff4f29600092f65a65d001 | SagarikaNagpal/Python-Practice | /QuesOnOops/B-8.py | 416 | 4.0625 | 4 | name = input("name of an employee: ")
salary = int(input("input of salary: "))
HRA = 0
DA = 0
if(salary> 5000 and salary <10000):
print("Salary is in between 5000 and 10000")
HRA = salary *0.1
DA = salary * 0.05
elif(salary>10001 and salary<15000):
print("Salary is in between 10001 and 15000")
HRA = salary * 0.15
DA = salary * 0.08
print(name)
print(salary)
print(HRA)
print(DA)
|
169945565fd5ffb9c590d7a38715b3a08a8280ff | SagarikaNagpal/Python-Practice | /QuesOnOops/A-10.py | 248 | 4.34375 | 4 | # to input the number the days from the user and convert it into years, weeks and days.
days = int(input("days: "))
year = days/365
days = days%365
week = days/7
days = days%7
day = days
print("year",year)
print("week",week)
print("day",day)
|
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") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.