blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
a245c1688386bd966ee720f661926b2d1c0a1cca | abmurli/my_codes | /python_code/Self-test/ladder.py | 392 | 3.84375 | 4 | def ladder(n):
for x in range(1, n+1):
print('{}'.format(' ' * (n-x)) + '{}'.format('#' * (x)))
def ladder_1(n):
for i in range(1, n+1):
for j in range(i, n+1):
if i >=j:
print("#"*j, end= "\n")
def ladder_2(n):
for i in range(1, n+1):
print("#"*i, end="\n")
if __name__ == '__main__':
n = int(input())
ladder_1(n)
|
dbe9157c5ad08f06bb5eba7a2215892f3eef1abe | leetcode-notes/CSE20-Projects | /Assignment_1/Converter.py | 265 | 3.703125 | 4 | num = float(input())
if (num<1024):
print(num, " B")
elif (num>=1024 and num<(1024*1024)):
print(int(num/1024), " KB")
elif (num>=1024*1024 and num<(1024*1024*1024)):
print(int(num/(1024*1024)), " MB")
else:
print(int(num/(1024*1024*1024)), " GB")
|
49f433c6afc3afa42e7ce6bec9418def0613616e | minghuadev/minecraft-tests | /other-pygui/prog-py/generator-test3.py | 3,209 | 4.46875 | 4 | #!/usr/bin/env python
###################################################################
'''
this is almost a verbatim copy of itertools.product with only added
one more level of indirection when len(args)==1. this adds the ability
to pass args in a single tuble argument variable.
'''
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
if len(args) == 1:
args = args[0]
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
print result
for prod in result:
yield tuple(prod)
a=[1,2]
b=[3,4]
d=[5,6]
c=[a,b,d]
for k in product(c):
print k
for k in product(*c):
print k
###################################################################
'''
another example by searching python turn nested for loop to generator
http://code.activestate.com/recipes/578046-easily-write-nested-loops/
'''
"""Provide an iterator for automatically nesting multiple sequences.
The "nest" generator function in this module is provided to make writing
nested loops easier to accomplish. Instead of writing a for loop at each
level, one may call "nest" with each sequence as an argument and receive
items from the sequences correctly yielded back to the caller. A test is
included at the bottom of this module to demonstrate how to use the code."""
__author__ = 'Stephen "Zero" Chappell <[email protected]>'
__date__ = '17 February 2012'
__version__ = 1, 0, 0
################################################################################
def nest(*iterables):
"Iterate over the iterables as if they were nested in loops."
return _nest(list(map(tuple, reversed(iterables))))
def _nest(stack):
"Build recursive loops and iterate over tuples on the stack."
top = stack.pop()
if stack:
for v1 in top:
for v2 in _nest(stack):
yield (v1,) + v2
else:
for value in top:
yield (value,)
stack.append(top)
################################################################################
def test():
"Check the nest generator function for correct yield values."
subject = 'I He She It They Adam Eve Cain Abel Zacharias'.split()
verb = 'ate bought caught dangled elected fought got hit'.split()
complement = 'an elephant,a cow,the boot,my gun,its head'.split(',')
for sentence in nest(subject, verb, complement):
print('{} {} {}.'.format(*sentence))
if __name__ == '__main__':
test()
###################################################################
'''
my version based on an answer here
http://stackoverflow.com/questions/1280667/in-python-is-there-an-easier-way-to-write-6-nested-for-loops
by searching python turn nested for loop to generator
'''
def product2(*args):
if len(args)<1:
return
if len(args) == 1:
for x in args[0]:
yield (x,)
else:
head = args[0]
tail = args[1:]
for h in head:
for t in product2(*tail):
yield tuple( [h] + list(t) )
for k in product2(*c):
print k
|
9037338250f4b9674a35275cbff33ac5f0b348d7 | tvonsosen/CAP-code | /lowToHigh.py | 268 | 4.09375 | 4 | # function that sums all the numbers from the lower bound number given to the higher bound number given (inclusively)
def lowHigh(lowB, highB):
answer1 = 0
for i in range(lowB,highB +1):
answer1 = answer1 + i
return answer1
print(lowHigh(-2,5))
|
a940c43f131cbf3625fa014687eaa1d5c4678811 | ivSaav/Programming-Fundamentals | /R09/budgeting.py | 668 | 3.609375 | 4 | '''
BUDGETING
'''
def sort_rule(x):
return x[1]
def budgeting(budget, products, wishlist):
# sorted product dictionary (descending order)
sort_prod = sorted(products.items(), key = sort_rule, reverse = True)
sort_p = dict(sort_prod)
price_list = list(sort_p.keys())
total = 0
for item in price_list:
if item in wishlist:
total += sort_p[item] * wishlist[item]
while(total > budget):
total -= sort_p[item]
wishlist[item] -= 1
if wishlist[item] == 0:
del wishlist[item]
return wishlist
|
fc86bc45f4aeb4ccfe156080a6c0970ebe7749cf | tadvepio/Object-Oriented-Programming | /Exercise5/Codefiles/student_mammal.py | 1,266 | 3.59375 | 4 | """
Created 8.2.2021
@File: student_mammal.py
@Description: Create a dictionary with studen object as key
and a pet mammal as value
@author: Tapio Koskinen
"""
# Import necessary modules
from mammal import Mammal
from student_class import Student
def main():
# Create a dictionary to hold mammal and student
# Numbered keys is the way.
stud_pet_dic = dict()
# Create a list to hold both student and mammal object
stud_pet_lst = []
# Create both objects and store them into the
# empty list as a separate list, for convenience
myself = Student("Tapio", "Koskinen", 1337)
mypet = Mammal(1,"Bear","Tiny","Big",150,2)
stud_pet_lst.append([myself,mypet])
friend = Student("Matti","Mallikas", 100)
friendpet = Mammal(2, "Unicorn", "Fred","Medium", 500, 1.5)
stud_pet_lst.append([friend,friendpet])
# Add each pair that is in the pair list
for i in range(len(stud_pet_lst)):
stud_pet_dic[i] = stud_pet_lst[i]
# Loop through all key in the dictionary
# and print out the student and their pet
for i in stud_pet_dic:
pair = stud_pet_dic[i]
print("*"*40)
print(f"Student:\n\n{pair[0]}\n"+"-"*30,f"\nHis/her pet:\n\n{pair[1]}")
print("*"*40)
main()
|
0a7afcfef3f80b8f51bb59daffef49e74cbbd3a7 | Akitektuo/University | /1st year/PF/Lab/Assignment2/complex.py | 1,785 | 4.3125 | 4 | import math
class Complex:
# Init block
def __init__(self, real = 0, imaginary = 0):
self.real = real
self.imaginary = imaginary
# Override str()
def __str__(self):
if self.imaginary == 0:
return self.format_float(self.real)
if self.real == 0:
if self.imaginary == -1:
return "-i"
return self.format_float(self.imaginary, False) + "i"
if (self.imaginary < 0):
return self.format_float(self.real) + "-" + self.format_float(-self.imaginary, False) + "i"
return self.format_float(self.real) + "+" + self.format_float(self.imaginary, False) + "i"
'''
Formats a float number to have only 2 decimals and if it is a int, to be shown as a int
Input:
int - representing the number to be formated
(optional) bool - true to format the number if it's 1, false to return an empty string
Output: string - representing the formated number
'''
def format_float(self, number, show_1 = True):
number = round(number, 2)
if (not show_1 and number == 1):
return ""
if number == int(number):
return str(int(number))
return str(number)
'''
Checks if the instance is a real number
Input: -
Output: bool - true either the instance is a real number or not
'''
def is_real(self):
if self.imaginary == 0:
return True
return False
'''
Returns the modulus of the instance
Input: -
Output: float - representing the modulus
'''
def get_modulus(self):
return math.sqrt(self.real**2 + self.imaginary**2) |
a6204b27e9e26637fd41b1433add8bcc2fa92312 | measlesbagel/isa-281 | /HW1/Cagle-Myles-HW1-Q2.py | 409 | 3.984375 | 4 | #Cagle-Myles-HW
food = float(input("Enter the cost of food "))
tip = float(input("Enter the amount tipped: "))
ratio = (tip/food)*100
if(ratio < 10):
print("You only tipped",round(ratio,2),"% please tip better next time.")
elif(ratio >= 10 and ratio <= 20):
print("You tipped",round(ratio,),"% thats perfect keep it up!")
else:
print("You seriously tipped",round(ratio,2),"% thats way too much!")
|
9704d9e459111b7c66b56f9b66c9148e301e9370 | rporumalla/Interview_Programming_Practice | /binarySearch.py | 524 | 3.828125 | 4 | # O(log n)
def binarySearch(myList,x):
myList=sorted(myList)
low=0
high=len(myList)-1
while True:
if low>high:
return -1
mid=low+(high-low)/2
if x<myList[mid]:
high=mid-1
elif x>myList[mid]:
low=mid+1
else:
return mid
lst=[10,14,19,26,27,31,33,35,42,44]
idx=binarySearch(lst,31)
if idx==-1:
print 'Number not found'
else:
print 'Number found at index ', idx
idx=binarySearch(lst,32)
if idx==-1:
print 'Number not found'
else:
print 'Number found at index ', idx
|
110d1ac444411439845365cbddadb54c558606c5 | Tumle/Project1 | /search_file.py | 1,720 | 3.9375 | 4 | #http://www.opentechguides.com/how-to/article/python/59/files-containing-text.html
#Import os module
import os
import re
# Ask the user to enter string to search
search_path = raw_input("Enter directory path to search : ")
file_type = raw_input("File Type : ")
search_str = raw_input("Enter the search string : ")
# If path does not exist, set search path to current directory
if not os.path.exists(search_path):
search_path = "."
print search_path
# Append a directory separator if not already present
if not (search_path.endswith("/") or search_path.endswith("\\") ):
# search_path = search_path + "/"
search_path = search_path + "\\"
print search_path
# Repeat for each file in the directory
for fname in os.listdir(search_path):
print os.listdir(search_path)
# Apply file type filter
if fname.endswith(file_type):
# Open file for reading
fo = open(search_path + fname)
print fo
# Read the first line from the file
line = fo.readline()
print line
# Initialize counter for line number
line_no = 1
# Loop until EOF
while line != '' :
# Search for string in line
index = line.find(search_str)
if ( index != -1) :
# print(fname, "[", line_no, ",", index, "] ", line, sep = "")
print(fname, "[", line_no, ",", index, "] ", line)
# Read next line
line = fo.readline()
# Increment line counter
line_no += 1
# Close the files
fo.close()
print ("Done")
"Another example"
#!/usr/bin/env python
#import re
#shakes = open("wssnt10.txt", "r")
#love = open("love.txt", "w")
#for line in shakes:
# if re.match("(.*)(L|l)ove(.*)", line):
# print >> love, line,
|
c53b2b897b1ba71f36247858d310f84447dc42c4 | nurlan5t/python-homeworks | /hw15_fibonacci recursion.py | 577 | 4.34375 | 4 | '''Написать Fibonacci sequence с помощью рекурсивного метода.
Пользователь вводит число(например 8) и программа
должна вывести числа Фибоначчи до 8.'''
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = int(input('Enter integer number: '))
if nterms <= 0:
print("Please enter a positive integer: ")
else:
print(f"Fibonacci sequence: {nterms}")
for i in range(nterms):
print(recur_fibo(i))
|
06a0d6b3714108cb35bb6ad3e7758e8353395b4e | alfonsoar/SpaceApps | /services/population_density.py | 1,320 | 3.65625 | 4 | import pandas as pd
import json
import constants
def readDataForPopulationDensity(populationFileName):
"""
Should only need to be run once to generate
json file with calculated population densities
"""
headers = ["city", "area", "populationCount"]
popFile = pd.read_csv(populationFileName, names=headers)
popJsonStr = popFile.to_json(orient="records")
populations = json.loads(popJsonStr)
for p in populations:
popCount = float(p["populationCount"])
area = float(p["area"])
popDensity = popCount / (area * 1000)
p["populationDensity"] = popDensity
with open('./resources/population_with_densities.json', 'w') as fp:
json.dump(populations, fp)
def optimalPopDensityScore():
"""
sort cities by population density relative to optimal density
"""
with open("./resources/population_with_densities.json") as f:
cityList = json.load(f)
summation = 0
cityDict = {}
for city in cityList:
summation += city["populationDensity"]
diff = abs(city['populationDensity'] - constants.OPTIMAL_DENSITY)
score = (diff/constants.OPTIMAL_DENSITY) * 100
score = 100 - score
cityName = city["city"]
city["score"] = score
cityDict[cityName] = city
return cityDict
|
955dc45d6f6ce25fc05e78bfbea06125fb2fd783 | oguztimurtasdelen/PerformanceAnalysisTechnology | /driver.py | 9,401 | 3.84375 | 4 | """
Izmir University of Economics Faculty of Engineering
Project Name: Performance Analysis Technology
Lecture: FENG 498 - Graduation Project II
Supervisor: İlker KORKMAZ
Project Group: Ömer EROĞLU - Fatih KOCA - Oğuz Timur TAŞDELEN
"""
import csv # importing the csv module
import re # importing regex
import random # importing random module
from datetime import datetime
import DBmanager
def randomDataGenerator(trainingMode):
# creating random sensorNum
sensorNum = random.randint(1, 12)
responseTime = 0.0
isSuccess = 0
if trainingMode == "Easy":
responseTime = round(random.uniform(0.50, 4.00), 2)
if responseTime < 3.00:
isSuccess = 1
else:
isSuccess = 0
responseTime = 3.00
elif trainingMode == "Medium":
responseTime = round(random.uniform(0.5, 4.0), 2)
if responseTime < 2.00:
isSuccess = 1
else:
isSuccess = 0
responseTime = 2.00
elif trainingMode == "Hard":
responseTime = round(random.uniform(0.5, 4.0), 2)
if responseTime < 1.50:
isSuccess = 1
else:
isSuccess = 0
responseTime = 1.50
return sensorNum, responseTime, isSuccess
# This function checks the csv file if there is missing data or not.
def dataConfirmation(paramVar): # 'paramVar' means 'parameter variable'.
with open("training_process.csv") as file:
csv_list = list(csv.reader(file))
data = list(csv_list)
count = int(len(data) / 2) # returns float originally and make it type integer
file.close()
"""
print("paramVar:" + str(paramVar))
print("count:" + str(count))
print("")
"""
if count == paramVar:
print("Training has completed!")
return True
else:
print("There is some missing data. Please repeat the training!")
return False
def trainingProcess(playerID, trainingID, trainingMode, timeStamp):
# Easy Mode
if trainingMode == "E":
trainingMode = "Easy"
minTouch = 4
maxTouch = 24
# Medium Mode
elif trainingMode == "M":
trainingMode = "Medium"
minTouch = 6
maxTouch = 24
# Hard Mode
elif trainingMode == "H":
trainingMode = "Hard"
minTouch = 8
maxTouch = 24
# accuracy training constant=12 times sensors will light
ACCURACY_CONSTANT = 12
# name of csv file
filename = "training_process.csv"
# field names
fields = ['playerID', 'trainingID', 'sensorNum', 'responseTime', 'isSuccess', 'trainingMode', 'timeStamp']
accuracyTraining = re.compile("A-*")
speedTraining = re.compile("S-*")
# It means it is an accuracy training
if re.match(accuracyTraining, trainingID):
for i in range(ACCURACY_CONSTANT):
# print("accuracy ", i)
with open(filename, 'a+') as csvFile:
# creating a csv dict writer object
writer = csv.DictWriter(csvFile, fieldnames=fields)
randomData = randomDataGenerator(trainingMode)
# light sensor
sensorLight = randomData[0]
# getting random response time
responseTime = randomData[1]
# getting random result of random attempt
isSuccess = randomData[2]
myDict = [{'playerID': playerID, 'trainingID': trainingID, 'sensorNum': sensorLight,
'responseTime': responseTime, 'isSuccess': isSuccess, 'trainingMode': trainingMode,
'timeStamp': timeStamp}]
writer.writerows(myDict)
csvFile.close()
# Counts csv file if it is missing or not.
if dataConfirmation(ACCURACY_CONSTANT):
# no need to check if input is valid or not because this is not an actual implementation.
confirmation = input("Do you confirm the training? Y/N")
if confirmation == "Y" or confirmation == "y":
DBmanager.recorder()
print("The training has recorded to database!")
elif confirmation == "N" or confirmation == "n":
print("Not confirmed, cancel the Training!")
DBmanager.reduceSequence("trainingID")
f = open("training_process.csv", "w")
f.truncate()
f.close()
Welcome()
else:
# There is missing data in csv file. Clear the csv file and restart the training process!
print("")
f = open("training_process.csv", "w")
f.truncate()
f.close()
Welcome()
# Speed Training
else:
randomSpeed = random.randint(minTouch, maxTouch) # Generates number of touches in 12 seconds.
for i in range(randomSpeed):
# print("speed ", i)
with open(filename, 'a+') as csvFile:
# creating a csv dict writer object
writer = csv.DictWriter(csvFile, fieldnames=fields)
randomData = randomDataGenerator(trainingMode)
# light sensor
sensorLight = randomData[0]
# getting random response time
responseTime = randomData[1]
# getting random result of random attempt
isSuccess = randomData[2]
myDict = [{'playerID': playerID, 'trainingID': trainingID, 'sensorNum': sensorLight,
'responseTime': responseTime, 'isSuccess': isSuccess, 'trainingMode': trainingMode,
'timeStamp': timeStamp}]
writer.writerows(myDict)
csvFile.close()
# Counts row in csv file if there is a missing data or not.
if dataConfirmation(randomSpeed):
# no need to check if input is valid or not because this is not an actual implementation.
confirmation = input("Do you confirm the training? Y/N")
if confirmation == "Y" or confirmation == "y":
DBmanager.recorder()
print("The training has recorded to database!")
elif confirmation == "N" or confirmation == "n":
print("Not confirmed, cancel the Training!")
DBmanager.reduceSequence("trainingID")
f = open("training_process.csv", "w")
f.truncate()
f.close()
Welcome()
else:
# There is missing data in csv file. Clear the csv file and restart the training process!
print("")
f = open("training_process.csv", "w")
f.truncate()
f.close()
Welcome()
# Generates trainingID according to training type with auto incrementation
def TrainingIDGenerator(type):
lastIndex = DBmanager.getNextSequence("trainingID")
trainingID = ""
if type == 0:
trainingID = ("A-{}")
trainingID = (trainingID.format(lastIndex))
# print(trainingID.format(lastIndex))
return trainingID
elif type == 1:
trainingID = ("S-{}")
trainingID = (trainingID.format(lastIndex))
# print(trainingID.format(lastIndex))
return trainingID
def Welcome():
f = open("training_process.csv", "w")
f.truncate()
f.close()
# Section: 'Welcome'
print("\n ***WELCOME TO PERFORMANCE ANALYSIS TECHNOLOGY SYSTEM*** \n")
print("Performance Analysis Technology is used to measure performance of players in wide range sports branch and "
"to serve this measurements to coaches.")
enterKey = input("Press Enter to Start!")
# Checks if input is 'Enter' key or not.
while enterKey != "":
enterKey = ""
continue
print("\n\n\n")
print("***SETUP THE PLATFORM***")
# Section: 'Prepare the Platform'
coachID = input('Enter Coach ID: ') # Check if coach exists!
if not DBmanager.checkCoach(int(coachID)):
# just terminate the program
quit()
playerID = input('Enter Player ID: ') # Check if player exists!
if not DBmanager.checkPlayer(playerID, coachID):
# just terminate the program
quit()
print("\n\n\n")
print("***SETUP THE PLATFORM***")
print("\n0: Accuracy Measurement Training | 1: Speed Measurement Training")
trainingType = int(input('Select Training Type (Press 0 or 1): '))
print("'E': easy\n'M': medium\n'H': hard")
# No need to check if input is valid or not because this is not an actual implementation
difficultyType = input("Select Difficulty - E/M/H:")
# Actual implementation will not be terminal application. Therefore no need to check if input is valid or not.
trainingID = TrainingIDGenerator(trainingType)
enterKey = input("Ready, Go!")
# Checks if input is 'Enter' key or not.
while enterKey != "":
enterKey = ""
continue
print("\n\n\n")
# Training process starts after pressed the Enter Key.
trainingProcess(playerID, trainingID, difficultyType, timeStamp())
print("\n\n\n")
print("Process has finished!")
# process is completed for one step for now
def timeStamp():
time = datetime.now()
stamp = time.strftime("%d.%m.%Y, %H:%M")
return stamp
Welcome()
|
a8f563cc2ee4ef7064a6d329d676963610243478 | Shivanshgarg-india/pythonprogramming-day4 | /class and object/questio 4.py | 468 | 4.125 | 4 | # Write a Python class named Student with two attributes student_id, student_name. Add a new attribute student_class. Create a function to display the entire attribute and their values in Student class
class Student:
student_id = 'V10'
student_name = 'Jacqueline Barnett'
def display():
print(f'Student id: {Student.student_id}\nStudent Name: {Student.student_name}')
print("Original attributes and their values of the Student class:")
Student.display() |
8552ba656127ae33182510c3d8a4a2870ecbe0ed | BrianS3-Git/day-2-3-excercise-time-left | /main.py | 383 | 3.796875 | 4 | # 🚨 Don't change the code below 👇
age = input("What is your current age? ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
age_as_int = int(age)
daysLeft = (90 - age_as_int) * 365
weeksLeft = (90 - age_as_int) * 52
monthsLeft = (90 - age_as_int) * 12
print(f"You have {daysLeft} days, {weeksLeft} weeks, and {monthsLeft} months left")
|
682c691f9c955f6500e4a6a85978cb341ae16118 | mklsw/python-learning | /basic/output/print.py | 704 | 4.1875 | 4 | x = 7 **6
print (x)
a = 10 # int
b = 3.14 # float
c = 3 # int
d = a **2 # square of a
print (type(d)) #return the type of d
print (type(d//10)) # return the type of d/10
print (type(a/b)) # return the type of a/b
print (type(a/c)) # return the type of a/c
print (type(b*d)) # return the type of b*d
x = 7 **6
print (x)
a = 10 # int
b = 3.14 # float
c = 3 # int
d = a **2 # square of a
print (type(d)) #return the type of d
print (type(d//10)) # return the type of d/10
print (type(a/b)) # return the type of a/b
print (type(a/c)) # return the rype of a/c
print (type(b*d)) # return the type of b*d
a, b, c, = 5 ,3.2, "hello"
print(a)
print(b)
print(c)
print(help(print))
|
3feaf460ab4669f87971fba67339e027f1ff10cc | KennyMcD/Blackjack | /blackjack.py | 13,013 | 4.09375 | 4 | """
@author: Kenneth McDonnell
"""
import random
# Dictionary for card values
cardVal = {
'A': 11,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10
}
MAX_CARDS = 52
"""
Create card object with a suit and rank to be used for deck and hand
@author: Kenneth McDonnell
"""
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
# Purpose: return the rank of card
# Input: n/a
# Return: rank
def getRank(self):
return self.rank
# Purpose: return suit of card
# Input: n/a
# Return: suit
def getSuit(self):
return self.suit
"""
Creates a deck object so players can draw; keeps track of cards remaining
@author Kenneth McDonnell
"""
class Deck:
def __init__(self, cards, cardsLeft):
self.cards = []
self.cardsLeft = MAX_CARDS
# Purpose: Appends set of 13 cards based on suit to cards array
# Input: suit
# Return: n/a
def appendSuit(self, suit):
for key in cardVal.keys():
self.cards.append(Card(suit, key))
# Purpose: Creates deck array by calling appendSuit for every suit
# Input: n/a
# Return: n/a
def createDeck(self):
self.appendSuit("♣")
self.appendSuit("♦")
self.appendSuit("♥")
self.appendSuit("♠")
# Purpose: Shuffle the deck in random order; uses random library
# Input: n/a
# Return: n/a
def shuffle(self):
random.shuffle(self.cards)
# Purpose: Return card; remove it from deck
# Input: n/a
# Return: card object from top of deck
def dealCard(self):
self.cardsLeft -= 1
return self.cards.pop()
# Purpose: Prints contents of deck; used for testing/debugging
# Input: n/a
# Return: n/a
def dumpDeck(self):
cards = 0
for i in range(self.cardsLeft):
print(str(self.cards[i].getRank()) + " " + str(self.cards[i].getSuit()) + '\n')
cards += 1
print(cards)
"""
Hand object for each players; starts with 2 cards; allows player to draw cards
@author Kenneth McDonnell
"""
class Hand:
def __init__(self, deck):
self.deck = deck
self.numCards = 0
def setNumCards(self, cards):
self.numCards = cards
# Purpose: Adds one card to a player's hand
# Input: player's hand
# Return: updated player's hand with new card
def draw(self, hand):
self.numCards += 1
hand.append(self.deck.dealCard())
return hand
# Purpose: Calculates value of player's current hand; handles aces
# Input: player's hand
# Return: value of player's hand
def handValue(self, hand):
handVal = 0
ace = 0
for i in range(self.numCards):
handVal += cardVal[hand[i].getRank()]
if (hand[i].getRank() == 'A'):
ace += 1
# Handles aces; also handles if 2 or more aces are drawn
while (handVal > 21 and ace > 0):
handVal -= 10
ace -= 1
return handVal
# Purpose: Prints player's hand with string formatting
# Input: player's hand
# Return: n/a
def dumpHand(self, hand):
print("Hand")
for i in range(self.numCards):
r = str(hand[i].getRank())
s = str(hand[i].getSuit())
print("┌─────────┐")
print("│"+"{0:2s}".format(r)+" │")
print("│ │")
print("│ │")
print("│ "+s+" │")
print("│ │")
print("│ │")
print("│ "+"{0:2s}".format(r)+"│")
print("└─────────┘")
"""
Player object; can hit or stay; checks for blackjack on initial hand
@author Kenneth McDonnell
"""
class Player:
def __init__(self, hand, deck):
self.hand = Hand(deck)
self.currHand = []
self.stay = False
self.bust = False
self.blackjack = False
# Purpose: Adds one card to player's hand; accounts for busts
# Input: n/a
# Return: n/a
def hit(self):
self.hand.draw(self.currHand)
handVal = self.hand.handValue(self.currHand)
# Checks for blackjack
if (handVal > 21):
self.bust = True
elif (handVal == 21):
self.blackjack = True
# Purpose: Draws two cards for player and checks for blackjack
# Input: n/a
# Return: n/a
def startingHand(self):
# Draw 2 cards
self.hit()
self.hit()
# Blackjack check
handVal = self.hand.handValue(self.currHand)
if (handVal == 21):
self.blackjack = True
# Purpose: Get amount of cards in player's hand
# Input: n/a
# Return: length of player's hand array
def handSize(self):
return len(self.currHand)
# Purpose: Set when player chooses to stay
# Input: n/a
# Return: n/a
def setStay(self):
self.stay = True
# Purpose: Get whether player decides to stay
# Input: n/a
# Return: stay bool
def getStay(self):
return self.stay
# Purpose: Get if player busts; set when hand value > 21
# Input: n/a
# Return: bust bool
def getBust(self):
return self.bust
# Purpose: Get if player has blackjack; hand value = 21
# Input: n/a
# Return: blackjack bool
def getBlackjack(self):
return self.blackjack
# Purpose: Print players current hand
# Input: n/a
# Return: returns current hand value
def dumpPlayerHand(self):
self.hand.dumpHand(self.currHand)
handVal = self.hand.handValue(self.currHand)
print(handVal)
return handVal
"""
Dealer class which inherits player; Dealer is a player, although they show
their first card in hand.
@author Kenneth McDonnell
"""
class Dealer(Player):
def __init__(self, hand, deck):
self.hand = Hand(deck)
self.currHand = []
self.stay = False
self.bust = False
self.blackjack = False
# Purpose: Show first card of dealers hand (like in real blackjack)
# Input: n/a
# Return: n/a
def peekFirst(self):
r = str(self.currHand[0].getRank())
s = str(self.currHand[0].getSuit())
print("┌─────────┐")
print("│"+"{0:2s}".format(r)+" │")
print("│ │")
print("│ │")
print("│ "+s+" │")
print("│ │")
print("│ │")
print("│ "+"{0:2s}".format(r)+"│")
print("└─────────┘")
"""
Creates Game object which starts, runs, and ends game based on win conditions
@author Kenneth McDonnell
"""
class Game():
def __init__(self):
self.cards = []
self.deck = Deck(self.cards, MAX_CARDS)
self.deck.createDeck()
self.deck.shuffle()
self.playerHand = Hand(self.deck)
self.player = Player(self.playerHand, self.deck)
self.dealerHand = Hand(self.deck)
self.dealer = Dealer(self.dealerHand, self.deck)
# Purpose: Runs the main menu and main game loop; checks for win conditions
# Input: n/a
# Return: n/a
def runGame(self):
# Running the game
print("Welcome to Blackjack!")
choice = input("1) Start \n2) Exit\n")
if choice == '1':
playagain = True
while (playagain == True):
# Start game
# Dealer Draw
print("Dealer's Peek")
self.dealer.startingHand()
self.dealer.peekFirst() # Print dealer's first card
print('\n')
# Player turn
print("Human's turn")
self.player.startingHand()
# Allows the player to stay or hit until they bust or get blackjack
while (self.player.getStay() != True):
self.player.dumpPlayerHand()
# Loop menu for human player
play = input("1) Hit\n2) Stay\n")
# Hit
if (play == '1'):
self.player.hit()
if (self.player.getBust() == True):
print("Human Bust")
self.player.setStay()
elif (self.player.getBlackjack() == True):
print("Human Blackjack")
self.player.setStay()
# Stay
elif (play == '2'):
self.player.setStay()
playerVal = self.player.dumpPlayerHand() # Print player's hand
# Dealer turn
print("\nDealer's turn")
dealerVal = self.dealer.dumpPlayerHand() # Reveal dealer's hand
# Checking if player gets blackjack on starting hand
if (self.player.handSize() == 2 and self.player.getBlackjack() == True and self.dealer.getBlackjack() == False):
print("Human wins!")
# Checking if dealer gets blackjack on starting hand
elif (self.dealer.getBlackjack() == True and self.player.getBlackjack() == False):
print("Dealer Wins!")
# Both players have blackjack on their starting hands
elif (self.player.handSize() == 2 and self.player.getBlackjack() == True and self.dealer.getBlackjack() == True):
print("Tie game!")
print("Dealer Wins!")
else:
# Dealer hits when hand value is less than 17
while (dealerVal < 17):
self.dealer.hit()
dealerVal = self.dealer.dumpPlayerHand()
print("\n")
self.dealer.setStay()
# Cases for if either player has blackjack or busts
# Dealer busts, player stayed or has blackjack
if (self.dealer.getBust() == True and self.player.getBust() == False):
print("Dealer Bust")
print("Human Wins!")
# Player busts, dealer stayed or has blackjack
elif (self.dealer.getBust() == False and self.player.getBust() == True):
print("Human Bust")
print("Dealer Wins!")
# Dealer has blackjack and the player doesn't or busts
elif (self.dealer.getBlackjack() == True and self.player.getBlackjack() == False):
print("Dealer Blackjack")
print("Dealer Wins!")
# Both players bust; dealer wins
elif (self.dealer.getBust() == True and self.player.getBust() == True):
print("Dealer Wins!")
# Both players reach blackjack after hitting
elif (self.dealer.getBlackjack() == True and self.player.getBlackjack() == True):
print("Tie Game!")
else:
# Comparing hand values if no player busts or gets blackjack
if (dealerVal < playerVal):
print("Player Wins!")
elif (dealerVal > playerVal):
print("Dealer Wins!")
elif (dealerVal == playerVal):
print("Tie Game!")
pa = input("Play again?(y/n) ")
# Restart the game; instantiate new objects
if (pa == 'y'):
playagain = True
# Creates deck
cards = []
self.deck = Deck(cards, MAX_CARDS)
self.deck.createDeck()
self.deck.shuffle()
# Creates human player
playerHand = Hand(self.deck)
self.player = Player(playerHand, self.deck)
# Creates dealer player
dealerHand = Hand(self.deck)
self.dealer = Dealer(dealerHand, self.deck)
# End game
else:
playagain = False
print("Goodbye")
else:
print("See you next time!")
def main():
# Main
game = Game()
game.runGame()
if __name__ == "__main__":
main() |
48ea4b5c6ba89b4e488b774579ab9d4fd201f8f3 | rvmoura96/distance-optimizer | /truck.py | 766 | 3.640625 | 4 | """Using Python 3.6."""
from cargo import Cargo
from haversine import haversine
class Truck:
def __init__(
self, truck: str, city: str, state: str, lat: float, lng: float
) -> None:
self.truck = truck
self.city = city
self.state = state
self.lat = lat
self.long = lng
def shipment(self, cargo: Cargo) -> str:
"""Return what truck should deliver."""
return cargo.product
def distance_to_cargo(self, cargo: Cargo) -> float:
"""Return the distance between the truck and his shipment."""
distance_to_cargo = haversine(
self.lat, self.long, cargo.origin_lat, cargo.origin_long
)
return distance_to_cargo
if __name__ == "__main__":
pass
|
45d408c1bf1c8a71dce2e531d58ee795d6ab21b2 | neilpelow/Security | /vigenere.py | 907 | 3.890625 | 4 | from itertools import cycle
ALPHA = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.1234567890'
myKey = "FACEBOOKPASSWORD"
myText = "Yhwvtroi, 28 Yuqa 2016"
def encrypt(key, plaintext):
"""Encrypt the string and return the ciphertext"""
pairs = zip(plaintext, cycle(key))
result = ''
for pair in pairs:
total = reduce(lambda x, y: ALPHA.index(x) + ALPHA.index(y), pair)
result += ALPHA[total % 26]
return result.lower()
def decrypt(key, ciphertext):
"""Decrypt the string and return the plaintext"""
pairs = zip(ciphertext, cycle(key))
result = ''
for pair in pairs:
total = reduce(lambda x, y: ALPHA.index(x) - ALPHA.index(y), pair)
result += ALPHA[total % 26]
return result
def show_result(plaintext, key):
print 'Decrytped: %s' % decrypted
decrypted = decrypt(myKey, myText)
show_result(decrypted, myKey)
|
e31f0f77128d8c672486570f1f445eba9f8fc7c6 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4005/codes/1590_1446.py | 259 | 3.78125 | 4 | # Teste seu codigo aos poucos.
var = input("litros:")
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
d= float(var)/3
restante = round(d,3)
print(restante)
|
4b5b879655f95e253d7e3a12f20cf86b35929407 | jbelke/catalyst | /catalyst/examples/simple_universe.py | 6,176 | 3.53125 | 4 | """
Requires Catalyst version 0.3.0 or above
Tested on Catalyst version 0.3.3
These example aims to provide and easy way for users to learn how to collect data from the different exchanges.
You simply need to specify the exchange and the market that you want to focus on.
You will all see how to create a universe and filter it base on the exchange and the market you desire.
The example prints out the closing price of all the pairs for a given market-exchange every 30 minutes.
The example also contains the ohlcv minute data for the past seven days which could be used to create indicators
Use this as the backbone to create your own trading strategies.
Variables lookback date and date are used to ensure data for a coin existed on the lookback period specified.
"""
import numpy as np
import pandas as pd
from datetime import timedelta
from catalyst import run_algorithm
from catalyst.exchange.exchange_utils import get_exchange_symbols
from catalyst.api import (
symbols,
)
def initialize(context):
context.i = -1 # counts the minutes
context.exchange = context.exchanges.values()[0].name.lower() # exchange name
context.base_currency = context.exchanges.values()[0].base_currency.lower() # market base currency
def handle_data(context, data):
context.i += 1
lookback_days = 7 # 7 days
# current date formatted into a string
today = data.current_dt
date, time = today.strftime('%Y-%m-%d %H:%M:%S').split(' ')
lookback_date = today - timedelta(days=lookback_days) # subtract the amount of days specified in lookback
lookback_date = lookback_date.strftime('%Y-%m-%d %H:%M:%S').split(' ')[0] # get only the date as a string
# update universe everyday
new_day = 60 * 24 # assuming data_frequency='minute'
if not context.i % new_day:
context.universe = universe(context, lookback_date, date)
# get data every 30 minutes
minutes = 30
one_day_in_minutes = 1440 # 1440 assumes data_frequency='minute'
lookback = one_day_in_minutes / minutes * lookback_days # get N lookback_days of history data
if not ((context.i % minutes) - minutes + 1) and context.universe: # fetch data at last minute of the candle
# we iterate for every pair in the current universe
for coin in context.coins:
pair = str(coin.symbol)
# 30 minute interval ohlcv data (the standard data required for candlestick or indicators/signals)
# 30T means 30 minutes re-sampling of one minute data. change to your desire time interval.
opened = fill(data.history(coin, 'open', bar_count=lookback, frequency='30T')).values
high = fill(data.history(coin, 'high', bar_count=lookback, frequency='30T')).values
low = fill(data.history(coin, 'low', bar_count=lookback, frequency='30T')).values
close = fill(data.history(coin, 'price', bar_count=lookback, frequency='30T')).values
volume = fill(data.history(coin, 'volume', bar_count=lookback, frequency='30T')).values
# close[-1] is the equivalent to current price
# displays the minute price for each pair every 30 minutes
print(today, pair, opened[-1], high[-1], low[-1], close[-1], volume[-1])
# ----------------------------------------------------------------------------------------------------------
# -------------------------------------- Insert Your Strategy Here -----------------------------------------
# ----------------------------------------------------------------------------------------------------------
def analyze(context=None, results=None):
pass
# Get the universe for a given exchange and a given base_currency market
# Example: Poloniex BTC Market
def universe(context, lookback_date, current_date):
json_symbols = get_exchange_symbols(context.exchange) # get all the pairs for the exchange
universe_df = pd.DataFrame.from_dict(json_symbols).transpose().astype(str) # convert into a dataframe
universe_df['base_currency'] = universe_df.apply(lambda row: row.symbol.split('_')[1],
axis=1)
universe_df['market_currency'] = universe_df.apply(lambda row: row.symbol.split('_')[0],
axis=1)
# Filter all the exchange pairs to only the ones for a give base currency
universe_df = universe_df[universe_df['base_currency'] == context.base_currency]
# Filter all the pairs to ensure that pair existed in the current date range
universe_df = universe_df[universe_df.start_date < lookback_date]
universe_df = universe_df[universe_df.end_daily >= current_date]
context.coins = symbols(*universe_df.symbol) # convert all the pairs to symbols
# print(universe_df.symbol.tolist())
return universe_df.symbol.tolist()
# Replace all NA, NAN or infinite values with its nearest value
def fill(series):
if isinstance(series, pd.Series):
return series.replace([np.inf, -np.inf], np.nan).ffill().bfill()
elif isinstance(series, np.ndarray):
return pd.Series(series).replace([np.inf, -np.inf], np.nan).ffill().bfill().values
else:
return series
if __name__ == '__main__':
start_date = pd.to_datetime('2017-11-10', utc=True)
end_date = pd.to_datetime('2017-11-13', utc=True)
performance = run_algorithm(start=start_date, end=end_date,
capital_base=100.0, # amount of base_currency, not always in dollars unless usd
initialize=initialize,
handle_data=handle_data,
analyze=analyze,
exchange_name='bitfinex',
data_frequency='minute',
base_currency='btc',
live=False,
live_graph=False,
algo_namespace='simple_universe')
"""
Run in Terminal (inside catalyst environment):
python simple_universe.py
"""
|
ef723bbff557577e369c0342db99af5912fcbf28 | thatguy0999/PythonCodes | /Python2/Ex50.py | 582 | 4.0625 | 4 | from math import sqrt
a = float(input('what will be the value of a '))
b = float(input('what will be the value of b '))
c = float(input('what will be the value of c '))
no_roots = (b**2)-(4*a*c)
if no_roots < 0:
print('there are no intersections with the x axis')
elif no_roots == 0:
print('there is a repeated intersection / one intersection with the x axis')
print(f'{(-b+sqrt(no_roots))/2*a:.3f}')
elif no_roots > 0:
print('there are two intersections with the x axis')
print(f'{(-b+sqrt(no_roots))/2*a:.3f}')
print(f'{(-b-sqrt(no_roots))/2*a:.3f}')
|
68308b935782c09d34cf1e2457da6d42a815d549 | MozartArthur/Programming-3-4-5-6 | /Тема 8. Встроенные коллекции/ВСР.py | 1,614 | 4.21875 | 4 | # Создание программы, позволяющей выполнять основные операции (объединение, пересечение, вычитание) над множествами (количество множеств и их элементы вводятся вручную)
def set_array(count: int):
i = 1
arrays = []
while i <= count:
a = input("Введите множество " + str(i) + ": ")
a = a.split(",")
for j in range(len(a)):
a[j] = int(a[j])
arrays.append(a)
i += 1
return arrays
def calc():
count_arrays = int(input(' Введите количество множеств:\n'))
choice = input(' Введите номер действия: \n 1.Объединение, 2.Пересечение, 3.Вычитание\n')
if choice == '1':
arrays = set_array(count_arrays)
result = set(arrays[0])
for i in range(1, len(arrays)):
result |= set(arrays[i])
print("Результат:", result)
elif choice == '2':
arrays = set_array(count_arrays)
result = set(arrays[0])
for i in range(1, len(arrays)):
result &= set(arrays[i])
print("Результат:", result)
elif choice == '3':
arrays = set_array(count_arrays)
result = set(arrays[0])
for i in range(1, len(arrays)):
result -= set(arrays[i])
print("Результат:", result)
else:
print('Некорректный ввод')
calc() |
0e2c2d0ed852a4a94d4fab12a020515b6a6c486e | erinspace/NightSkyNetwork | /NsN_project.py | 826 | 4 | 4 | requesters = {'Erin': 3, 'Mary': 5, 'Sue':1, 'Frank': 2}
MAXIMUM_REQUESTS = 5
def show_requesters():
for name, request in requesters.items():
print '{0:5} has requested {1:5d}'.format(name, request)
def new_entry():
new_name = raw_input('Please enter your name: ')
new_request = int(raw_input('Enter a number of items you want: '))
if new_name in requesters:
total = requesters[new_name]+new_request
if total<=MAXIMUM_REQUESTS:
requesters[new_name] = total
show_requesters()
else:
print 'You already requested the maximum.'
show_requesters()
else:
if new_request<=MAXIMUM_REQUESTS:
requesters[new_name] = new_request
show_requesters()
else:
print 'You can only have {0} items'.format(MAXIMUM_REQUESTS)
requesters[new_name] = MAXIMUM_REQUESTS
show_requesters()
new_entry()
|
c93b87e7a6b5d95292d4ebc28b23fe7904a55a68 | vo-andrew/interview-prep | /epi/5.5.py | 1,111 | 4.03125 | 4 | """
Delete Duplicates From A Sorted Array
Input:
A sorted array with duplicate values.
Output:
An array with the duplicate values removed.
"""
def solution(A):
"""
We want to overwrite duplicate values with new values that we see in one pass.
"""
available = 1
for i in range(1, len(A)):
if A[available - 1] != A[i]: # We look at available - 1 because we know that a duplicate value can only be at the current position of available. available - 1 should be the start position of where the duplicates occur. Since a duplicate value can only occur at the current position of available, this makes A[available] a candidate for being overwritten. We cannot compare the value of the current element we are looking at to A[available] because A[available] is not necessarily a duplicate value.
A[available] = A[i]
available += 1
return A
print(solution([2, 3, 5, 5, 7, 11, 11, 11, 13]))
# Time Complexity: O(N) because we traverse through the array in one pass.
# Space Complexity: O(1) because we do not allocate any extra memory to hold data.
|
8fc898c47a3fb1e427a8278c550f8e7859593707 | sohannaik7/python-fun-logic-programs- | /fun_with_dates.py | 975 | 4.15625 | 4 | from datetime import datetime
def checkdate(date):
monthNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
month, day, year = date.split('/')
if int(year) % 4 == 0 or int(year) % 400 == 0:
print("This ",year, "is a leap year")
else:
print("This ",year, "isn't a leap year")
return monthNames[eval(month)-1] + "," + day + ', ' + year
def totaldays(date,date_format,dob):
a = datetime.strptime(date, date_format)
b = datetime.strptime(dob, date_format)
return a - b
if __name__ == '__main__':
date = input("enter the date..m/d/y")
dob = input("enter your birth date....m/d/y")
print("todys date is ", checkdate(date))
print("..............")
print("your birth date is ", checkdate(dob))
date_format = "%m/%d/%Y"
tot = totaldays(date,date_format,dob)
print("total number of days from ",dob," to ",date," is ",tot.days)
|
993b3423859cc6016ef1af0463891f4fdf1a89f7 | tkazusa/TDD-python-practice | /chapter05/money/franc.py | 274 | 3.703125 | 4 | class Franc(object):
""" franc class"""
def __init__(self, amount: int):
self._amount = amount
def times(self, multiplier: int):
return Franc(self._amount * multiplier)
def __eq__(self, other):
return self._amount == other._amount
|
4983c1571119d44f8bade6b9d7fd877ae4a96d97 | Nurdilin/cryptography | /nullCipher/nullCipher_decode.py | 624 | 3.90625 | 4 | #!/usr/bin/python
# Decode Null Cipher
def decode(encryptedText, charPosition):
decodedText = ""
for word in encryptedText.split():
if (word[charPosition] >= 'A' and word[charPosition] <= 'Z') or (word[charPosition] >= 'a' and word[charPosition] <= 'z'):
decodedText += word[charPosition]
return decodedText
if __name__ == "__main__":
keyPosition = 2 #key is the second letter of each word
f = open("ciphertext.txt", "r")
o = open("plaintext.txt", "w")
o.write(decode(f.read(), keyPosition-1))
f.close()
o.close()
f = open("plaintext.txt", "r")
print("Decoded Text:")
print(f.read())
f.close() |
ca9b04c06bdf1d8ef0b18ec70b976de06da78327 | htostes/hello-world | /CursoEmVideoPython/Desafio092.py | 501 | 3.765625 | 4 | from datetime import date
pessoa = {'nome': str(input('Nome: ').strip()),
'idade': date.today().year-int(input('Ano de nascimento: ')),
'CTPS': int(input('CTPS (Só números): '))}
if pessoa['CTPS'] != 0:
pessoa['contratacao'] = int(input('Ano de contratação: '))
pessoa['salario'] = int(input('Salario: R$'))
pessoa['aposentadoria'] = pessoa['idade'] + 35 - (date.today().year - pessoa['contratacao'])
for k, v in pessoa.items():
print(f'{k} tem o valor {v}')
|
2ebbb8450eea8134d6fa09738d44c1acfb092ad8 | FelipeGabrielAmado/Uri-Problems | /Iniciantes/1065.py | 116 | 3.6875 | 4 | par = int(0)
for x in range(1, 6):
A = int(input())
if (A%2 == 0):
par += 1
print("%d valores pares" %par)
|
435c49090f8b6f6902623521c4905f93c085f127 | sebastian011511/Blackjack | /BlackJack.py | 7,737 | 4.0625 | 4 | """
Sebastian Vasco
This program allows the user to play the game of blackjack to a very limited extent
Fall 2017
"""
# Todo: Change minimum from 100 to 1000
from tkinter import *
import tkinter.messagebox as box
import random
total_made_lost=0
def PlayGame():
# () rather than [] makes array immutable
faces = ('Ace', 2, 3, 4, 5, 6, 7, 8, 9, 'Jack', 'Queen', 'King')
suits = ('Spades', 'Hearts', 'Diamonds', 'Clubs')
total_points=0
global total_made_lost
# random face and suit
rand_face = 0 # str(random.choice(faces))
rand_suit = 0 # str(random.choice(suits))
card_value=['Starting Game...','Cards Pulled:\n\n']
card_value_counter = 0 # This is used to use in text body of message box
round_counter = 0 # To use in message box to display number of times a card has been played
round_title="Deck:" # Title of message box
game_limit = -1000
# loops until you stop of go over game limit= 21
while True:
"""
If round counter is 0, display starting game message box OR if # of round counter is greater than 1, display
message box with the first two cards drawn. When starting the game, you have to automatically pull two cards.
This if statement allows to only show message box when starting game and when you have done the loop twice
displaying the first two cards. After the first two loops, user needs to click yes to pull next one.
"""
if round_counter > 1 or round_counter == 0:
another_around=box.askyesno(round_title , card_value[card_value_counter])
round_title="Cards Pulled:" # Message box title
# If YES is clicked to start game
if another_around == 1:
rand_face=str(random.choice(faces))
rand_suit=str(random.choice(suits))
# Collecting points based on value of card
if rand_face == 'Ace':
if total_points <= 10:
total_points += 11
else:
total_points += 1
elif rand_face == 'Jack' or rand_face == 'Queen' or rand_face == 'King':
total_points += 10
else:
total_points += int(rand_face)
# if points are over 21, you lost the bet, else
if total_points >= 22:
# looses bet
total_made_lost -= 50
# If user looses more than $1,000, quit game
if total_made_lost <= game_limit:
"""
If the player looses the round, check for funds. If funds are below -$1,000, then
display message box with game over notice & close game
"""
game_ending_message="GAME OVER--YOU ARE OUT OF FUNDS!\n" \
"Current Funds: $"+str(total_made_lost)+"\n" \
"You scored: "+str(total_points)+" points"+"\n" \
"Last Card Pulled: "+str(rand_face)+" of "+str(rand_suit)
close_notice=box.showwarning("Game Ending...",game_ending_message)
window.destroy() # Close program
print('GAME OVER--RAN OUT OF FUNDS!!!!!')
break
# Else you loose game but can pay again
else:
sorry_message="You Lost the game, you went over 21:\n" \
"Last Card Pulled: "+str(rand_face)+" of "+str(rand_suit) + \
"\nYou scored: "+str(total_points)+" points" + \
"\nTotal Funds: $"+str(total_made_lost)
box.showinfo('Sorry',sorry_message)
break
# You reach exactly 21 points, you win
elif total_points == 21:
total_made_lost += 100
winning_message = "You Won the game! \nYou scored: " + str(total_points)+"\nWinning Amount: $" \
+ str(100)+"\nLast Card Pulled: "+str(rand_face)+" of "+str(rand_suit)+\
"\n\nTotal Funds: $" + str(total_made_lost)
box.showinfo('Congrats!', winning_message)
break
round_counter += 1
card_value[1]+=str(round_counter)+". "+str(rand_face)+" of "+str(rand_suit)+"\n" \
"Total Points: "+str(total_points)+"\n\n"
if card_value_counter < 1:
card_value_counter += 1
print("Points: ",total_points)
print("Funds: ",total_made_lost)
# If NO is clicked to not start the game
else:
break
# Debugging purposes
print(rand_face)
print(rand_suit)
print("Points: ",total_points)
print("Funds: ",total_made_lost)
def DisplayFunds():
funds_message='\nTotal Funds: $ %s' % total_made_lost # Display text and subs %s for actual value of total funds
box.showinfo('Displaying Funds',funds_message)
def ResetFunds():
funds_message='\nYou are about to reset your funds.\n' \
'Are you sure you want to reset your funds?'
reset_notice=box.askyesno("Reset Your Funds",funds_message)
if reset_notice==1:
global total_made_lost
total_made_lost=0
box.showwarning("Reset Funds","Your funds were reset to $0.")
def Quit():
closeNotice=box.askyesno("Quit Game","Are you sure you want to QUIT GAME?")
if closeNotice==1: # yes
box.showinfo('Good Bye','You have quit the Game...')
window.destroy() # Close program
window = Tk()
window.title('Black Jack in Python!')
window.geometry("600x375")
window.resizable(0, 0) # Window is not resizable
window.configure(bg='white')
menu=Menu(window)
window.config(menu=menu)
gameMenu=Menu(menu)
# Create the menu which calls methods above
menu.add_cascade(label='Select Game Options',menu=gameMenu)
gameMenu.add_command(label='1. Play the Game',command=PlayGame)
gameMenu.add_command(label='2. Display Available Funds',command=DisplayFunds)
gameMenu.add_command(label='3. Reset Funds to Zero',command=ResetFunds)
gameMenu.add_separator()
gameMenu.add_command(label='4. Quit',command=Quit)
main_menu="\nWelcome to the Game of Blackjack\n"
labelWindow=Message(window,text=main_menu, fg="dark green",bg='white') # Display main menu
# Method calls other methods that correspond to radio buttons in selection
def dialog():
if menu_selection.get() == 1:
PlayGame()
elif menu_selection.get() == 2:
DisplayFunds()
elif menu_selection.get() == 3:
ResetFunds()
elif menu_selection.get() == 4:
Quit()
# Value of the radio button
menu_selection=IntVar()
radio_1=Radiobutton(window,text='1. Play the Game',font="times 14",fg='dark red',bg='white',
variable=menu_selection,value=1)
radio_2=Radiobutton(window,text='2. Display Available Funds',font="times 14",fg='dark red',bg='white',
variable=menu_selection,value=2)
radio_3=Radiobutton(window,text='3. Reset Funds to Zero',font="times 14",fg='dark red',bg='white',
variable=menu_selection,value=3)
radio_4=Radiobutton(window,text='4. Quit the Game',font="times 14",fg='dark red',bg='white',
variable=menu_selection,value=4)
radio_1.select()
labelWindow.config(font=('times', 20, 'bold'), bg='white', justify='center') # sets menu display style
labelWindow.pack(side=TOP)
btn=Button(window,text=" Select ", fg='dark green', font='bold', bg='dark grey', command=dialog)
radio_1.pack()
radio_2.pack()
radio_3.pack()
radio_4.pack()
btn.pack(pady=10)
window.mainloop()
|
78050a6ab7fb76e3d6da51cd0a524a5cb072792a | thatsmysky/Python-Program-Five | /PROGRAM 5 CODE.py | 3,393 | 4.0625 | 4 | import csv
def try_open(file):
try:
opening_file = open(file, 'r')
return True
except IOError:
print("I'm sorry, that file cannot be opened, please try again.")
except:
print("Please try again")
def try_output(file):
try:
opening_file = open(file, 'a')
return True
except IOError:
print("I'm sorry, that file cannot be opened, please try again.")
except:
print("Please try again")
def fill_months(mon, Mon):
key = str(keys)
mons = str(mon)
if mons in key:
Mon.append(Months[keys])
return Mon
def Avg_Rain(key,value):
value = '{:.2f}'.format(value)
AvgMonths[key] = value
return AvgMonths
Months = {}
AvgMonths = {}
Jan = []
Feb = []
Mar = []
Apr = []
May = []
Jun = []
Jul = []
Aug = []
Sep = []
Oct = []
Nov = []
Dec = []
lines = []
Open_File = True
while Open_File == True:
##Input:
## Ask user what file they would like to open
File = input("What file would you like to open? ")
## If that does not work because the file does not exist:
while (".csv") not in File:
print("That is not a valid file format.")
File = input("What file would you like to open? ")
## Try/Except:
try_open(File)
##Second input:
## Ask user what file they would like to output to
Output_File = input("What file would you like to write to?")
while (".csv") not in File:
print("That is not a valid file format.")
Output_File = input("What file would you like to open? ")
try_output(Output_File)
Input_File = open(File, 'r')
##Iterate through the csv file line by line
for line in Input_File:
Line = line.split(',')
Line[1] = Line[1][:-1]
if not Line[1].isalpha():
Month = int(Line[0])
Months[Month] = float(Line[1])
for keys in Months:
key = str(keys)
if '0001' in key:
Jan.append(Months[keys])
fill_months('0001',Jan)
fill_months('0002',Feb)
fill_months('0003',Mar)
fill_months('0004',Apr)
fill_months('0005',May)
fill_months('0006',Jun)
fill_months('0007',Jul)
fill_months('0008',Aug)
fill_months('0009',Sep)
fill_months('0010',Oct)
fill_months('0011',Nov)
fill_months('0012',Dec)
SumJan = sum(Jan)/len(Jan)
SumFeb = sum(Feb)/len(Feb)
SumMar = sum(Mar)/len(Mar)
SumApr = sum(Apr)/len(Apr)
SumMay = sum(May)/len(May)
SumJun = sum(Jun)/len(Jun)
SumJul = sum(Jul)/len(Jul)
SumAug = sum(Aug)/len(Aug)
SumSep = sum(Sep)/len(Sep)
SumOct = sum(Oct)/len(Oct)
SumNov = sum(Nov)/len(Nov)
SumDec = sum(Dec)/len(Dec)
Avg_Rain(200001,SumJan)
Avg_Rain(200002,SumFeb)
Avg_Rain(200003,SumMar)
Avg_Rain(200004,SumApr)
Avg_Rain(200005,SumMay)
Avg_Rain(200006,SumJun)
Avg_Rain(200007,SumJul)
Avg_Rain(200008,SumAug)
Avg_Rain(200009,SumSep)
Avg_Rain(200010,SumOct)
Avg_Rain(200011,SumNov)
Avg_Rain(200012,SumDec)
YearRain = []
Output_File = open(Output_File, 'a')
for year, value in AvgMonths.items():
Output_File.write('{},{}/n'.format(year, value))
print("Monthly Averages")
print("=====================")
for keys in AvgMonths:
print('{0:<10} {1:>10}'.format(keys, AvgMonths[keys])) |
42651a49b6736aa10e816758c106c77594e064a9 | ishantk/PythonDec5 | /venv/Session2.py | 1,017 | 4.1875 | 4 | """num1 = int(input("Enter Number1"))
num2 = int(input("Enter Number2"))
# Arithmetic : +, -, *, /, %
num3 = num1 % num2
print(num3)
"""
age = 2
gender = "M"
# Conditional : >, <, >=, <= == !=
print(age>18)
# Logical : and or not
print(age>18 and gender=="M")
num1 = 8 # 1 0 0 0
num2 = 10 # 1 0 1 0
# Bitwise Operators
num3 = num1 & num2 # 1 0 0 0
num4 = num1 | num2 # 1 0 1 0
num5 = num1 ^ num2 # 0 0 1 0
print(num3) # 8
print(num4) # 10
print(num5) # 10
# Shift Operators
# num6 = num1 >> 2 # 1 0 0 0 >> 2 -> 0 0 1 0
# print("num6 is:",num6) # 0 0 1 0
num6 = 11 >> 3
print("num6 is:",num6) # 1
num7 = 8 << 3
print("num7 is:",num7) # 1 0 0 0 << 3 1 0 0 0 0 0 0
# Explore : odd numbers and negative numbers !!
x = 5
y = 3
# z = x/y
z = x//y
print("z is ",z)
johnsAge = 30
siasAge = 12
print(johnsAge is siasAge)
print(johnsAge is not siasAge)
# num = 12345
# result = 1+2+3+4+5
# 12345 => 1+2+3+4+5 = 15 |
ba6b98385356750c318a5b6378234980c374ec21 | lucafrance/practice-python-solutions | /es02/es2.py | 300 | 4.125 | 4 | num = int(input("What's the number to check? "))
check = int(input("What's the number to divide by? "))
if num % 4 == 0:
print("It's a multiple of 4! :)")
elif num % check == 0:
print(str(num) + " is divisible by " + str(check))
else:
print(str(num) + " ain't divisible by " + str(check)) |
a31e24f73bce97d906d859027c7957810c774b05 | mariaprandt/Bioinformatica | /ProjetoAtividade2/teste.py | 240 | 3.765625 | 4 | linha = list()
for c in range(1,6):
for i in range (1,c+1):
linha.append(c*i)
print(f'{linha}')
linha.clear()
print('\n')
for j in range(1,6):
for b in range (1,j+1):
print(f'{j*b}', end=' ')
print('') |
f82f92d70a5916240fd28eb1d53163815de71e78 | xaohuihui/algorithm_study | /tree/binary_tree_traversal.py | 2,671 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# @Author : xaohuihui
# @Time : 19-12-19 上午9:59
# @File : binary_tree_traversal.py
# Software : algorithm_study
"""
二叉树遍历,pre_order(先序遍历)、in_order(中序遍历)、post_order(后续遍历)、breadth_first_search(广度优先遍历)、depth_first_search(深度优先遍历)
"""
import collections
class TreeNode:
def __init__(self, val):
self.val = val
self.left = self.right = None
def pre_order(root: TreeNode) -> list:
if not root:
return []
return [root.val] + pre_order(root.left) + pre_order(root.right)
def in_order(root: TreeNode) -> list:
if not root:
return []
return in_order(root.left) + [root.val] + in_order(root.right)
def post_order(root: TreeNode) -> list:
if not root:
return []
return post_order(root.left) + post_order(root.right) + [root.val]
def breadth_first_search(root: TreeNode) -> list:
"""
这个只是二叉树的广度优先遍历,和图的广度优先不同,返回二叉树的遍历顺序
:param root: TreeNode
:return: list
"""
if not root:
return []
queue = collections.deque() # 申请一个双端队列
queue.append(root)
result = []
# visited = set(root) # 因为是树的结构,所以只要向下走不会存在重复的情况
while queue:
level_size = len(queue)
for _ in range(level_size):
node = queue.popleft() # 这里从左边出了,下面加入的时候就要加到末尾,若是从右边出,则下面从左边push进去
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
def depth_first_search(root: TreeNode, result=[]) -> list:
"""
二叉树广度优先遍历,返回广度遍历顺序
:param root:
:param result:
:return:
"""
if not root:
return []
result.append(root.val)
depth_first_search(root.left, result)
depth_first_search(root.right, result)
return result
if __name__ == '__main__':
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
node4.left = node2
node2.left = node1
node2.right = node3
node4.right = node6
node6.left = node5
node6.right = node7
print(pre_order(node4))
print(in_order(node4))
print(post_order(node4))
print(breadth_first_search(node4))
print(depth_first_search(node4))
|
09f15bc88cbd77bb37cb313623ad4a19b0b067b5 | wmillar/ProjectEuler | /057.py | 996 | 4.09375 | 4 | '''
It is possible to show that the square root of two can be expressed as an
infinite continued fraction.
2^.5 = 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?
'''
def nextFraction(numerator,denominator):
return (denominator*2+numerator,denominator+numerator)
totalNum = 0
fraction = (1,1)
for x in xrange(0,1000):
fraction = nextFraction(fraction[0],fraction[1])
if len(str(fraction[0])) > len(str(fraction[1])):
totalNum += 1
print totalNum
|
3a1e97fac6f009f79c0963dcfe7bf61b8dbc87d6 | pavanq/Practice | /python_assessment/q8.py | 320 | 3.953125 | 4 | class Point:
def __init__(self, x, y ):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
def __add__(self,other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
p1=Point(2,3)
p2=Point(1,4)
print (p1+p2)
|
360699b859201a3a67c5087e2a80affda6933870 | prajakta401/UdemyTraining | /venv/Lect51 Box and Violin Plot.py | 1,439 | 3.890625 | 4 | #Lecture 53 Heat map and Clustered Matrixes
import numpy as np
import pandas as pd
from numpy.random import randn
# from pandas import Series,DataFrame
import matplotlib as mpl
import matplotlib.pyplot as plt#plotting
import seaborn as sns#
from scipy import stats# for stats
flight_dframe = sns.load_dataset('flights')#loding the data set availbale in sns library
print(flight_dframe.head())
flight_dframe = flight_dframe.pivot('month','year','passengers')
print(flight_dframe)
sns.heatmap(flight_dframe,cmap="Greens",annot=True,fmt='d')
plt.show()
sns.heatmap(flight_dframe,center=flight_dframe.loc['January',1955])# 2 color gradients split at center
plt.show()
#drawing multiple plots in one window figure "Subplots
fig,(axis1,axis2) = plt.subplots(2,1)#figure name , 2 sets of axis ( 2rows and 1 colun
yearly_flights = flight_dframe.sum()#sum of flights for each year
print(yearly_flights)
years = pd.Series(yearly_flights.index.values)
years = pd.DataFrame(years)
flights = pd.Series(yearly_flights.values)
flights = pd.DataFrame(flights)
year_dframe = pd.concat((years,flights),axis = 1)
year_dframe.columns =['Year','Flights']
sns.barplot('Year',y='Flights',data=year_dframe,ax=axis1,color='Blue')
sns.heatmap(flight_dframe,cmap='Blues',ax=axis2,cbar_kws={'orientation':'horizontal'})
plt.show()
#drawing cluster map. Similar data is next to each other
sns.clustermap(flight_dframe)#similar rows are next to eachother
plt.show()
|
2f8ab557be71db1cc40cd15b175155116ee3ce86 | NUsav77/Python-Exercises | /Crash Course/Chapter 6 - Dictionaries/6.7_people.py | 1,056 | 4.625 | 5 | """Start with the program you wrote for Exercise 6-1. Make two new dictionaries representing different people,
and store all three dictionaries in a list called people. Loop through your list of people. As you loop through the
list, print everything you know about each person. """
pa_xiong = {
'first_name': 'pa',
'last_name': 'xiong',
'dob': '03/30/1986',
'city': 'st. paul',
'ethnicity': 'hmong',
}
evy_nodalo = {
'first_name': 'evolet',
'last_name': 'nodalo',
'dob': '07/07/2020',
'city': 'san diego',
'ethnicity': 'filipino/hmong',
}
snodalo = {
'first_name': 'steven',
'last_name': 'nodalo',
'dob': '05/09/1987',
'city': 'san diego',
'ethnicity': 'filipino',
}
people = [pa_xiong, evy_nodalo, snodalo]
[print(f"\nFirst name:{person['first_name'].title()}"
f"\nLast name: {person['last_name'].title()}"
f"\n\tDate of Birth: {person['dob']}"
f"\n\tBirth Location: {person['city'].title()}"
f"\n\tEthnicity: {person['ethnicity'].title()}")for person in people] |
8a9ccd254ebf8c79aa19b651711d41fa882dd474 | Iso-luo/python-assignment | /practice/Ch8_Strings/1.py | 551 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time: 2020-05-06 8:41 a.m.
import math
#
# def theta(m1, m2, r):
# a = -3 * math.pi * (r ** 3)
# b = math.sqrt((m1 * m2) / (2 * (r ** 2)))
# c = math.log10((3 * m1) / (4 * m2))
# d = math.exp(math.tan(r))
# print(a * b * c * d)
def theta(m1, m2, r):
a = -3 * math.pi * (r ** 3)
b = math.sqrt((m1 * m2) / (2 * (r ** 2)))
c = math.log10((3 * m1) / (4 * m2))
d = math.exp(math.tan(r))
print(a * b * c * d)
theta(10, 20, 5)
theta(10, 20, 5)
theta(1, 2, 3)
|
575da21a38ff2e09c6ed5cf34348c92a1dfaa5e7 | HBinhCT/Q-project | /hackerrank/Algorithms/Matrix Layer Rotation/solution.py | 1,763 | 3.546875 | 4 | #!/bin/python3
# Complete the matrixRotation function below.
def matrixRotation(matrix, r):
height = len(matrix)
width = len(matrix[0])
for i in range(min(height // 2, width // 2)):
state = []
# top-left to top-right
for j in range(i, width - i):
state.append(matrix[i][j])
# top-right to bottom-right
for j in range(i + 1, height - 1 - i):
# in Python, a[len(a) - 1 - i] = a[-1 - i]
state.append(matrix[j][-1 - i])
# bottom-right to bottom-left
for j in range(width - 1 - i, i - 1, -1):
state.append(matrix[-1 - i][j])
# left-bottom to left-top
for j in range(height - 2 - i, i, -1):
state.append(matrix[j][i])
# rotate by R
# no. of nodes
no = 2 * (height - 2 * i) + 2 * (width - (2 * i + 2))
k = r % no
state = state[k:] + state[:k]
# populate A with rotated matrix same as above
flag = 0
for j in range(i, width - i):
matrix[i][j] = state[flag]
flag += 1
for j in range(i + 1, height - 1 - i):
matrix[j][-1 - i] = state[flag]
flag += 1
for j in range(width - 1 - i, i - 1, -1):
matrix[-1 - i][j] = state[flag]
flag += 1
for j in range(height - 2 - i, i, -1):
matrix[j][i] = state[flag]
flag += 1
for row in matrix:
print(*row, end=' ')
print('')
if __name__ == '__main__':
mnr = input().rstrip().split()
m = int(mnr[0])
n = int(mnr[1])
r = int(mnr[2])
matrix = []
for _ in range(m):
matrix.append(list(map(int, input().rstrip().split())))
matrixRotation(matrix, r)
|
005056754b1b097f33d0bad87340b8461f7802bb | yiranzhimo/Python-Practice | /Day-1_3.py | 163 | 3.703125 | 4 | num=int(input("请输入您的数字:"))
dic=dict()
if num<=0:
print("输入不规范!")
for i in range(1,num+1):
if i>0:
dic[i]=i*i
print(dic) |
9b693f85a3183584799f39119225beaddc8fcd10 | robpalacios1/holbertonschool-higher_level_programming | /0x0A-python-inheritance/7-base_geometry.py | 810 | 3.625 | 4 | #!/usr/bin/python3
'''Same class or inherit from module'''
class BaseGeometry():
'''empty class BaseGeometry'''
pass
def area(self):
'''that raises an Exception with the message area()
is not implemented
'''
raise Exception("area() is not implemented")
def integer_validator(self, name, value):
'''if value is not an integer: raise a TypeError exception,
with the message <name> must be an integer
if value is less or equal to 0: raise a ValueError exception
with the message <name> must be greater than 0
'''
if type(value) is not int:
raise TypeError("{} must be an integer".format(name))
if value <= 0:
raise ValueError("{} must be greater than 0".format(name))
|
9995fb26b93dd92f9c18f4d5d1edef4eaac39d3a | EachenKuang/LeetCode | /code/98#Validate Binary Search Tree.py | 3,204 | 4.09375 | 4 | # https://leetcode.com/problems/validate-binary-search-tree/
"""
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 1 使用前序遍历二叉树,若下一个小于或者等于前一个数,则返回False
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
stack, inorder = [], float('-inf')
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
# If next element in inorder traversal
# is smaller than the previous one
# that's not BST.
if root.val <= inorder:
return False
inorder = root.val
root = root.right
return True
# 2 使用迭代方法来遍历二叉树
class Solution2:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
stack = [(root, None, None), ]
while stack:
root, lower_limit, upper_limit = stack.pop()
if root.right:
if root.right.val > root.val:
if upper_limit and root.right.val >= upper_limit:
return False
stack.append((root.right, root.val, upper_limit))
else:
return False
if root.left:
if root.left.val < root.val:
if lower_limit and root.left.val <= lower_limit:
return False
stack.append((root.left, lower_limit, root.val))
else:
return False
return True
# 3 使用递归方法遍历二叉树
class Solution3:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
def isBSTHelper(node, lower_limit, upper_limit):
if lower_limit is not None and node.val <= lower_limit:
return False
if upper_limit is not None and upper_limit <= node.val:
return False
left = isBSTHelper(node.left, lower_limit, node.val) if node.left else True
if left:
right = isBSTHelper(node.right, node.val, upper_limit) if node.right else True
return right
else:
return False
return isBSTHelper(root, None, None) |
62212db6d6a9139e24f8cb567c9ae58d5b44951f | Stefanh18/python_projects | /mimir/assingnment_4/q8.py | 170 | 3.828125 | 4 | stars = int(input("Max number of stars: ")) # Do not change this line
for x in range(1, stars + 1):
print("*" * x)
for x in range(stars-1, 0, -1):
print("*" * x) |
bda2dba98d0c4ff7bddd8239bbe4c0736cbc25e3 | amzn/differential-privacy-bayesian-optimization | /experiments/output_perturbation/scikit-learn/examples/linear_model/plot_polynomial_interpolation.py | 2,070 | 4.15625 | 4 | #!/usr/bin/env python
"""
========================
Polynomial interpolation
========================
This example demonstrates how to approximate a function with a polynomial of
degree n_degree by using ridge regression. Concretely, from n_samples 1d
points, it suffices to build the Vandermonde matrix, which is n_samples x
n_degree+1 and has the following form:
[[1, x_1, x_1 ** 2, x_1 ** 3, ...],
[1, x_2, x_2 ** 2, x_2 ** 3, ...],
...]
Intuitively, this matrix can be interpreted as a matrix of pseudo features (the
points raised to some power). The matrix is akin to (but different from) the
matrix induced by a polynomial kernel.
This example shows that you can do non-linear regression with a linear model,
using a pipeline to add non-linear features. Kernel methods extend this idea
and can induce very high (even infinite) dimensional feature spaces.
"""
print(__doc__)
# Author: Mathieu Blondel
# Jake Vanderplas
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
def f(x):
""" function to approximate by polynomial interpolation"""
return x * np.sin(x)
# generate points used to plot
x_plot = np.linspace(0, 10, 100)
# generate points and keep a subset of them
x = np.linspace(0, 10, 100)
rng = np.random.RandomState(0)
rng.shuffle(x)
x = np.sort(x[:20])
y = f(x)
# create matrix versions of these arrays
X = x[:, np.newaxis]
X_plot = x_plot[:, np.newaxis]
colors = ['teal', 'yellowgreen', 'gold']
lw = 2
plt.plot(x_plot, f(x_plot), color='cornflowerblue', linewidth=lw,
label="ground truth")
plt.scatter(x, y, color='navy', s=30, marker='o', label="training points")
for count, degree in enumerate([3, 4, 5]):
model = make_pipeline(PolynomialFeatures(degree), Ridge())
model.fit(X, y)
y_plot = model.predict(X_plot)
plt.plot(x_plot, y_plot, color=colors[count], linewidth=lw,
label="degree %d" % degree)
plt.legend(loc='lower left')
plt.show()
|
cbcefe68790b74d3f62266cf29c9a5945b428c9c | smohapatra1/scripting | /python/practice/start_again/2021/02222021/factors_of_a_num.py | 344 | 4.0625 | 4 | # Find the factors of a number
def main():
n = int(input("Enter a number "))
i = 1
a = []
while i <=n:
if n % i == 0 :
#print ("The Factors are %d for num %d" % (i, n))
a.append(i)
i +=1
print ("The factors are %s for num %d " %(a, n))
if __name__ == "__main__":
main() |
e51605eefe682f35632253ee38a7d53c17b7772e | medesiv/ds_algo | /sorting_and_searching/qsort.py | 841 | 3.890625 | 4 | """
implement qsort
[10,7,5,3,8,9]
10 7 5 3 8 9
"""
import random
def qsort(arr):
return helper(arr,0,len(arr)-1)
def helper(arr,s,e):
#if len is <2 or if s>=e to check arr size is 0 or 1
if s>=e:
return
#select a random number as pivot
p_indx = random.randint(s,e)
#swap pivot with first element
arr[s], arr[p_indx] = arr[p_indx], arr[s]
orange = s #orange is lesser #green is bigger
for green in range(s+1,e+1):
if arr[green] <arr[s]:
orange+=1
arr[orange],arr[green]=arr[green],arr[orange]
#swap back pivot with orange which would be right place for pivot
arr[s],arr[orange]=arr[orange],arr[s]
#quick sort based on final index of partition
helper(arr,s,orange-1)
helper(arr,orange+1,e)
return arr
print(qsort([10,7,5,3,8,9])) |
59b99ffe2e96be588a73ccd7866ac53c019da414 | srinujammu/Python | /Types and Values/2 Numbers.py | 173 | 3.734375 | 4 | from decimal import *
x= .1+ .1 + .1 - .3
print('x is {}'.format(x)) # it is wrong
a = Decimal('.10')
b = Decimal('.30')
y = a+a+a-b
print('y is {}'.format(y))
|
603fa0ebe855042a232de283ab803b4c717f2391 | emhhd7/python-rpg | /rpg-01.py | 2,500 | 3.765625 | 4 | class Character():
def __init__(self, name, health, power):
self.name = name
self.health = health
self.power = power
def alive(self):
if self.health > 0:
return True
def print_status(self):
return "%s has %d health and %d power." % (self.name, self.health, self.power)
class Hero(Character):
def __init__(self, name, health, power):
super().__init__(name, health, power)
# Hero attacks Goblin
def attack(self, boss):
boss.health -= sudri.power
class Goblin(Character):
def __init__(self, name, health, power):
super().__init__(name, health, power)
# Goblin attacks Hero
def attack(self, hero):
hero.health -= goblin.power
class Undead(Character):
def __init__(self, name, health, power):
super().__init__(name, health, power)
def attack(self, hero):
hero.health -= self.power
def alive(self):
return True
sudri = Hero('Sudri', 40, 5)
goblin = Goblin('Goblin', 10, 4)
bone_crawler = Undead('Bone Crawler', 10, 2)
def main():
while bone_crawler.alive() and sudri.alive():
print(sudri.print_status())
print(bone_crawler.print_status())
print()
print("What do you want to do?")
print("1. fight boss")
print("2. do nothing")
print("3. flee")
print("> ",)
user_input = input()
if user_input == "1":
sudri.attack(bone_crawler)
print("You do %d damage to the boss." % sudri.power)
if bone_crawler.health <= 0:
print("The goblin is dead.")
elif user_input == "2":
pass
elif user_input == "3":
print("Goodbye.")
break
else:
print("Invalid input %r" % user_input)
if bone_crawler.health > 0:
# Goblin attacks hero
sudri.health -= bone_crawler.power
print("The boss does %d damage to you." % bone_crawler.power)
if sudri.health <= 0:
print("You are dead.")
main()
# hero.attack(goblin)
# def __str__(self):
# return self.name + ' is on a journey.'
# if goblin.health > 0:
# # Goblin attacks hero
# sudri.health -= goblin.power
# print("The goblin does %d damage to you." % goblin.power)
# if sudri.health <= 0:
# print("You are dead.")
# sudri.attack(goblin)
# goblin.attack(sudri)
# sudri.is_alive()
# goblin.is_alive()
|
c8ab8046b8179e3f71ccf668bbcbfd883119bf9a | southpawgeek/perlweeklychallenge-club | /challenge-118/cristian-heredia/python/ch-1.py | 624 | 4.09375 | 4 | '''
TASK #1 › Binary Palindrome
Submitted by: Mohammad S Anwar
You are given a positive integer $N.
Write a script to find out if the binary representation of the given integer is Palindrome. Print 1 if it is otherwise 0.
Example
Input: $N = 5
Output: 1 as binary representation of 5 is 101 which is Palindrome.
Input: $N = 4
Output: 0 as binary representation of 4 is 100 which is NOT Palindrome.
'''
N = 5
bits = f'{N:b}'
j = -1
for num in bits:
if num != bits[j]:
print("Output: 0")
exit()
j -= 1
print("Output: 1")
|
7c21d83a825f8c5670669101a64587f71de8d5a1 | itminsu/Python | /Assignment#2/asd.py | 3,230 | 3.8125 | 4 | __author__ = 'Minsu Lee'
#Declare random
import random
dice1=random.randint(1,6)
dice2=random.randint(1,6)
dice3=random.randint(1,6)
dice4=random.randint(1,6)
dice5=random.randint(1,6)
#Declare Variable to determine the number
amountOfOne = 0
amountOfTwo = 0
amountOfThree = 0
amountOfFour = 0
amountOfFive = 0
amountOfSix = 0
#print the random numbers
print("Dice 1: "+str(dice1))
print("Dice 2: "+str(dice2))
print("Dice 3: "+str(dice3))
print("Dice 4: "+str(dice4))
print("Dice 5: "+str(dice5))
#The number of dice1
if dice1 == 1:
amountOfOne = amountOfOne + 1
elif dice1 == 2:
amountOfTwo = amountOfTwo + 1
elif dice1 == 3:
amountOfThree = amountOfThree + 1
elif dice1 == 4:
amountOfFour = amountOfFour + 1
elif dice1 == 5:
amountOfFive = amountOfFive + 1
else :
amountOfSix = amountOfSix + 1
#The number of dice2
if dice2 == 1:
amountOfOne = amountOfOne + 1
elif dice2 == 2:
amountOfTwo = amountOfTwo + 1
elif dice2 == 3:
amountOfThree = amountOfThree + 1
elif dice2 == 4:
amountOfFour = amountOfFour + 1
elif dice2 == 5:
amountOfFive = amountOfFive + 1
else :
amountOfSix = amountOfSix + 1
#The number of dice3
if dice3 == 1:
amountOfOne = amountOfOne + 1
elif dice3 == 2:
amountOfTwo = amountOfTwo + 1
elif dice3 == 3:
amountOfThree = amountOfThree + 1
elif dice3 == 4:
amountOfFour = amountOfFour + 1
elif dice3 == 5:
amountOfFive = amountOfFive + 1
else :
amountOfSix = amountOfSix + 1
#The number of dice4
if dice4 == 1:
amountOfOne = amountOfOne + 1
elif dice4 == 2:
amountOfTwo = amountOfTwo + 1
elif dice4 == 3:
amountOfThree = amountOfThree + 1
elif dice4 == 4:
amountOfFour = amountOfFour + 1
elif dice4 == 5:
amountOfFive = amountOfFive + 1
else :
amountOfSix = amountOfSix + 1
#The number of dice5
if dice5 == 1:
amountOfOne = amountOfOne + 1
elif dice5 == 2:
amountOfTwo = amountOfTwo + 1
elif dice5 == 3:
amountOfThree = amountOfThree + 1
elif dice5 == 4:
amountOfFour = amountOfFour + 1
elif dice5 == 5:
amountOfFive = amountOfFive + 1
else :
amountOfSix = amountOfSix + 1
combination = " " #Str Variable
if amountOfOne == 3 or amountOfTwo == 3 or amountOfThree == 3 or amountOfFour == 3 or amountOfFive == 3 or amountOfSix == 3 :
if amountOfOne ==2 or amountOfTwo == 2 or amountOfThree == 2 or amountOfFour == 2 or amountOfFive == 2 or amountOfSix == 2:
combination = "Full house"
elif amountOfOne == 1 and amountOfTwo == 1 and amountOfThree == 1 and amountOfFour == 1 and amountOfFive == 1 and amountOfSix == 1:
combination = "Large Straight"
elif amountOfOne == 5 or amountOfTwo == 5 or amountOfThree == 5 or amountOfFour == 5 or amountOfFive == 5 or amountOfSix == 5 :
combination = "Five of a Kind"
elif amountOfOne == 4 or amountOfTwo == 4 or amountOfThree == 4 or amountOfFour == 4 or amountOfFive == 4 or amountOfSix == 4 :
combination = "Four of Kind"
elif amountOfOne == 3 or amountOfTwo == 3 or amountOfThree == 3 or amountOfFour == 3 or amountOfFive == 3 or amountOfSix == 3 :
combination = "Three of Kind"
elif amountOfOne or amountOfTwo or amountOfThree or amountOfFour or amountOfFive or amountOfSix == 2 :
combination = "One Pair"
else:
combination = "No Combination"
print("Highest Combination: "+ combination) |
4e23316f462bf8b25e0071c19a0fb2fa57f060ab | alexp01/trainings | /Python/6_Advance_Python_development/607_Timezones/app.py | 546 | 4.1875 | 4 |
# https://www.udemy.com/course/the-complete-python-course/learn/lecture/9477766#questions
# https://www.udemy.com/course/the-complete-python-course/learn/lecture/9477768#questions
from datetime import datetime,timezone, timedelta
now = datetime.now(timezone.utc)
print(now)
tomorrow = now + timedelta(days=2)
print(tomorrow)
print(now.strftime('%d-%m-%Y, %H:%M:%S')) # strf is string format
user_date = input('Please give a date YYYY-MM-DD:_')
user_date = datetime.strptime(user_date, '%Y-%m-%d') # strp is string parse time
print(user_date) |
5f9630b23f4c248e57b2bbf8c27ac451c519da44 | loc-dev/CursoEmVideo-Python | /Fase07/Desafios/Desafio_11.py | 310 | 3.9375 | 4 | # Fase 07 - Operadores Aritméticos
# Desafio 11
# Crie um programa que leia quanto dinheiro
# uma pessoa tem na carteira e mostre quantos
# dólares ela pode comprar.
dolar = 5.65
saldo = float(input('Quantos reais você tem na carteira? '))
print('Posso comprar US${:.2f}'.format(saldo * dolar))
|
32d3e02d6c05d23d7dd766e885ec6effee357385 | SR0-ALPHA1/hackerrank-tasks | /list_reverse.py | 260 | 3.890625 | 4 | """
Task: Implement List.reverse()
"""
def reverse(lst):
for i in xrange(int(len(lst)/2)):
tmp = lst[i]
lst[i] = lst[len(lst)-1-i]
lst[len(lst)-1-i] = tmp
return lst
l = ['q','w','e','a','s','d','f']
print l
print reverse(l)
|
fd18ca72054c6440837b9bf218ee40fdec403af9 | MarcosLazarin/Curso-de-Python | /ex070.py | 1,007 | 3.875 | 4 | # Fazer um programa que leia o nome e o preço de vários produtos.
# O programa deverá perguntar se quer continuar.
# No final, mostre:
# Qual é o total gasto na compra.
# Quantos produtos custam mais de R$100,00 reais.
# Qual é o nome do produto mais barato.
totalgasto = maiorque100 = ma = me = c = 0
while True:
nomeproduto = input('Qual é o nome do produto: ')
precoproduto = float(input('Qual é o preço: '))
continuar = input('Você quer continuar? [S/N] ').upper().strip()
c += 1
totalgasto += precoproduto
if continuar == 'N':
break
if precoproduto > 100:
maiorque100 += 1
if c == 1:
ma = me = precoproduto = nomeproduto
else:
if ma > me:
ma = precoproduto = nomeproduto
if me < ma:
me = precoproduto = nomeproduto
print(f'o total gasto na compra foi {totalgasto} reais.')
print(f'{maiorque100} produtos custam mais de R$100,00 reais.')
print(f'O nome do produto mais caro é {nomeproduto}.') |
661e3167420f104c7b52190d025139f265300630 | anshusolar/antenna_modelling_data_processing | /package_common_modules/find_line_in_text_file.py | 499 | 4.15625 | 4 | '''
'''
# *** Find_line finds a line in .txt file which contains 'needed_text' ***
# needed_text - text to find
# start_char - number of character where the needed_text starts in line
# line - returns a text line from the file with needed_text
def find_line_in_text_file (file_handle, needed_text, start_char):
tempChar = ''
while tempChar != needed_text:
line = file_handle.readline()
tempChar = line[start_char : len(needed_text) + start_char]
return line
|
3f16dd3adfd7ca566615be964afd52f41701c29f | ironmanvim/coding_interview_questions | /19_sep_2020/1-2.py | 1,235 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode (object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2, c=0):
# Fill this in.
result = ListNode(c)
if l1 and l2:
result.val += l1.val + l2.val
c = result.val // 10
result.val = result.val % 10
result.next = self.addTwoNumbers(l1.next, l2.next, c)
return result
if l1:
result.val += l1.val
c = result.val // 10
result.val = result.val % 10
result.next = self.addTwoNumbers(l1.next, l2, c)
return result
if l2:
result.val += l2.val
c = result.val // 10
result.val = result.val % 10
result.next = self.addTwoNumbers(l1, l2.next, c)
return result
if c > 0:
return result
return None
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(0)
l2 = ListNode(1)
l2.next = ListNode(6)
l2.next.next = ListNode(6)
result = Solution().addTwoNumbers(l1, l2)
while result:
print(result.val, end='')
result = result.next
print()
# 7 0 8
|
c1442d0eeb7e59d405ec7d154b3fe3cc72b55e55 | deroahe/Project-Euler | /Problem 7/euler.py | 461 | 3.953125 | 4 | # What is the 10 001st prime number?
import math
def prime(n):
if (n < 2):
return 0
if (n != 2 and n % 2 == 0):
return 0
x = math.floor(math.sqrt(n))
for d in range (3, x + 1, 2):
if (n % d == 0):
return 0
return 1
if __name__ == "__main__":
n = 1
i = 1
while (i != 10001):
if (prime(n)):
i += 1
print(n)
n += 2 |
8570cac15e7c9aee219188af258f1f23eec12090 | yanfriend/python-practice | /licode/st45.py | 463 | 3.609375 | 4 | class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret=0
max_reach=0
i=0
while max_reach<len(nums)-1:
next_reach=max_reach
while i<=max_reach:
next_reach=max(next_reach,i+nums[i])
i+=1
ret+=1
max_reach=next_reach
return ret
print Solution().jump([1,2,3]) # expect 2
|
dcc1b912188ccdf1f13f042d4c713cf6994a21a7 | sixiangxz/Python | /python算法/算法/排序/选择排序.py | 624 | 3.578125 | 4 | # 选择排序 O(n*n)
def select_sort(lis):
for i in range(len(lis)-1):
# 假如lis_min为list无序区最小数的下标,默认为第一个数
lis_min = i
# i之前为有序区,i之后为无序区,通过循环找到无序列表最小值然后获取下标
for j in range(i, len(lis)):
if lis[j] < lis[lis_min]:
lis_min = j
# 找到比lis_min还小的值,并交换这个值
if lis_min != i:
lis[i], lis[lis_min] = lis[lis_min], lis[i]
print(a)
a = [1, 4, 5, 3, 7, 9, 6, 2, 8]
print('..........', a)
select_sort(a) |
05bfe4ebc216f2cbd8947a08da89ab18904ec6b6 | scasica0/FTPDemo-client-server- | /cli.py | 9,458 | 3.75 | 4 | # *****************************************************
# Description: Client for FTP server
# *****************************************************
import socket
import sys
import commands
import os
def get_function(clientSocket,host,port,fileName):
# Send get command
sendMsg (clientSocket, "get")
# Send fileName
sendMsg (clientSocket, fileName)
# wait for confirmation if desired file exists
confirmation = ""
confirmation = clientSocket.recv(1)
# continue if file exists
if confirmation != 'y':
print 'ERROR- the file: "', fileName, '" does not exist on server'
else:
# Generate emphemeral port
welcomeSocket = emphemeral()
# Wait for server to connect
welcomeSocket.listen(1)
print "Waiting for data connection..."
# Send server emphemeral port number
portNumberBuff = ""
portNumberBuff = welcomeSocket.getsockname()[1]
portNumber = str(portNumberBuff)
sendMsg (clientSocket, portNumber)
# Accept connections
serverSocket, addr = welcomeSocket.accept()
print "Accepted data connection from server: ", addr
# Receive the file
# The buffer to all data received from the client.
fileData = ""
# The temporary buffer to store the received data.
recvBuff = ""
# The size of the incoming file
fileSize = 0
# The buffer containing the file size
fileSizeBuff = ""
# Create the new file
fileObj = open(fileName, "w")
# Receive the first 10 bytes indicating the size of the file
fileSizeBuff = recvHeader(serverSocket, 10)
# Get the file size
fileSize = int(fileSizeBuff)
# Receive the file
recvBuff = recvHeader(serverSocket,fileSize)
# save the receive buffer into fileData
fileData = recvBuff
# write the data received to the file
fileObj.write(fileData)
# Close the sockets and the file
welcomeSocket.close()
serverSocket.close()
fileObj.close()
print 'Received: ' , fileName
print 'Total size received: (', len(fileData), ' bytes)'
def put_function(clientSocket,host,port,fileName):
# Send put command
sendMsg (clientSocket, "put")
# Send fileName
sendMsg (clientSocket, fileName)
# check if fileName is valid
if not os.path.isfile(fileName):
# file does not exist
print 'ERROR- ', fileName, ' does not exist'
clientSocket.send('n')
else:
# tell client that file is valid and continue
clientSocket.send('y')
# Generate emphemeral port
welcomeSocket = emphemeral()
# Wait for server to connect
welcomeSocket.listen(1)
print "Waiting for data connection..."
# Send server emphemeral port number
portNumberBuff = ""
portNumberBuff = welcomeSocket.getsockname()[1]
portNumber = str(portNumberBuff)
sendMsg (clientSocket, portNumber)
# Accept connections
serverSocket, addr = welcomeSocket.accept()
print "Accepted data connection from server: ", addr
# Open the file
fileObj = open(fileName, "r")
# The number of bytes sent
bytesSent = 0
# The file data
fileData = None
# Keep sending until all is sent
while True:
# Read 65536 bytes of data
fileData = fileObj.read(65536)
# Make sure we did not hit EOF
if fileData:
# Get the size of the data read and convert it to string
dataSizeStr = str(len(fileData))
# Prepend 0's to the size string until the size is 10 bytes
while len(dataSizeStr) < 10:
dataSizeStr = "0" + dataSizeStr
# Prepend the size of the data to the file data.
fileData = dataSizeStr + fileData
# The number of bytes sent
bytesSent = 0
# Send the data
while len(fileData) > bytesSent:
bytesSent += serverSocket.send(fileData[bytesSent:])
# The file has been read
else:
break
print 'Sent ', fileName
print 'Total size sent: (', bytesSent, ' bytes)'
# Close the sockets and the file
serverSocket.close()
fileObj.close()
welcomeSocket.close()
def ls_function(clientSocket,host,port):
# Send lls command
sendMsg (clientSocket, "ls")
# The size of the incoming data
dataSize = 0
# The buffer containing the data size
dataSizeBuff = ""
# The temporary buffer to store the received data.
recvBuff = ""
# The buffer to all data received from the client.
serverDirectory = ""
# Receive the first 10 bytes indicating the size of the file
dataSizeBuff = recvHeader(clientSocket, 10)
# Get the file size
dataSize = int(dataSizeBuff)
while len(serverDirectory) != dataSize:
# Receive what client has sent
recvBuff = clientSocket.recv(dataSize)
# The other socket has unexpectedly closed its socket
if not recvBuff:
break
# Save the file data
serverDirectory += recvBuff
# Print the server's directory
print 'Server Directory:'
print serverDirectory
def lls_function():
# Run ls command, get output, and print it
print 'Client Directory:'
for line in commands.getstatusoutput('ls -l'):
print line
def quit_function(clientSocket): #COMPLETE
# Send quit command
sendMsg (clientSocket, "quit")
def emphemeral(): #COMPLETE
# Create a socket
welcomeSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to port 0
welcomeSocket.bind(('',0))
return welcomeSocket
def recvHeader(socket, numBytes):
# The buffer
recvBuff = ""
# The temporary buffer
tmpBuff = ""
# Keep receiving till all is received
while len(recvBuff) < numBytes:
# Attempt to receive bytes
tmpBuff = socket.recv(numBytes)
# The other side has closed the socket
if not tmpBuff:
break
# Add the received bytes to the buffer
recvBuff += tmpBuff
return recvBuff
def sendMsg (socket, message):
messageSize = ""
# Get the size of the data read and convert it to string
messageSize = str(len(message))
# Prepend 0's to the size string until the size is 10 bytes
while len(messageSize) < 10:
messageSize = "0" + messageSize
# Prepend the size of the data to the file data.
message = messageSize + message
# The number of bytes sent
numSent = 0
# Send the command message
while len(message) > numSent:
numSent += socket.send(message[numSent:])
if __name__ == '__main__':
# Check the command line arguments
if len(sys.argv) != 3:
print "-ERROR- USAGE: ", sys.argv[0], " <SERVER_MACHINE> <SERVER_PORT> "
exit(0)
# Get the host name (or IP)
host = sys.argv[1]
# Get the server's port number
port = int(sys.argv[2])
# The client socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server */
clientSocket.connect((host,port))
print '\nConnected to server at', host, '; Port: ', port, '\n'
# List valid client commands
print 'Command List Usage: \n\tget <FILE_NAME> -> downloads file <file name> from the server'
print '\tput <FILE_NAME> -> uploads file <file name> to the server'
print '\tls -> lists files on the server'
print '\tlls -> lists files on the client'
print '\tquit -> disconnects from the server and exits \n'
# Client Command Interface
condition = True
# While quit is not chosen
while condition:
ans = raw_input ('FTP> ')
if len(ans.partition(' ')) == 2:
cmd = ans
else:
cmd, temp, fileName = ans.partition(' ')
if cmd == 'get':
get_function(clientSocket,host,port,fileName)
print "\n"
elif cmd == 'put':
put_function(clientSocket,host,port,fileName)
print "\n"
elif cmd == 'ls':
ls_function(clientSocket,host,port)
print "\n"
elif cmd == 'lls':
lls_function()
print "\n"
elif cmd == 'quit':
quit_function(clientSocket)
# Exit Command Interface
condition = False
else:
print '-ERROR- Invalid Command'
print 'Command List Usage: \n\tget <FILE_NAME> -> downloads file <file name> from the server'
print '\tput <FILE_NAME> -> uploads file <file name> to the server'
print '\tls -> lists files on the server'
print '\tlls -> lists files on the client'
print '\tquit -> disconnects from the server and exits'
print '\n'
# Close the connection to the server
clientSocket.close()
|
3cb1840b453d6aab58323676075f10fd442ed60b | batuhand/LYK17 | /class_ageOf.py | 1,100 | 3.515625 | 4 | class insanlar():
def __init__(self,mevki = "isci",saldirigucu=50,savunmagucu=10,kalancan=120):
self.mevki = mevki
self.saldirigucu = saldirigucu
self.savunmagucu = savunmagucu
self.kalancan = kalancan
def durum(self):
print("Bu insan bir ",self.mevki,". Saldırı gücü : ",self.saldirigucu,"Savunma gücü :",self.savunmagucu,"Kalan canı ise : ",self.kalancan)
def saldir(self):
print(self.mevki, "bir saldırı başlattı !")
class hero(insanlar):
def __init__(self,orduKur,mevki,saldirigucu,savunmagucu,kalancan):
self.orduKur = orduKur
super().__init__(mevki,saldirigucu,savunmagucu,kalancan)
def durum(self):
print("Bu hero ", self.mevki, ". Saldırı gücü : ", self.saldirigucu, "Savunma gücü :", self.savunmagucu,"Kalan canı ise : ", self.kalancan,"Ordu kurma gücü : ",self.orduKur)
okcu = insanlar("okçu",150,120,200)
atlı = insanlar("atlı",200,100,150)
arkantos = hero("Arkantos","tanrı",300,500,1500)
isci = insanlar()
arkantos.durum()
okcu.durum()
atlı.durum()
isci.durum() |
4127ba34e97dca9d7638d10cdb7f54f58deb16cd | sobriquette/interview-practice-problems | /Project Euler/nthFibonacci.py | 1,011 | 4.125 | 4 | # Print the nth number in the Fibonacci Sequence
# Approach 1: iterative, space optimized
def fibIterative(n):
n1, n2 = 0, 1
if n < 0:
return "Input is incorrect"
elif n == 1:
return n1
elif n == 2:
return n2
else:
for i in range(2,n):
n1, n2 = n2, n1 + n2
return n2
# Runtime: O(n)
# Space: O(1)
# Approach 2: recursion
def fibRecursive(n):
if n < 0:
return "Input is incorrect"
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibRecursive(n - 2) + fibRecursive(n - 1)
# Runtime: O(2^n)
# Space: O(1) -- if considering call stack size, O(n)
# Approach 3: recursion w/ dynamic programming
def fibDynamic(n):
fibs = [0, 1]
if n < 0:
return "Input is incorrect"
elif n <= len(fibs):
return fibs[n - 1]
else:
fib = fibDynamic(n - 1) + fibDynamic(n - 2)
fibs.append(fib)
return fib
# Runtime: O(n)
# Space: O(n) for storing calculated fibonacci numbers
if __name__=="__main__":
n = 9
print(fibIterative(n))
print(fibRecursive(n))
print(fibDynamic(n)) |
aa0016970bf263752a47c6c88b6dab48cff77e65 | Cherry232/Python | /Print.py | 732 | 4.03125 | 4 | print ("Hoi ik ben Kirsten en hier komt weer een nieuwe tekening met mijn geliefde turtle ik hoop dat jullie hem leuk vinden!")
import turtle
Jurjen = turtle.Turtle()
Jurjen.speed(50)
Jurjen.shape("turtle")
Jurjen.color("red")
Jurjen.penup()
Jurjen.forward(500)
Jurjen.pendown()
for i in range(5,106,3):
Jurjen.forward(i*2)
Jurjen.right(90)
import turtle
anna=turtle.Turtle()
anna.speed (50)
anna.shape("turtle")
anna.color("blue")
for i in range(5,106,3):
anna.forward(i*2)
anna.right(90)
import turtle
wouter=turtle.Turtle()
wouter.speed(50)
wouter.shape("turtle")
wouter.color("green")
wouter.penup()
wouter.backward(500)
wouter.pendown()
for i in range(5,106,3):
wouter.forward(i*2)
wouter.right(90)
|
ea6fbbe3f700fafaba182bdf3bd731e16c4299ee | Aasthaengg/IBMdataset | /Python_codes/p03433/s298100007.py | 71 | 3.5 | 4 | n=int(input())
a=int(input())
if a>=n%500:print("Yes")
else:print("No") |
29ec583c4fa2eb5054dd3fe430495a0b5cb9c2e9 | chunamanh/PY4E-PythonForEveryOne | /python_codes/fibonacci.py | 294 | 4.1875 | 4 | # count the nth fibonacci number with dynamic programming (Quy hoach dong)
# Fibonacci: 1 1 2 3 5 8 13 ...
def fibonacci(n):
result = [0] * (n + 1)
result[1] = 1
for i in range(2, n + 1):
result[i] = result[i - 1] + result[i - 2]
return result[n]
print(fibonacci(3)) |
eee6dd45fda2f7b47fc2c317c2162fb65c59fa20 | prc3333/Exercicios--de-Phyton- | /Exercicios mundo 1/ex078.py | 559 | 4.0625 | 4 | '''listnum = []
for c in range(0, 5):
listnum.append(int(input(f'Digite um valor para a posição {c}: ')))
print(f'você digitou os valores {listnum}')
print(f'O maior valor digitado foi:{max(listnum)}')
print(f'O menor valor digitado foi:{min(listnum)}')'''
lista = []
for c in range(0, 5):
lista.append(int(input(f'Digite um valor numerico {c+1}: ')))
print(f'Minha lista é {lista}.')
print(f'O menor numero é {min(lista)} na posição {lista.index(min(lista))}')
print(f'O maior numero é {max(lista)} na posição {lista.index(max(lista))}')
|
4769eabbeff25ae589352ee901815a4d32109b7b | Faethreck/Personal-Projects | /Random small projects/Tarea 8.py | 154 | 3.921875 | 4 | def sumDigits(numbers):
if numbers == 0:
return 0
else:
return numbers % 10 + sumDigits(int(numbers / 10))
print(sumDigits(345))
|
e456742dfe2e4e069f9f6e4bc7dae741e3d540b7 | nicklevin-zz/dailyprogrammer | /2016/10/10/KaprekarsRoutine.py | 972 | 3.640625 | 4 | def kaprekar(num) :
i = 0
while num not in [6174, 0] :
num = desc_digits(num) - asc_digits(num)
i += 1
return i
def breakdown_digits(num) :
digits = list(map(int, list(str(num))))
while len(digits) < 4 :
digits.append(0)
return digits
def largest_digit(num) :
return max(breakdown_digits(num))
def asc_digits(num) :
return int(''.join(map(str, sorted(breakdown_digits(num)))))
def desc_digits(num) :
return int(''.join(map(str,sorted(breakdown_digits(num), reverse=True))))
print('Largest Digit:')
for num in [1234, 3253, 9800, 3333, 120] :
print(str(num) + ': ' + str(largest_digit(num)))
print('Descending order:')
for num in [1234, 3253, 9800, 3333, 120] :
print(str(num) + ': ' + str(desc_digits(num)))
print('Kaprekar:')
for num in [6589, 5455, 6174] :
print(str(num) + ': ' + str(kaprekar(num)))
# find highest possible output
print('Highest: ' + str(max(map(kaprekar, range(10000)))))
|
1654fe1de8b8ea919aa56352579a47074cc79442 | fifa007/Leetcode | /src/word_break.py | 692 | 4.0625 | 4 | #!/usr/bin/env python2.7
'''
Given a string s and a dictionary of words dict, determine
if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
'''
class Solution(object):
def word_break(self, s, wordDict):
if s is None:
return False
n = len(s)
dp = [False] * (n+1)
dp[n] = True
for i in xrange(n-1, -1, -1):
for j in xrange(i, n):
if s[i:j+1] in wordDict and dp[j+1]:
dp[i] = True
break
return dp[0] |
ef3088ca3dc9ac8fb170367952d49f97780eac05 | sairamprogramming/python_book1 | /chapter6/programming_exercises/exercise12.py | 1,561 | 4.5 | 4 | # Average Steps Taken
# Program to find the average steps taken per month.
def main():
# Opening the step file.
infile = open('steps.txt', 'r')
# Initalizing the month variable
month = 0
# Getting the average number of steps for each month.
while month < 12:
month += 1
print('month :', end='')
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
average_month_steps = get_average(infile, 31)
print(month, format(average_month_steps, '.2f'))
elif month == 2:
average_month_steps = get_average(infile, 28)
print(month, format(average_month_steps, '.2f'))
else:
average_month_steps = get_average(infile, 30)
print(month, format(average_month_steps, '.2f'))
# Closing the file.
infile.close()
print('Output has been displayed.')
# Function to get the average number of steps of each month.
# Takes 2 arguments, 1st file object to read inputs from the file
# 2nd the number od days in the particular month.
def get_average(file_object, days):
count = 0
total = 0.0
# Getting the total number of steps in the month.
while count < days:
steps = file_object.readline()
count += 1
steps = int(steps)
total += steps
# Calculating the average
average = total / days
# Returning the average.
return average
# Calling the main function.
main()
|
591f2b0da0584ba34d7e9d970320facfa31416ae | Akhilnazim/Problems | /leetcode/largest.py | 567 | 4.25 | 4 | #laargest number without using conditional operator
# Python3 program to Compute the minimum
# or maximum of two integers without
# branching
# Function to find minimum of x and y
def min(x, y):
return y ^ ((x ^ y) & -(x < y))
# Function to find maximum of x and y using xor operation
def max(x, y):
return x ^ ((x ^ y) & -(x < y))
# Driver program to test above functions
x = 1
y = 6
print("Minimum of", x, "and", y, "is", end=" ")
print(min(x, y))
print("Maximum of", x, "and", y, "is", end=" ")
print(max(x, y))
|
82c6d548a61eda542202376e76696196146a1156 | littleliona/leetcode | /medium/386.lexicographical_numbers.py | 448 | 3.578125 | 4 | class Solution:
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
result = []
stack = [1]
while stack:
y = stack.pop()
result.append(y)
if y < n and y % 10 < 9:
stack.append(y + 1)
if y * 10 <= n:
stack.append(y * 10)
return result
s = Solution()
a = s.lexicalOrder(20)
print(a)
|
842d345067b288a27c2e8261616a088f0532c28a | NicoleGruber/Codility | /03-OddOccurrencesInArray.py | 1,906 | 4.34375 | 4 | '''Uma matriz não vazia A que consiste em N números inteiros é fornecida. A matriz contém um número ímpar de elementos e cada elemento da matriz pode ser emparelhado com outro elemento que tem o mesmo valor, exceto por um elemento que não é emparelhado.
Por exemplo, na matriz A, de modo que:
A [0] = 9 A [1] = 3 A [2] = 9
A [3] = 3 A [4] = 9 A [5] = 7
A [6] = 9
os elementos nos índices 0 e 2 têm valor 9,
os elementos nos índices 1 e 3 têm valor 3,
os elementos nos índices 4 e 6 têm valor 9,
o elemento no índice 5 tem valor 7 e não está emparelhado.
Escreva uma função:
solução def (A)
que, dada uma matriz A que consiste em N números inteiros que atendem às condições acima, retorna o valor do elemento não emparelhado.
Por exemplo, dada a matriz A de modo que:
A [0] = 9 A [1] = 3 A [2] = 9
A [3] = 3 A [4] = 9 A [5] = 7
A [6] = 9
a função deve retornar 7, conforme explicado no exemplo acima.
Escreva um algoritmo eficiente para as seguintes suposições:
N é um número inteiro ímpar dentro do intervalo [1 .. 1.000.000];
cada elemento da matriz A é um número inteiro dentro do intervalo [1..1.000.000.000];
todos, exceto um dos valores em A, ocorrem um número par de vezes.'''
def solution(A):
A.sort() #Colocando os numeros inteiros da lista em ordem crescente
if len(A) == 1: #Verificando se a lista contem apenas 1 elemento
return A[0] #Se tiver apenas 1, retornando esse numero
for i in range(0,len(A),2): #FOR para ir verificando na lista de dois em dois elementos
if i == len(A) - 1: #Verificando se o numero mais alto que é o numero que não tem repeticao
return A[i] #Se for, retorna o numero
if A[i] != A[i + 1]: #Fazendo a verificão dos demais numeros
return A[i] #Retorna o numero sem repeticao
|
4f2366209e0040815698ec2ac6b05c21ff657053 | czamoral2021/CEBD-1100-CODE-WINTER-2021 | /CZ_Exercises_class04/draw_triangle2.py | 441 | 3.796875 | 4 | # Isosceles triangle. Iso symmetrical triangle 3 lines only
# Triangle base size 5 starting with 1.
# initialize variables
v_triangle = 9
v_count = 1
v_string = ""
# v_triangle even => please enter an ODD base triangle and greater than 1
for y in range(1, int(v_triangle) + 1):
if v_count % 2 != 0:
v_string = v_count * "*"
v_n_string = str.center(v_string,v_triangle, ' ')
print(v_n_string)
v_count += 1
|
8df442a6a2a65d90b499947957a6e736123bf10d | Filipo-Dev/Python_Lists_Prac | /dictionaries_set_generator_compre.py | 1,181 | 4.15625 | 4 | #Dictionary comprehensions
names = ['Brian', 'Seth', 'Peter', 'Philip', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
#print (zip(names, heros))
#I want a dict{'name': 'hero'} for each name, hero in zip(name, heros)
my_dict = {}
for name, hero in zip(names, heros):
my_dict[name] = hero
print(my_dict)
#I want a dict{'name': 'hero'} for each name, hero in zip(name, heros)
#As a dictionary comprehension
my_dict = {name: hero for name, hero in zip(names, heros)}
print(my_dict)
#If name is not equal to Peter
my_dict = {name: hero for name, hero in zip(names, heros) if name != 'Peter'}
print(my_dict)
#Set Comprehensions
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
nums = [1, 1, 2, 1, 3, 4, 3, 4, 5, 5, 6, 7, 8, 7, 9, 9]
my_set = set()
for n in nums:
my_set.add(n)
print(my_set)
#Using set comprehensions
my_set = {n for n in nums}
print(my_set)
#Generator Expressions
#I want to yield 'n * n' for 'n' in nums
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
'''def get_func(nums):
for n in nums:
yield n * n
'''
#Using generator comprehensions
my_gen = (n*n for n in nums)
#my_gen = get_func(nums)
for i in my_gen:
print(i)
|
ffb789d038f8973d77ac4f49da36a8e7e111d188 | fred112f/CS | /new2.py | 232 | 4.21875 | 4 | def vowel(word):
if word[0] in("a", "e", "i", "o", "u","æ","ø","å"):
return True
return False
word= input("Type a word: ")
if vowel(word):
print ("Starts with a vowel")
else:
print ("Does not start with a vowel")
|
23d3f3666e373f8a899991213356d9276a9489e2 | ldosen/Shiftease-server | /flaskApp/test.py | 1,322 | 3.5625 | 4 | import unittest
import main_algorithm
class TestMainAlgorithm(unittest.TestCase):
def setUp(self):
self.raw_availabilities = [0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0]
self.slots_to_fill = {
2019: {4: {23: {"9am": None, "10am": None}, 24: {"9am": None, "10am": None}}}}
self.max_slots = 2
self.total_shifts = 4
self.employees = ["Luke", "George", "Zac"]
self.target_shifts = [2, 1, 1]
self.result = main_algorithm.make_schedule(
self.raw_availabilities, self.slots_to_fill, self.max_slots, self.total_shifts, self.employees, self.target_shifts)
def test_not_none(self):
self.assertNotEqual(self.result, None)
"""
def test_db_queries(self):
# check db query equal to expected
def test_data_processed(self):
# check db queries properly transformed into necessary inputs for algorithm
def test_unschedulable(self):
# check if unschedulable list in result is equal to expected
def test_scheduled(self):
# check result slots_to_fill dict is equal to expected
def test_db_update(self):
# check if the db updates to reflect the output of the algorithm
# basically test_scheduled combined with test_db_queries
"""
if __name__ == '__main__':
unittest.main()
|
bd20cdad1017159f5fa5cfc3ec7d8f0639945888 | Rudyk-Iurii/hilel_test | /tests.py | 3,565 | 3.6875 | 4 | from functions import (
task1,
task2,
task3,
)
#task 1
print("\ntask 2:")
"""
1. Напишите код на python, который посчитает и выведет на экран количество единичек и их индексы в массиве:
[-1, 1, -2, -1, -2, 0, 2, -3, 2, -2, 0, -1, 1, -3, 0, 1, 2, -1, -3, -3]
"""
list = [-1, 1, -2, -1, -2, 0, 2, -3, 2, -2, 0, -1, 1, -3, 0, 1, 2, -1, -3, -3]
print(task1(list))
#task 2
print("\ntask 2:")
"""
2. Дан список (list) цен на iphone xs max 256gb у разных продавцов на hotline:
[47.999, 42.999, 49.999, 37.245, 38.324, 37.166, 38.988, 37.720]
Средствами python, написать функцию, возвращающую tuple из min, max и mean (среднюю) и median (медианную) цену.
"""
list = [47.999, 42.999, 49.999, 37.245, 38.324, 37.166, 38.988, 37.720]
print(task2(list))
#task 3
print("\ntask 3:")
"""
3. Дан словарь продавцов и цен на iphone xs max 256gb у разных продавцов на hotline:
{ ‘citrus’: 47.999, ‘istudio’ 42.999,
‘moyo’: 49.999, ‘royal-service’: 37.245,
‘buy.ua’: 38.324, ‘g-store’: 37.166,
‘ipartner’: 38.988, ‘sota’: 37.720 }
Средствами python, написать функцию, возвращающую список имен продавцов, чьи цены попадают в диапазон (from_price, to_price). Например:
(37.000, 38.000) -> [‘royal-service’, ‘g-store’, ‘sota’]
"""
sellers = {'citrus': 47.999,
'istudio': 42.999,
'moyo': 49.999,
'royal-service': 37.245,
'buy.ua': 38.324,
'g-store': 37.166,
'ipartner': 38.988,
'sota': 37.720 }
from_price = 37.000
to_price = 38.000
print ("{} -> {}".format((from_price, to_price), task3(sellers, from_price, to_price)))
#task 4
print("\ntask 4:")
"""
4. Вычислите произведение матрицы M на вектор a.
M = |1, 2| a = |1|
|3, 4| |2|
"""
print("""
M = |1, 2| a = |1|
|3, 4| |2|
S = |1*1 + 2*2| = |5|
|3*1 + 4*2| |11|
""")
#task 5
print("\ntask 5:")
"""
5. Нарисуйте трехмерные оси координат. Постройте на них вектора i = (2, 0, 0), j = (0, 3, 0), k = (0, 0, 5). Постройте вектор, являющийся их суммой: b = i + j + k
"""
print("b(2, 3, 5)\nPlease find more in attached file")
#task 6
print("\ntask 6:")
"""
6. Посчитайте производную функции e^(2x) + x^3 + 3
"""
print("""
(e^(2x) + x^3 + 3)'
(e^(2x))' + (x^3)' + 3'
e^(2x) + 3x^2 + 0
""")
#task 7
print("\ntask 7:")
"""
7. В мешке есть 7 шаров, 5 из них белые, 2 черные. Вы вытаскиваете два шара, какова вероятность, что они оба черные? Опишите рассуждения.
"""
print("""P = 2/7 * 1/6 = {}%
При одновременности событий (вытянут черный !И! черный) происходит умножнния вероятностей каждого события.
Первое событе - вероятность вытащить черный шар 2 к 7, Второе - вероятность вытащить черный шар 1 к 6.
""".format(round(2/7 * 1/6 * 100, 3))) |
a34092ae5f77b3abdfc74574f4fc8ee8b4188236 | dev-arthur-g20r/how-to-code-together-using-python | /How to Code Together using Python/EVENT DRIVEN PYTHON/perimeteroftriangle.py | 355 | 4.125 | 4 | import os
def perimeterOfTriangle(a,b,c):
p = a + b + c
return p
print("Enter length of two sides and base to check perimeter of the triangle.")
base = float(input("Base: "))
side1 = float(input("Side 1: "))
side2 = float(input("Side 2: "))
perimeter = perimeterOfTriangle(side1,base,side2)
print("Perimeter of triangle: ", perimeter)
os.system("pause") |
fddf2fb2aec4674c7d4f0aa6a6ffd345e6acc009 | pombredanne/dssp1 | /stack.py | 697 | 4.125 | 4 | # -*- coding: utf-8 -*-
import linked_list
class Stack(object):
"""
All operations on a stack are O(1)
"""
def __init__(self):
self.items = linked_list.DoublyLinkedList()
def push(self, value):
self.items.add_last(value)
def peek(self):
if not self.items.count:
raise Exception("Cannot peek at an empty stack ☹")
return self.items._tail.value
def pop(self):
if not self.items.count:
raise Exception("Cannot pop from an empty stack ☹")
tail_value = self.items._tail.value
self.items.remove_last()
return tail_value
def get_count(self):
return self.items.count
|
bea3e24654283e21e6b5dacca5dd5715547a182f | CandyDong/Algorithms | /String/string_easy.py | 867 | 4 | 4 | #############################################reverse string###################################
def reverseString(s):
result = ""
length = len(s)
i = length-1
while (i >= 0):
result += s[i]
i -= 1
return result
#############################################reverse string###################################
#############################################reverse integer###################################
def reverse(x):
minNum = -1 << 31;
maxNum = (1 << 31) - 1;
sign = (-1) if (x < 0) else 1;
result = ''
digit_list = list(str(abs(x)))
for digit in list(reversed(digit_list)):
result += digit
resultInt = sign*int(result);
if ((resultInt < minNum) or (resultInt > maxNum)): return 0;
return resultInt;
#############################################reverse integer################################### |
fa66d73ef53ffe6f221af8f735fe476a54cb0e9e | abostroem/AstronomicalData | /_build/jupyter_execute/04_select.py | 16,124 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Chapter 4
#
# This is the fourth in a series of notebooks related to astronomy data.
#
# As a running example, we are replicating parts of the analysis in a recent paper, "[Off the beaten path: Gaia reveals GD-1 stars outside of the main stream](https://arxiv.org/abs/1805.00425)" by Adrian M. Price-Whelan and Ana Bonaca.
#
# In the first lesson, we wrote ADQL queries and used them to select and download data from the Gaia server.
#
# In the second lesson, we write a query to select stars from the region of the sky where we expect GD-1 to be, and save the results in a FITS file.
#
# In the third lesson, we read that data back and identified stars with the proper motion we expect for GD-1.
# ## Outline
#
# Here are the steps in this lesson:
#
# 1. Using data from the previous lesson, we'll identify the values of proper motion for stars likely to be in GD-1.
#
# 2. Then we'll compose an ADQL query that selects stars based on proper motion, so we can download only the data we need.
#
# 3. We'll also see how to write the results to a CSV file.
#
# That will make it possible to search a bigger region of the sky in a single query.
#
# After completing this lesson, you should be able to
#
# * Convert proper motion between frames.
#
# * Write an ADQL query that selects based on proper motion.
# ## Installing libraries
#
# If you are running this notebook on Colab, you can run the following cell to install Astroquery and a the other libraries we'll use.
#
# If you are running this notebook on your own computer, you might have to install these libraries yourself.
#
# If you are using this notebook as part of a Carpentries workshop, you should have received setup instructions.
#
# TODO: Add a link to the instructions.
#
# In[1]:
# If we're running on Colab, install libraries
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
get_ipython().system('pip install astroquery astro-gala pyia python-wget')
# ## Reload the data
#
# The following cells download the data from the previous lesson, if necessary, and load it into a Pandas `DataFrame`.
# In[2]:
import os
from wget import download
filename = 'gd1_dataframe.hdf5'
path = 'https://github.com/AllenDowney/AstronomicalData/raw/main/data/'
if not os.path.exists(filename):
print(download(path+filename))
# In[3]:
import pandas as pd
df = pd.read_hdf(filename, 'df')
centerline = pd.read_hdf(filename, 'centerline')
selected = pd.read_hdf(filename, 'selected')
# ## Selection by proper motion
#
# At this point we have downloaded data for a relatively large number of stars (more than 100,000) and selected a relatively small number (around 1000).
#
# It would be more efficient to use ADQL to select only the stars we need. That would also make it possible to download data covering a larger region of the sky.
#
# However, the selection we did was based on proper motion in the `GD1Koposov10` frame. In order to do the same selection in ADQL, we have to work with proper motions in ICRS.
#
# As a reminder, here's the rectangle we selected based on proper motion in the `GD1Koposov10` frame.
# In[4]:
pm1_min = -8.9
pm1_max = -6.9
pm2_min = -2.2
pm2_max = 1.0
# In[5]:
import astropy.units as u
pm1_rect = [pm1_min, pm1_min, pm1_max, pm1_max, pm1_min] * u.mas/u.yr
pm2_rect = [pm2_min, pm2_max, pm2_max, pm2_min, pm2_min] * u.mas/u.yr
# The following figure shows:
#
# * Proper motion for the stars we selected along the center line of GD-1,
#
# * The rectangle we selected, and
#
# * The stars inside the rectangle highlighted in green.
# In[6]:
import matplotlib.pyplot as plt
pm1 = centerline['pm_phi1']
pm2 = centerline['pm_phi2']
plt.plot(pm1, pm2, 'ko', markersize=0.3, alpha=0.3)
pm1 = selected['pm_phi1']
pm2 = selected['pm_phi2']
plt.plot(pm1, pm2, 'gx', markersize=0.3, alpha=0.3)
plt.plot(pm1_rect, pm2_rect, '-')
plt.xlabel('Proper motion phi1 (GD1 frame)')
plt.ylabel('Proper motion phi2 (GD1 frame)')
plt.xlim(-12, 8)
plt.ylim(-10, 10);
# Now we'll make the same plot using proper motions in the ICRS frame, which are stored in columns `pmra` and `pmdec`.
# In[7]:
pm1 = centerline['pmra']
pm2 = centerline['pmdec']
plt.plot(pm1, pm2, 'ko', markersize=0.3, alpha=0.3)
pm1 = selected['pmra']
pm2 = selected['pmdec']
plt.plot(pm1, pm2, 'gx', markersize=1, alpha=0.3)
plt.xlabel('Proper motion phi1 (ICRS frame)')
plt.ylabel('Proper motion phi2 (ICRS frame)')
plt.xlim([-10, 5])
plt.ylim([-20, 5]);
# The proper motions of the selected stars are more spread out in this frame, which is why it was preferable to do the selection in the GD-1 frame.
#
# But now we can define a polygon that encloses the proper motions of these stars in ICRS,
# and use the polygon as a selection criterion in an ADQL query.
#
# SciPy provides a function that computes the [convex hull](https://en.wikipedia.org/wiki/Convex_hull) of a set of points, which is the smallest convex polygon that contains all of the points.
#
# To use it, I'll select columns `pmra` and `pmdec` and convert them to a NumPy array.
# In[8]:
import numpy as np
points = selected[['pmra','pmdec']].to_numpy()
points.shape
# We'll pass the points to `ConvexHull`, which returns an object that contains the results.
# In[9]:
from scipy.spatial import ConvexHull
hull = ConvexHull(points)
hull
# `hull.vertices` contains the indices of the points that fall on the perimeter of the hull.
# In[10]:
hull.vertices
# We can use them as an index into the original array to select the corresponding rows.
# In[11]:
pm_vertices = points[hull.vertices]
pm_vertices
# To plot the resulting polygon, we have to pull out the x and y coordinates.
# In[12]:
pmra_poly, pmdec_poly = np.transpose(pm_vertices)
# The following figure shows proper motion in ICRS again, along with the convex hull we just computed.
# In[13]:
pm1 = centerline['pmra']
pm2 = centerline['pmdec']
plt.plot(pm1, pm2, 'ko', markersize=0.3, alpha=0.3)
pm1 = selected['pmra']
pm2 = selected['pmdec']
plt.plot(pm1, pm2, 'gx', markersize=0.3, alpha=0.3)
plt.plot(pmra_poly, pmdec_poly)
plt.xlabel('Proper motion phi1 (ICRS frame)')
plt.ylabel('Proper motion phi2 (ICRS frame)')
plt.xlim([-10, 5])
plt.ylim([-20, 5]);
# To use `pm_vertices` as part of an ADQL query, we have to convert it to a string.
#
# We'll use `flatten` to convert from a 2-D array to a 1-D array, and `str` to convert each element to a string.
# In[14]:
t = [str(x) for x in pm_vertices.flatten()]
t
# Now `t` is a list of strings; we can use `join` to make a single string with commas between the elements.
# In[15]:
pm_point_list = ', '.join(t)
pm_point_list
# ## Selecting the region
#
# Let's review how we got to this point.
#
# 1. We made an ADQL query to the Gaia server to get data for stars in the vicinity of GD-1.
#
# 2. We transformed to `GD1` coordinates so we could select stars along the centerline of GD-1.
#
# 3. We plotted the proper motion of the centerline stars to identify the bounds of the overdense region.
#
# 4. We made a mask that selects stars whose proper motion is in the overdense region.
#
# The problem is that we downloaded data for more than 100,000 stars and selected only about 1000 of them.
#
# It will be more efficient if we select on proper motion as part of the query. That will allow us to work with a larger region of the sky in a single query, and download less unneeded data.
#
# This query will select on the following conditions:
#
# * `parallax < 1`
#
# * `bp_rp BETWEEN -0.75 AND 2`
#
# * Coordinates within a rectangle in the GD-1 frame, transformed to ICRS.
#
# * Proper motion with the polygon we just computed.
#
# The first three conditions are the same as in the previous query. Only the last one is new.
#
# Here's the rectangle in the GD-1 frame we'll select.
# In[16]:
phi1_min = -70
phi1_max = -20
phi2_min = -5
phi2_max = 5
# In[17]:
phi1_rect = [phi1_min, phi1_min, phi1_max, phi1_max] * u.deg
phi2_rect = [phi2_min, phi2_max, phi2_max, phi2_min] * u.deg
# Here's how we transform it to ICRS, as we saw in the previous lesson.
# In[18]:
import gala.coordinates as gc
import astropy.coordinates as coord
corners = gc.GD1Koposov10(phi1=phi1_rect, phi2=phi2_rect)
corners_icrs = corners.transform_to(coord.ICRS)
# To use `corners_icrs` as part of an ADQL query, we have to convert it to a string. Here's how we do that, as we saw in the previous lesson.
# In[19]:
point_base = "{point.ra.value}, {point.dec.value}"
t = [point_base.format(point=point)
for point in corners_icrs]
point_list = ', '.join(t)
point_list
# Now we have everything we need to assemble the query.
# ## Assemble the query
#
# Here's the base string we used for the query in the previous lesson.
# In[20]:
query_base = """SELECT
{columns}
FROM gaiadr2.gaia_source
WHERE parallax < 1
AND bp_rp BETWEEN -0.75 AND 2
AND 1 = CONTAINS(POINT(ra, dec),
POLYGON({point_list}))
"""
# **Exercise:** Modify `query_base` by adding a new clause to select stars whose coordinates of proper motion, `pmra` and `pmdec`, fall within the polygon defined by `pm_point_list`.
# In[21]:
# Solution
query_base = """SELECT
{columns}
FROM gaiadr2.gaia_source
WHERE parallax < 1
AND bp_rp BETWEEN -0.75 AND 2
AND 1 = CONTAINS(POINT(ra, dec),
POLYGON({point_list}))
AND 1 = CONTAINS(POINT(pmra, pmdec),
POLYGON({pm_point_list}))
"""
# Here again are the columns we want to select.
# In[22]:
columns = 'source_id, ra, dec, pmra, pmdec, parallax, parallax_error, radial_velocity'
# **Exercise:** Use `format` to format `query_base` and define `query`, filling in the values of `columns`, `point_list`, and `pm_point_list`.
# In[23]:
# Solution
query = query_base.format(columns=columns,
point_list=point_list,
pm_point_list=pm_point_list)
print(query)
# Here's how we run it.
# In[24]:
from astroquery.gaia import Gaia
job = Gaia.launch_job_async(query)
print(job)
# And get the results.
# In[25]:
candidate_table = job.get_results()
len(candidate_table)
# ## Plotting one more time
#
# Let's see what the results look like.
# In[26]:
x = candidate_table['ra']
y = candidate_table['dec']
plt.plot(x, y, 'ko', markersize=0.3, alpha=0.3)
plt.xlabel('ra (degree ICRS)')
plt.ylabel('dec (degree ICRS)');
# Here we can see why it was useful to transform these coordinates. In ICRS, it is more difficult to identity the stars near the centerline of GD-1.
#
# So, before we move on to the next step, let's collect the code we used to transform the coordinates and make a Pandas `DataFrame`:
# In[27]:
from pyia import GaiaData
def make_dataframe(table):
"""Transform coordinates from ICRS to GD-1 frame.
table: Astropy Table
returns: Pandas DataFrame
"""
gaia_data = GaiaData(table)
c_sky = gaia_data.get_skycoord(distance=8*u.kpc,
radial_velocity=0*u.km/u.s)
c_gd1 = gc.reflex_correct(
c_sky.transform_to(gc.GD1Koposov10))
df = table.to_pandas()
df['phi1'] = c_gd1.phi1
df['phi2'] = c_gd1.phi2
df['pm_phi1'] = c_gd1.pm_phi1_cosphi2
df['pm_phi2'] = c_gd1.pm_phi2
return df
# Here's how we can use this function:
# In[28]:
candidate_df = make_dataframe(candidate_table)
# And let's see the results.
# In[44]:
x = candidate_df['phi1']
y = candidate_df['phi2']
plt.plot(x, y, 'ko', markersize=0.5, alpha=0.5)
plt.xlabel('ra (degree GD1)')
plt.ylabel('dec (degree GD1)');
# We're starting to see GD-1 more clearly.
#
# We can compare this figure with one of these panels in Figure 1 from the original paper:
#
# <img height="150" src="https://github.com/datacarpentry/astronomy-python/raw/gh-pages/fig/gd1-2.png">
#
# <img height="150" src="https://github.com/datacarpentry/astronomy-python/raw/gh-pages/fig/gd1-4.png">
#
# The top panel shows stars selected based on proper motion only, so it is comparable to our figure (although notice that it covers a wider region).
#
# In the next lesson, we will use photometry data from Pan-STARRS to do a second round of filtering, and see if we can replicate the bottom panel.
#
# We'll also learn how to add annotations like the ones in the figure from the paper, and customize the style of the figure to present the results clearly and compellingly.
# ## Saving the DataFrame
#
# Let's save this `DataFrame` so we can pick up where we left off without running this query again.
# In[30]:
get_ipython().system('rm -f gd1_candidates.hdf5')
# In[31]:
filename = 'gd1_candidates.hdf5'
candidate_df.to_hdf(filename, 'candidate_df')
# We can use `ls` to confirm that the file exists and check the size:
# In[32]:
get_ipython().system('ls -lh gd1_candidates.hdf5')
# If you are using Windows, `ls` might not work; in that case, try:
#
# ```
# !dir gd1_candidates.hdf5
# ```
# ## CSV
#
# Pandas can write a variety of other formats, [which you can read about here](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html).
#
# We won't cover all of them, but one other important one is [CSV](https://en.wikipedia.org/wiki/Comma-separated_values), which stands for "comma-separated values".
#
# CSV is a plain-text format with minimal formatting requirements, so it can be read and written by pretty much any tool that works with data. In that sense, it is the "least common denominator" of data formats.
#
# However, it has an important limitation: some information about the data gets lost in translation, notably the data types. If you read a CSV file from someone else, you might need some additional information to make sure you are getting it right.
#
# Also, CSV files tend to be big, and slow to read and write.
#
# With those caveats, here's how to write one:
# In[33]:
candidate_df.to_csv('gd1_candidates.csv')
# We can check the file size like this:
# In[34]:
get_ipython().system('ls -lh gd1_candidates.csv')
# The CSV file about 2 times bigger than the HDF5 file (so that's not that bad, really).
#
# We can see the first few lines like this:
# In[35]:
get_ipython().system('head -3 gd1_candidates.csv')
# The CSV file contains the names of the columns, but not the data types.
#
# We can read the CSV file back like this:
# In[36]:
read_back_csv = pd.read_csv('gd1_candidates.csv')
# Let's compare the first few rows of `candidate_df` and `read_back_csv`
# In[37]:
candidate_df.head(3)
# In[38]:
read_back_csv.head(3)
# Notice that the index in `candidate_df` has become an unnamed column in `read_back_csv`. The Pandas functions for writing and reading CSV files provide options to avoid that problem, but this is an example of the kind of thing that can go wrong with CSV files.
# ## Summary
#
# In the previous lesson we downloaded data for a large number of stars and then selected a small fraction of them based on proper motion.
#
# In this lesson, we improved this process by writing a more complex query that uses the database to select stars based on proper motion. This process requires more computation on the Gaia server, but then we're able to either:
#
# 1. Search the same region and download less data, or
#
# 2. Search a larger region while still downloading a manageable amount of data.
#
# In the next lesson, we'll learn about the databased `JOIN` operation and use it to download photometry data from Pan-STARRS.
# ## Best practices
#
# * When possible, "move the computation to the data"; that is, do as much of the work as possible on the database server before downloading the data.
#
# * For most applications, saving data in FITS or HDF5 is better than CSV. FITS and HDF5 are binary formats, so the files are usually smaller, and they store metadata, so you don't lose anything when you read the file back.
#
# * On the other hand, CSV is a "least common denominator" format; that is, it can be read by practically any application that works with data.
# In[ ]:
|
c035fcefec027a5b8e1c619b49d09c7c96cbc330 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/beginner-bite-169-simple-length-converter.py | 1,245 | 4.34375 | 4 | '''
Your task is to complete the convert() function. It's purpose is to convert centimeters to inches
and vice versa. As simple as that sounds, there are some caveats:
convert():
The function will take value and fmt parameters:
value: must be an int or a float otherwise raise a TypeError
fmt: string containing either "cm" or "in" anything else raises a ValueError.
returns a float rounded to 4 decimal places.
Assume that if the value is being converted into centimeters that the value is in inches and
centimeters if it's being converted to inches.
That's it!
'''
___ convert(value: f__, fmt: s..) __ f__:
"""Converts the value to the designated format.
:param value: The value to be converted must be numeric or raise a TypeError
:param fmt: String indicating format to convert to
:return: Float rounded to 4 decimal places after conversion
"""
__ t..(value) __ i.. o. t..(value) __ f__:
__ fmt.l.. __ "cm" o. fmt.l.. __ "in":
__ fmt.l.. __ "cm":
result value*2.54
r.. r..(result,4)
____
result value*0.393700787
r.. r..(result, 4)
____
r.. V...
____
r.. T..
print(convert(60.5, "CM" |
0ddfaaa3e78f7507cfa0cada48642f64e01c8789 | ximuwang/Python_Crash_Course | /Chap9_Classes/Practice/user_module.py | 1,010 | 3.921875 | 4 | # A user module
class Users():
'''A class representing users'''
def __init__(self, first, last, user_profile):
'''Initialize the users'''
self.first_name = first
self.last_name = last
self.user_profile = user_profile
self.login_attempts = 0
def describe_user(self):
'''Display the information of users'''
print('')
print("First name: " + self.first_name.title())
print("Last name: " + self.last_name.title())
print("Profile: " + self.user_profile)
def greet_user(self):
'''Display a message that greet the user'''
full_name = self.first_name + ' ' + self.last_name
full_name = full_name.title()
print('\n\nWelcome! ' + '\n' + full_name)
def increment_login_attempts(self):
self.login_attempts += 1
return self.login_attempts
def reset_login_attempts(self):
self.login_attempts = 0
return self.login_attempts |
c84ec1c58774a4bd33d490e727f3d3233fad2d5d | HyeonJun97/Python_study | /Chapter06/Chapter6_pb2.py | 261 | 3.53125 | 4 | #Q6.2
def sumDigits(n):
sum=0
while n!=0:
sum+=n%10
n=n//10
return sum
def main():
a=eval(input("정수를 입력하세요: "))
print(a,"의 각 자릿수의 합은",sumDigits(a),"입니다.")
main() |
ffc206c03e989689c2b14043df6da47b2d7234ca | itizarsa/python-workouts | /reverseNumber.py | 241 | 4.40625 | 4 | #program to enter a number and print its reverse
number=int(input("Enter Number "))
reverse=0
i=0
while i<number:
last_num=number%10
reverse=(reverse*10)+last_num
number=number//10
print("The Reverse of numbers are", reverse) |
254b667fe980285a95e9c22cff6d38a6acede3dd | maxwell-martin/gaddis-python2018-projects | /magic_dates/magic_dates.py | 241 | 4.1875 | 4 | month = int(input("Enter the month (numeric): "))
day = int(input("Enter the day (numeric): "))
year = int(input("Enter a two digit year: "))
if month * day == year:
print("The date is magic.")
else:
print("The date is not magic.")
|
1bdde830ff3445ec16101fd5be187d186aa46a35 | epidersis/olymps | /705A/705A.py | 157 | 3.78125 | 4 | string = ['I hate that' if x % 2 == 0 else 'I love that' for x in range(int(input()))]
string[-1] = string[-1].replace('that', 'it')
print(' '.join(string))
|
caf0de2234614941d2affedac15427224e41ff96 | threemay/python3_study | /class/bicycile.py | 917 | 4 | 4 | class bicycle:
def __init__(self,name):
self.name = name
def run(self, km):
print(self.name,'has ride',km,'KM by legs')
class Ebicycle(bicycle):
volume = 0
def __init__(self,name):
super().__init__(name)
def Charge(self,vol):
Ebicycle.volume += vol
print(name, 'charged',vol, 'now volume is',Ebicycle.volume)
def run(self,km):
if km <= 10 * Ebicycle.volume:
print(name,'ride',km,'KM by electricity')
Ebicycle.volume -= km/10
if km > 10 * Ebicycle.volume:
print(self.name,'ride',10 * Ebicycle.volume,'KM by electricity')
super().run(km - 10 * Ebicycle.volume)
Ebicycle.volume = 0
print('current volume:', Ebicycle.volume)
def main():
b1 = bicycle('b1')
b1.run(10)
b2 = Ebicycle('b2')
#b2.Charge(100)
b2.run(60)
if __name__ == '__main__':
main() |
1474321166a753e472e7e308abb997de2a53c2d3 | NMoro811/Battleship-Online-AI | /textbox_class.py | 5,243 | 3.640625 | 4 | '''
Contains the TextBox class
'''
import os
import pygame as game
game.init()
game.event.set_allowed([game.MOUSEBUTTONDOWN, game.KEYDOWN])
# TextBox design
inactive_color = game.Color("dark gray")
active_color = game.Color("black")
background_color = (0, 85, 128)
default_font = game.font.SysFont('Cambria',30)
# Buttons
green_tick = game.image.load(os.path.join("img", "check.png"))
green_tick = game.transform.scale(green_tick, (30, 30))
red_cross = game.image.load(os.path.join("img", "remove.png"))
red_cross = game.transform.scale(red_cross, (30, 30))
class TextBox():
''' Creates simple input boxes for the user to introduce his/her username
Attributes:
pos_x Horizontal position of the input box's rect (i.e., where the text is rendered)
pos_y Vertical position
width Textbox's width
height Textbox's width
rect Creates a rectangle with the same dimensions
background_rect The rectangle containing the textbox and the two buttons
original_text Default text to be displayed if the textbox is empty
text Introduced by the user as their name
font Text's font
active Checks if the textbox has been clicked on
color Current color of the textbox's borders
text_surf To display the introduced text
finished 0 if text is still being introduced, 1 if done
final_str Entered string
Methods:
handle_event Modifies the textbox for a given PyGame event
draw Draw the TextBox, the rectangle that contains it, and display the buttons
'''
def __init__(self, pos_x, pos_y, width, height, player_num):
self.pos_x = pos_x
self.pos_y = pos_y
self.width = width
self.height = height
self.rect = game.Rect(pos_x, pos_y, width, height)
self.background_rect = self.rect.inflate(pos_x*0.5, pos_y*0.5)
if player_num == 0:
self.original_text = "Username" # To be used in Player vs CPU or LAN/Online
elif player_num == 1:
self.original_text = "Player1" # Player 1 in Local gameplay
else:
self.original_text = "Player2" # Player 2 in Local gameplay
self.text = self.original_text
self.font = default_font
self.active = False # Inactive textbox by default
self.color = inactive_color # Default colour is inactive
self.text_surf = default_font.render(self.text, True, self.color)
self.finished = 0
self.final_str = self.text
def handle_event(self, event):
''' Handle the given PyGame event
Input: (PyGame) event
Output: None
'''
# Set up the two buttons' coordinates and store their rect surfaces
bottom_right = self.background_rect.bottomright
green_tick_coords = (bottom_right[0]-80, bottom_right[1]-50)
green_tick_rect = green_tick.get_rect(topleft=green_tick_coords)
red_cross_coords = (bottom_right[0]-40, bottom_right[1]-50)
red_cross_rect = red_cross.get_rect(topleft=red_cross_coords)
# Used to activate the TextBox, give it the corresponding color, and swap the
# default text with an empty string (and vice versa)
if event.type == game.MOUSEBUTTONDOWN:
mouse_pos = event.pos
# Clicked on the text box
if self.rect.collidepoint(mouse_pos):
self.active = not self.active
# Clicked on the green 'Enter' button
elif green_tick_rect.collidepoint(mouse_pos):
self.active = False
self.finished = 1
self.final_str = self.text
return
# Clicked on the red 'Discard' button
elif red_cross_rect.collidepoint(mouse_pos):
self.active = False
self.finished = 1
return "red_cross"
# Clicked elsewhere
else:
self.active = False
# Modify input box's color and text
if self.active:
self.color = active_color
if self.text == self.original_text:
self.text = ''
else:
self.color = inactive_color
if self.text == '':
self.text = self.original_text
# Used for typing the username down
elif event.type == game.KEYDOWN:
if self.active:
# Pressed 'Enter' key
if event.key == game.K_RETURN:
self.finished = 1
self.final_str = self.text
return
# Pressed 'Backspace' key
elif event.key == game.K_BACKSPACE:
self.text = self.text[:-1]
else:
self.text += event.unicode
# Add a (non-blinking) bar '|' if the text box is active
if self.active:
self.text_surf = default_font.render(self.text+'|', True, self.color)
else:
self.text_surf = default_font.render(self.text, True, self.color)
def draw(self, screen):
# Set up the two buttons' coordinates and store their rect surfaces
bottom_right = self.background_rect.bottomright
green_tick_coords = (bottom_right[0]-80, bottom_right[1]-50)
green_tick_rect = green_tick.get_rect(topleft=green_tick_coords)
red_cross_coords = (bottom_right[0]-40, bottom_right[1]-50)
red_cross_rect = red_cross.get_rect(topleft=red_cross_coords)
# Draw all components
game.draw.rect(screen, background_color, self.background_rect)
screen.blit(green_tick, green_tick_coords)
screen.blit(red_cross, red_cross_coords)
game.draw.rect(screen, (255,255,255), self.rect)
screen.blit(self.text_surf, (self.rect.x+5, self.rect.y+5))
game.draw.rect(screen, self.color, self.rect, 2) |
da4d91057f6c3fa848fd7f5e3205277ad7a182d2 | vimallohani/LearningPython | /three_dry.py | 646 | 3.71875 | 4 | #Dry principle says do not repeat same lines.
#This is better version of exercise_three_eight_guessing_game
import random
rand=random.randint(1,100)
counter=1
gameover=False #just to make logic for a gammer point of view
while not gameover:
num=int(input("Please guess a number between 1 and 100 :"))
if num== rand:
print(f"You win: Total guess : {counter}")
gameover=True
break
else: #now this below code is not repeating line
if num>rand:
print("Too high")
else:
print("Too low")
counter+=1
continue |
ee438e3878a7fcf5ec6e2a0a9c0cd7f5166a8315 | saswatmohanty95/trainingassignments | /Python/Assessments/Day1/Dayofmonth.py | 524 | 4 | 4 | '''
a=input("Enter date in number dd:")
if int(a)%7==1:
print("Friday")
elif int(a)%7==2:
print("Saturday")
elif int(a)%7==3:
print("Sunday")
elif int(a)%7==4:
print("Monday")
elif int(a)%7==5:
print("Tuesday")
elif int(a)%7==6:
print("Wednesday")
elif int(a)%7==0:
print("Thursday")
'''
days=['Thursday','Friday','Saturday','Sunday','Monday','Tuesday','Wednesday']
date=input("Enter date in dd format for the month of November: ")
d=int(date)
if d>0 and d<=30:
print(days[(d%7)])
else:
print("Invalid Date")
|
403a1bf5c865478b68e73ef361887aba8720474b | edu-athensoft/stem1401python_student | /py200325_python1/py200508/homework/stem1401_python_homework_12_max.py | 456 | 3.984375 | 4 | """
Quiz 6
"""
# 8.
matrix123 = [[1,2],[1,2],[1,2]]
print(matrix123[0])
print(matrix123[1])
print(matrix123[2])
# 9.
# 9.1
print("The dimensions of the box are {}, {}, {}".format("width: 30cm", "height: 20cm", "depth: 10cm"))
# 9.2
print("The dimensions of the box are {2}, {1}, {0}".format("depth: 10cm", "height: 20cm", "width: 30cm",))
# 9.3
print("The dimensions of the box are {0}, {2}, {1}".format("height: 20cm", "depth: 10cm", "width: 30cm",))
|
cd99d21a5e6785a65eb0f2f17749eb28ff5fa385 | yoanschnee/Neural-Network | /yoannet/loss.py | 720 | 3.671875 | 4 | """
A loss function measures how good our predictions are
we can use this to adjust the parameters of our network
"""
from yoannet.tensor import Tensor
import numpy as np
class Loss:
def loss(self, predicted: Tensor, actual: Tensor) -> float:
raise NotImplementedError
def grad(self, predicted: Tensor, actual: Tensor) -> Tensor:
raise NotImplementedError
class MSE(Loss):
"""
MSE is mean squarred error, although we'll do just the total squared error
"""
def loss(self, predicted: Tensor, actual: Tensor) -> float:
return np.sum((predicted - actual) ** 2)
def grad(self, predicted: Tensor, actual: Tensor) -> Tensor:
return 2 * (predicted - actual)
|
7a292b5a02f844649369413de53cd9170aac622d | jameswmccarty/AdventOfCode2015 | /day4.py | 1,512 | 4.0625 | 4 | #!/usr/bin/python
import hashlib
"""
--- Day 4: The Ideal Stocking Stuffer ---
Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.
To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key (your puzzle input, given below) followed by a number in decimal. To mine AdventCoins, you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash.
For example:
If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the lowest such number to do so.
If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef....
Your puzzle input is yzbqklnj.
--- Part Two ---
Now find one that starts with six zeroes.
"""
if __name__ == "__main__":
# Part 1 Solution
num = 0
prefix = "yzbqklnj"
m = hashlib.md5()
while m.hexdigest()[0:5] != "00000":
m = hashlib.md5()
m.update(prefix+str(num))
num += 1
print num-1
# Part 2 Solution
num = 0
prefix = "yzbqklnj"
m = hashlib.md5()
while m.hexdigest()[0:6] != "000000":
m = hashlib.md5()
m.update(prefix+str(num))
num += 1
print num-1
|
b8e3f5f3d87fd72ca2285c6be3337fccffaf19e4 | rashmiranganath/list-programs-python- | /min_max.py | 227 | 3.5 | 4 | def min(a):
i=0
min=list[i]
while i<len(list):
if list[i]<min:
min=list[i]
i=i+1
print min
j=0
max=list[j]
while j<len(list):
if list[j]>max:
max=list[j]
j=j+1
print max
list=[2,5,8,1,20,0]
min(list)
|
5da0894635c4aa2e418a9c8c3d142425cf7dbedb | handole/pythonthusiast-course | /Fundamental/denih/latihan1.py | 291 | 4.125 | 4 | names = ['Jep', 'Ger', 'Joll', 'Sam']
for name in names:
print('Hello there, ' + name)
print(' '.join(['Hello there,', name]))
print(', '.join(names))
who = 'Garyy'
how_many = 12
print(who, 'bought', how_many, 'apple today!')
print('{} bought apples today!'.format(who, how_many)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.