blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e79be156fc9fa86f86179e21c7f84cacf06cc72b | kovsaw/Hand-vessel-identification | /binary_array.py | 304 | 3.71875 | 4 | import numpy
def _binary_array_to_hex(arr):
"""
internal function to make a hex string out of a binary array.
"""
bit_string = ''.join(str(b) for b in 1 * arr.flatten())
width = int(numpy.ceil(len(bit_string)/4))
return '{:0>{width}x}'.format(int(bit_string, 2), width=width)
A
|
b792612970f4dc773371a0f09b50f39457d570cb | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/beer-song/cb3fcb6f7f0246698078861a61ef5a00.py | 918 | 3.890625 | 4 | class Beer:
""" Counts down the bottles of beer on the wall song"""
def verse(self, n):
if n == 0:
return "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"
b = "bottles"
c = n - 1
d = "one"
if n == 1:
b = "bottle"
c = "no more"
d = "it"
line1 = "{} {} of beer on the wall, {} {} of beer.\n".format(n,b, n,b)
line2 = "Take {} down and pass it around, {} bottles of beer on the wall.\n".format(d, c)
if n == 2:
line2 = "Take {} down and pass it around, {} bottle of beer on the wall.\n".format(d, c)
return line1 + line2
def sing(self, start, end = 0):
result = ""
for i in range(start, end - 1, -1):
result = result + self.verse(i) + "\n"
return result
|
fb1287b49b4a2b7a498ec1c26a22c0fa6390b8db | JMCCMJ/CSCI-220-Introduction-to-Programming | /HW12/hw12.py | 13,950 | 3.921875 | 4 | #hw12.py
#Jan-Michael Carrington
#Purpose: To construct a class for a deck of cards.
#Authenticity: I certify this code is my own work.
from graphics import *
from random import *
from time import sleep
class Button:
"""A button is a labeled rectangle in a window.
It is activated or deactivated with the activate()
and deactivate() methods. The clicked(p) method
returns true if the button is active and p is inside it."""
def __init__(self, win, center, width, height, label, color):
""" Creates a rectangular button, eg:
qb = Button(myWin, centerPoint, width, height, 'Quit','yellow') """
self.xmax, self.xmin = center.getX()+width/2.0, center.getX()-width/2.0
self.ymax, self.ymin = center.getY()+height/2.0, center.getY()-height/2.0
p1,p2 = Point(self.xmin, self.ymin), Point(self.xmax, self.ymax)
self.rect = Rectangle(p1,p2)
self.rect.setFill(color)
self.label = Text(center, label)
self.win = win
self.active = False
def clicked(self, p):
"Returns true if button active and p is inside"
return (self.active and
self.xmin <= p.getX() <= self.xmax and
self.ymin <= p.getY() <= self.ymax)
def activate(self):
"Sets this button to active and draws the button."
if self.active == False:
self.active = True
self.rect.draw(self.win)
self.label.draw(self.win)
def deactivate(self):
"Sets this button to 'inactive' and undraws the button."
if self.active == True:
self.active = False
self.rect.undraw()
self.label.undraw()
class Words:
'''reads a file of words and creates a list of words'''
def __init__(self,filename):
infile = open(filename,'r')
self.file_string = infile.read()
infile.close()
self.file_string_split = self.file_string.split()
#print(self.file_string_split)
def get_word(self):
'''returns a random word from the list'''
self.amt_words = len(self.file_string_split)
rand_num = randrange(0,self.amt_words)
self.rand_word = self.file_string_split[rand_num]
self.file_string_split.pop(rand_num)
return self.rand_word
def length_of_file(self):
return self.amt_words
#print(self.rand_word)
#print(self.file_string_split)
class Guess:
def __init__ (self,word,win,head,body,left_leg,right_leg,left_arm,right_arm,right_eye_1,right_eye_2,eye1,eye2):
self.win = win
self.let_guessed = []
self.word = word
self.head=head
self.body = body
self.left_leg = left_leg
self.right_leg = right_leg
self.left_arm = left_arm
self.right_arm = right_arm
self.right_eye_1 = right_eye_1
self.right_eye_2 = right_eye_2
self.eye1 = eye1
self.eye2 = eye2
#print(self.word)
list_letters = {}
length = (len(self.word))
for letter in self.word:
list_letters[letter] = list_letters.get(letter,0)+1
#print(list_letters)
#x = list_letters.get('c')
#print(x)
self.word_letters = []
for i in range(length):
self.word_letters.append(self.word[i])
#print(self.word_letters)
self.word_empty = []
for i in range(length):
under = '_'
self.word_empty.append(under)
#print(self.word_empty)
self.word_third = []
for i in range(length):
#self.word_third.append(self.word[i])
under = '_'
self.word_third.append(under)
#print(self.word_third)
#print(self.word_third)
#self.letters_guessed = ''
self.num_guesses = 7
def missed (self):
'''returns the word string that could not be guessed'''
def guess_letter (self,letter):
'''uncovers letters that match the guess, counts the bad guesses
and keeps track of the letters guessed. It returns a number, 0,
if the letter has already been guessed, 1 if the letter is NOT
in the word and 2 if the letter IS in the word
'''
try:
self.guessed_letter = self.word_letters.index(letter)
self.word_empty[self.guessed_letter] = self.word_letters[self.guessed_letter]
#self.word_letters.remove(letter)
self.word_letters[self.guessed_letter] = self.word_third[self.guessed_letter]
#print(self.word_empty)
#print(self.guessed_letter)
self.finished = ""
for letter in self.word_empty:
self.finished = self.finished + letter
return self.guessed_letter
except ValueError:
#self.num_guesses = self.num_guesses + 1
#print(self.num_guesses)
return None
def gameover (self,letter):
'''returns Boolean, T if word is guessed or the number of guesses
has exceeded the limit and F otherwise'''
try:
guess = self.word_letters.index(letter)
return 7
except:
self.num_guesses = self.num_guesses - 1
#print('Wrong letter.')
#print('You have', self.num_guesses, 'guesses left.')
self.noose_num = self.num_guesses
noose = Noose(self.win,self.noose_num,self.head,self.body,self.left_leg,self.right_leg,self.left_arm,self.right_arm,self.right_eye_1,self.right_eye_2,self.eye1,self.eye2)
noose.wrong()
return self.num_guesses
def gameover_win(self):
try:
if self.finished == self.word:
return 1
except AttributeError:
return 0
def num_of_guesses(self):
'''returns a STRING with the number of remaining guesses'''
def letters_guessed (self,let):
'''returns a string, in alphabetical order, of all the letters
that have been guessed'''
try:
z = self.let_guessed.index(let)
if z == -7:
#print("You already guessed that.")
self.num_guesses = self.num_guesses + 1
except ValueError:
self.let_guessed.append(let)
self.let_guessed.sort()
def letters_guessed_print(self):
#print(self.let_guessed)
#print()
return self.let_guessed
def __str__ (self):
'''returns a string with the letters in the word and _ for each
unguessed letter separated by spaces'''
self.string = ""
for letter in self.word_empty:
self.string = self.string + letter + " "
return self.string
class Noose:
def __init__(self,win,num,head,body,left_leg,right_leg,left_arm,right_arm,right_eye_1,right_eye_2,eye1,eye2):
'''creates a Noose object with 7 sections that can be drawn one at a
time in the win canvas'''
self.win = win
self.num = num
self.head=head
self.body = body
self.left_leg = left_leg
self.right_leg = right_leg
self.left_arm = left_arm
self.right_arm = right_arm
self.right_eye_1 = right_eye_1
self.right_eye_2 = right_eye_2
self.eye1 = eye1
self.eye2 = eye2
def wrong(self):
'''draws another of the 7 sections to the noose platform and/or figure'''
if self.num == 6:
self.head.draw(self.win)
if self.num == 5:
self.body.draw(self.win)
if self.num == 4:
self.left_leg.draw(self.win)
if self.num == 3:
self.right_leg.draw(self.win)
if self.num == 2:
self.left_arm.draw(self.win)
if self.num == 1:
self.right_arm.draw(self.win)
if self.num == 0:
self.right_eye_1.draw(self.win)
self.right_eye_2.draw(self.win)
self.eye1.draw(self.win)
self.eye2.draw(self.win)
def play_one_game():
win = GraphWin('Hangman', 600, 600)
floor = Line(Point(20,400),Point(200,400))
floor.draw(win)
pole = Line(Point(110,400),Point(110,100))
pole.draw(win)
upper_pole = Line(Point(110,100),Point(250,100))
upper_pole.draw(win)
small_pole = Line(Point(250,100),Point(250,150))
small_pole.draw(win)
guess_button = Button(win,Point(550,100),75,75,'Enter','yellow')
guess_button.activate()
user_guess = Entry(Point(500,100),1)
user_guess.draw(win)
start_button = Button(win,Point(50,50),75,75,'Start','green')
start_button.activate()
words_view = Text(Point(300,500), '')
words_view.draw(win)
words_used_view = Text(Point(500,300),'')
letters_you_used = Text(Point(500,285),'Letters you have used:')
guesses_left = Text(Point(485,350),'')
guesses_left.draw(win)
you_win_text = Text(Point(300,550),'You Win!')
you_lose_text = Text(Point(300,550),'You Lose...')
play_again_text = Text(Point(125,450),'Do you want to play again?')
yes_button = Button(win,Point(75,500),75,75,'Yes','cyan')
no_button = Button(win,Point(175,500),75,75,'No','red')
click_start = Text(Point(125,500),'Hit start when this \n text dissapears to begin.')
head = Circle(Point(250,175),25)
body = Line(Point(250,200),Point(250,275))
left_leg = Line(Point(250,275),Point(200,350))
right_leg = Line(Point(250,275),Point(300,350))
left_arm = Line(Point(250,225),Point(200,275))
right_arm = Line(Point(250,225),Point(300,275))
right_eye_1 = Line(Point(235,180),Point(245,165))
right_eye_2 = Line(Point(235,165),Point(245,180))
right_eye_1.setFill('red')
right_eye_2.setFill('red')
eye1 = right_eye_1.clone()
eye2 = right_eye_2.clone()
eye1.move(20,0)
eye2.move(20,0)
words = Words('wordlist.txt')
rand_word = words.get_word()
amt_of_plays = words.length_of_file()
#print(rand_word)
while True:
mouse = win.getMouse()
user_guess.setText('')
if start_button.clicked(mouse):
letters_you_used.draw(win)
words_used_view.draw(win)
for i in range(amt_of_plays):
x = Guess(rand_word,win,head,body,left_leg,right_leg,left_arm,right_arm,right_eye_1,right_eye_2,eye1,eye2)
x.letters_guessed_print()
#print(x)
words_view.setText(x)
while True:
point = win.getMouse()
if guess_button.clicked(point):
user_letter = user_guess.getText()
letters = x.letters_guessed(user_letter)
guess_wrong_count = x.gameover(user_letter)
string_guesses_left = 'You have ' + str(guess_wrong_count) + ' wrong guesses left.'
if guess_wrong_count == 0:
you_lose_text.draw(win)
you_win_text.move(1000,1000)
you_win_text.draw(win)
sleep(3)
you_win_text.undraw()
you_win_text.move(-1000,-1000)
you_lose_text.undraw()
play_again_text.draw(win)
yes_button.activate()
no_button.activate()
pt = win.getMouse()
break;
while True:
a = x.guess_letter(user_letter)
if a == None:
break;
guesses_left.setText(string_guesses_left)
words_view.setText(x)
#print(x)
letters_used = x.letters_guessed_print()
words_used_view.setText(letters_used)
guess_right = x.gameover_win()
if guess_right == 1:
you_win_text.draw(win)
you_lose_text.move(1000,1000)
sleep(3)
you_win_text.undraw()
you_lose_text.undraw()
you_lose_text.move(-1000,-1000)
play_again_text.draw(win)
yes_button.activate()
no_button.activate()
pt = win.getMouse()
break;
rand_word = words.get_word()
break;
if no_button.clicked(pt):
win.close()
break;
if yes_button.clicked(pt):
head.undraw()
body.undraw()
left_leg.undraw()
right_leg.undraw()
right_arm.undraw()
left_arm.undraw()
right_eye_1.undraw()
right_eye_2.undraw()
eye1.undraw()
eye2.undraw()
yes_button.deactivate()
no_button.deactivate()
click_start.draw(win)
guesses_left.undraw()
letters_you_used.undraw()
words_used_view.undraw()
play_again_text.undraw()
sleep(4)
click_start.undraw()
play_one_game()
|
8fef5bc6a5090423c79d925793663e82a52a7ba8 | s-touchstone/College | /Advanced Computer Languages - Python/CantorStart - Bonus.py | 940 | 4.21875 | 4 | #Steven Touchstone
#Advanced Programming Language (Python)
#Professor Vladimir Ufimtsev
#Cantor Lines Assignment (Bonus)
import turtle as T
#raise/lower pen for drawing lines
def _bwswitch():
if T.isdown():
T.up()
else:
T.down()
#drawing the white lines over the black to cut in thirds
def _cantor(x, y, i):
dec = 600
T.color("white")
T.up()
while i > 0:
dec /= 3
while x > -300:
x -= dec
T.goto(x, y)
_bwswitch()
x = 300
i -= 1
T.up()
T.goto(x, y)
T.goto(-300, y)
#main area to draw black lines and call the cantor function
def _main():
T.width(5)
y = 80
for i in range(5):
# for i in range (8):
x = -300
T.up()
T.goto(x, y)
T.color("black")
T.down()
x = 300
T.goto(x, y)
_cantor(x, y, i)
y -= 10
_main()
T.done()
#Change all '300's to 150 or any other number to change the line size
#change 'dec' variable to double the number placed in the '300's
|
20b2cc8ce0b04d20556c29bf7ae9fe7882006691 | HarlanJ/CS-Python | /PrimeNumber.py | 2,070 | 4.21875 | 4 | #John Harlan
#Prime Number function
#CS 100
#------Algorithm------
#1. Ask user for a number to test
#2. store answer (query)
#3a. If query is prime
#3a1a.create a place to store if the query is prime,defaulting to True
#(prime)
#3a1b. create somplace to store the current number (i) defaulting to 2
#3a1c. check to see if query is divisible by i
#3a1c1. if query / the current number has no remainder
#3a1c2. set prime to false
#3a1c3. goto 3a1c2
#3a1c2. increase i by 1
#3a1c3. goto 3a1c
#3a1d. return the the value of prime
#3a2. tell user that the query is prime
#3a3. goto 4
#3b. If query is not prime
#3b1. Tell user that the query is not prime
#3b2. goto 4
#4. end of main function
#-------Program-------
import math
def is_prime(a):
#3a1a. create a place to store if the query is prime, defaulting to True (prime)
prime = True
#3a1b. create somplace to store the current number (i) defaulting to 2
i = 2
#3a1c. check to see if query is divisible by i
while (i < math.sqrt(a) + 1 and prime):
#3a1c1. if query / the current number has no remainder
if a % i == 0:
#3a1c2. set prime to false
prime = False
#3a1c3. goto 3a1c2
#3a1c2. increase i by 1
i += 1
#3a1c3. goto 3a1c
#3a1d. return the the value of prime
return prime
def main():
#1. Ask user for a number to test
#2. store answer (query)
query = int(input("What number would you like to test?\n>"))
#3a. If query is prime
if is_prime(query):
#3a2. tell user that the query is prime
print(query, "is a prime.")
#3a3. goto 4
#3b. If query is not prime
else:
#3b1. Tell user that the query is not prime
print(query, "is not a prime")
#3b2. goto 4
#4. end of main function
#run forever
while True:
main()
|
e75513836ed2379ad2fcf345b93b3b1c32f26b7d | nhuntwalker/canvas-automation | /pair-maker.py | 1,433 | 3.953125 | 4 | """This module can be used to form pairs for students.
David Smith - 2017
"""
import random
def make_better_pairs(num_days, students):
"""Print out some pairs for a given number of days."""
student_dict = {}
for student in students:
temp = dict({})
for s in students:
if s != student:
temp.setdefault(s, 0)
student_dict[student] = temp
for day in range(0, num_days):
used = set()
random.shuffle(students)
students = sorted(students, key=lambda x: sorted(student_dict[x].values())[-1], reverse=True)
print('')
print(' - Day', day + 1, '-')
print('------------')
for student in students:
if student not in used:
try:
partner = min([(v, k) for k, v in student_dict[student].items() if k not in used])[1]
used.add(student)
used.add(partner)
student_dict[student][partner] += 1
student_dict[partner][student] += 1
print(student, '-', partner)
except ValueError:
print('-->', student, 'must be a third.')
if __name__ == '__main__':
STUDENT_LIST = ['Bob', 'Sarah', 'Jules', 'Harold', 'Natasha', 'Veronique', 'Harry', 'John', 'Maggie', 'Wendy', 'Greg', 'Alice', 'Terry', 'Trent']
make_better_pairs(20, STUDENT_LIST)
|
45b68b6e15e92d3b650cdcc3d25df202085c1f4b | codexnubes/Coding_Dojo | /api_ajax/OOP/car/car.py | 1,078 | 3.921875 | 4 | class Car(object):
def __init__(self,price,speed,fuel,mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if price > 10000:
self.tax = 0.15
else:
self.tax = 0.12
self.display_all()
def display_all(self):
print "\t\t\bPrice: ${0.price}\n\
Speed: {0.speed}\n\
Fuel: {0.fuel}\n\
Mileage: {0.mileage}\n\
Tax: {0.tax}\n".format(self)
if __name__ == "__main__":
car1 = Car(2000, "35mph", "Full", "10mpg")
car2 = Car(11000, "130mph", "Empty", "20mpg")
car3 = Car(5000, "65mph", "Half Full", "22mpg")
car4 = Car(7000, "50mph", "Full", "35mpg")
car5 = Car(100000, "200mph", "Full", "15mpg")
car6 = Car(1500, "45mph", "Half Full", "11mpg")
# car1.display_all()
# print ""
# car2.display_all()
# print ""
# car3.display_all()
# print ""
# car4.display_all()
# print ""
# car5.display_all()
# print ""
# car6.display_all()
|
bc7e4baf2b40dd67c4d35a7d9468a10075605965 | jupiterangulo/randomDraftOrder2018 | /draftOrderPublic.py | 886 | 4.03125 | 4 | # import libraries
import random
import time
# create function for Draft Order
def assignDraftOrder():
# enter number of players in your league
size = 10 #default to 10
# insert players names here
players = ['Bob', 'Ray', 'Fred', 'Leroy', 'Otis',
'Chet', 'Chad', 'Miles', 'Guy', 'Clay']
print ('The order of players as they joined is:')
for i in range(0,size):
j = i + 1
print ("{}. {}".format(j, players[i]))
# randomize the list to get the draft order
draftOrder = random.sample(players, len(players))
# dramatic pause
time.sleep(5)
# output the draft order with a dramatic pause
print ('The Draft Order Is:')
# one more dramatic pause because why not
time.sleep(3)
for i in range(0,size):
j = i + 1
print ("{}. {}".format(j, draftOrder[i]))
time.sleep(3)
|
26bcef22ef45b73215765abb4c42704e6facdd8b | craignicol/adventofcode | /2020/day.1.py | 906 | 3.796875 | 4 | #!/usr/bin/env python3
def execute():
with open('2020/input/1.txt') as inp:
lines = inp.readlines()
numbers = [int(l.strip()) for l in lines if len(l.strip()) > 0]
return multiply_to_2020(numbers), multiply_3_to_2020(numbers)
def verify(a, b):
if (a == b):
print("✓")
return
print (locals())
def multiply_to_2020(number_list):
s = set()
for n in number_list:
if (2020-n) in s:
return n * (2020-n)
s.add(n)
def multiply_3_to_2020(number_list):
s = set()
for n in number_list:
for x in s:
if (2020-n-x) in s:
return n * x * (2020-n-x)
s.add(n)
def test_cases():
verify(multiply_to_2020([1721,979,366,299,675,1456]), 514579)
verify(multiply_3_to_2020([1721,979,366,299,675,1456]), 241861950)
if __name__ == "__main__":
test_cases()
print(execute()) |
57b5de8d87c1184fd1d2b19081949016653a9b2f | Web-Dev-Collaborative/Lambda-Final-Backup | /7-assets/past-student-repos/Sorting-master/src/recursive_sorting/recursive_sorting.py | 3,245 | 4.125 | 4 | import random
# TO-DO: complete the helper function below to merge 2 sorted arrays
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
# Iterate through marged_arr to insert smallest item in arrA and arrB until merged_arr is full
for i in range(0, len(merged_arr)):
# If arrA is empty, use arrB to fill
if len(arrA) == 0:
merged_arr[i] = min(arrB)
arrB.remove(min(arrB))
# If arrB is empty, use arrA to fill
elif len(arrB) == 0:
merged_arr[i] = min(arrA)
arrA.remove(min(arrA))
# If the smallest item in arrA is smaller than the smallest item in arrB, insert arrA's smallest item and then remove from arrA
elif min(arrA) < min(arrB):
merged_arr[i] = min(arrA)
arrA.remove(min(arrA))
# If the smallest item in arrB is smaller than the smallest item in arrA, insert arrB's smallest item and then remove from arrB
elif min(arrA) >= min(arrB):
merged_arr[i] = min(arrB)
arrB.remove(min(arrB))
return merged_arr
# TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort( arr ):
if len(arr) == 0 or len(arr) == 1:
return arr
mid_point = round(len(arr)/2)
arrA = merge_sort(arr[:mid_point])
arrB = merge_sort(arr[mid_point:])
return merge(arrA,arrB)
# STRETCH: implement an in-place merge sort algorithm
def merge_in_place(arr, start, mid, end):
# Updating the pointers
# Getting past the halfway
# Assign a variable to track the index of the other starting point
# Decrement
return arr
def merge_sort_in_place(arr, l, r):
# TO-DO
return arr
# STRETCH: implement the Timsort function below
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
def insertion_sort(arr):
for i in range(1, len(arr)):
# Starts looping from first unsorted element
unsorted = arr[i]
# Starts comparing against last sorted element
last_sorted_index = i-1
# While unsorted is less than the last sorted...
while last_sorted_index >= 0 and unsorted < arr[last_sorted_index]:
# Shifts last sorted to the right by one
arr[last_sorted_index + 1] = arr[last_sorted_index]
# Decrements down the last sorted index, until no longer larger than or hits zero
last_sorted_index -= 1
# Places unsorted element into correct spot
arr[last_sorted_index + 1] = unsorted
return arr
def timsort( arr ):
# Divide arr into runs of 32 (or as chosen)
# If arr size is smaller than run, it will just use insertion sort
minirun = 32
for i in range(0, len(arr), minirun):
counter = 0
range_start = minirun * counter
range_end = minirun * (counter+1)
print(range_start, range_end)
print(f"i is: {i}")
print(insertion_sort(arr[range_start:range_end]))
counter += 1
# Sort runs using insertion sort
# Merge arrays using merge sort
# return insertion_sort(arr)
test_sort = random.sample(range(100), 64)
print(timsort(test_sort)) |
5d16d2431314f3918a84614867e4e8fb00a7370b | iamreebika/Python-Assignment2 | /Examples/19.py | 1,537 | 4.34375 | 4 | """
19. Write a Python class to find validity of a string of parentheses, '(',
')', '{', '}', '[' and ']. These brackets must be close in the correct order,
for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid
"""
class ParenthesesValidation:
paragraph = ''
open_parentheses = tuple('[{(')
closed_parentheses = tuple(']})')
parentheses_map = dict(zip(open_parentheses, closed_parentheses))
def __init__(self, para=''):
self.paragraph = para
def check_if_valid(self):
"""
:return: returns the string valid or invalid
"""
stack = []
letters_list = list(self.paragraph)
for letter in letters_list:
if letter in self.open_parentheses:
stack.append(letter)
elif letter in self.closed_parentheses:
if len(stack) > 0:
open_pr = stack.pop()
if self.parentheses_map[open_pr] == letter:
pass
else:
return 'Parentheses are not valid!'
else:
stack.append(letter)
break
if len(stack) == 0:
return 'Parentheses are valid!'
else:
return 'Parentheses are not valid!'
# check_para = ParenthesesValidation('hello my name is {anja[{()}]l} bam()')
check_para = ParenthesesValidation()
check_para.paragraph = 'hello my name[] is {anja[{()}]l} bam()'
print(check_para.check_if_valid())
|
799d206f0c25d5a6f2e405582f54f48c2e024a29 | RizwanRumi/python_Learning | /try6_assert.py | 293 | 4.03125 | 4 | """
print(1)
assert 2 + 2 == 4
print(2)
assert 1 + 1 == 3
print(3)
"""
def KelvinToFahrenheit(Temp):
assert (Temp >= 0), "colder than absolute zero"
return ((Temp-273)*1.8)+32
print( KelvinToFahrenheit(273) )
print( int(KelvinToFahrenheit(505.78)) )
print( KelvinToFahrenheit(-5) )
|
6b2811985f6fe2537bf2a4dc134b8f411d888fe2 | claireyegian/unit1 | /nameAge.py | 336 | 3.890625 | 4 | #Claire Yegian
#8/31/17
#nameAge.py - characters in a name and age next year
name = input('Enter your first and last name: ')
name1, name2 = name.split()
print('Your first name has', len(name1), 'letters, and your last name has', len(name2), 'letters.')
age = int(input('Enter your age: '))
print('Next year you will be', age+1, 'years old')
|
03bda825834035b06a91c3d876bc06a2269c229c | jrantunes/URIs-Python-3 | /URIs/URI1072.py | 277 | 3.59375 | 4 | #Interval 2
in_interval = []
out_interval = []
for i in range(int(input())):
x = int(input())
if x in range(10, 21):
in_interval.append(x)
else:
out_interval.append(x)
print("{} in\n{} out".format(len(in_interval), len(out_interval)))
|
03c64189622b6ee5710b7c5b0e5532cb7a356591 | lama-imp/python_basics_coursera | /Week5_tasks/10_sumfact.py | 184 | 3.96875 | 4 | def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
n = int(input())
sum = 0
for i in range(1, n + 1):
sum += factorial(i)
print(sum)
|
b87b690823dd5501ff4418ae82c52f20d3d634d0 | Niloy28/Python-programming-exercises | /Solutions/Q11.py | 501 | 4 | 4 | # Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and
# then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
# Example:
# 0100,0011,1010,1001
# Then the output should be:
# 1010
string = input()
bin_list = string.split(',')
print_list = []
for num in bin_list:
if int(num, 2) % 5 == 0:
print_list.append(num)
print(','.join(print_list))
|
fc7f962d046c49ffceb31f3339249be47152a464 | maza2580/test | /hello.py | 85 | 3.5625 | 4 | #!/usr/bin/python3
import math
a = float(input("Lederlappen: "))
print(math.sqrt(a))
|
97b55981ca2941e887a8611d4b22f2dadc71e934 | anvartdinovtimurlinux/py-30 | /py_homework_basic/2_3_exceptions.py | 2,181 | 4.3125 | 4 | # Нужно реализовать Польскую нотацию для двух положительных чисел.
# Реализовать нужно будет следующие операции:
# 1) Сложение
# 2) Вычитание
# 3) Умножение
# 4) Деление
# Например, пользователь вводит: + 2 2 Ответ должен быть: 4
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
operations = {
'+': add,
'-': subtract,
'*': multiply,
'/': divide,
}
class NotPositiveIntegerError(Exception):
pass
while True:
print('\nПрограмма реализует польскую нотацию для целых положительных чисел')
print('В данный момент доступны сложение (+), вычитание (-), '
'умножение (*) и деление (/)')
print('Введите ваш пример, например "* 2 5"')
try:
operator, x, y = input().strip().split()
except ValueError:
print('Вы ввели некорректный пример')
continue
assert operator in operations, 'Используйте следующие операторы: + - * /'
try:
x, y = map(int, (x, y))
if x < 0 or y < 0 or x != round(x) or y != round(y):
raise NotPositiveIntegerError('Вы должны вводить положительные целые числа')
result = operations[operator](x, y)
except NotPositiveIntegerError as e:
print(e)
except ValueError:
print('Вторым и третьим аргументом должны быть целые положительные числа')
except ZeroDivisionError:
print('На ноль делить нельзя! Это ж не джаваскрипт какой-нибудь')
else:
result = result if (round(result) == result) else f'{result:.2f}'
print(f'Результатом {x} {operator} {y} будет {result}')
break
|
f56e9923dfba17788a0677dde1e03f9bc0170cb9 | navyifanr/LeetCode-Source | /LeetCode-Py/Array/[14]最长公共前缀.py | 1,053 | 3.671875 | 4 | # 编写一个函数来查找字符串数组中的最长公共前缀。
#
# 如果不存在公共前缀,返回空字符串 ""。
#
#
#
# 示例 1:
#
#
# 输入:strs = ["flower","flow","flight"]
# 输出:"fl"
#
#
# 示例 2:
#
#
# 输入:strs = ["dog","racecar","car"]
# 输出:""
# 解释:输入不存在公共前缀。
#
#
#
# 提示:
#
#
# 1 <= strs.length <= 200
# 0 <= strs[i].length <= 200
# strs[i] 仅由小写英文字母组成
#
# Related Topics 字符串 👍 1944 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
res = strs[0]
idx = 1
while idx < len(strs):
while strs[idx].find(res) != 0:
res = res[0:len(res) - 1]
idx += 1
return res
# leetcode submit region end(Prohibit modification and deletion)
|
7ecc1c16af906a9a41b8ac01a74f158a14ae80e0 | armut/thinkcs-solutions | /chapter-04/4-4.py | 252 | 3.8125 | 4 | # exercise 4.4
import turtle
def draw_poly(t, n, sz):
for i in range(n):
t.forward(sz)
t.left(360//n)
t.left(18)
wn = turtle.Screen()
turtl = turtle.Turtle()
for i in range(20):
draw_poly(turtl, 4, 75)
wn.mainloop()
|
3a79cd425c6081b78fdbd103fd147f7f3c151a6d | MrDeshaies/NOT-projecteuler.net | /euler_028.py | 1,424 | 3.765625 | 4 | # Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral
# is formed as follows:
#
# 21 22 23 24 25
# 20 7 8 9 10
# 19 6 1 2 11
# 18 5 4 3 12
# 17 16 15 14 13
#
# It can be verified that the sum of the numbers on the diagonals is 101.
#
# What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
# ben's notes: the two diagonals contain the numbers:
# top-left-to-bottom-right diagonal: (A) 1-3-7-13-21-31-43-57-73-...
# bottom-left-to-top-right diagonal: (B) 1-5-9-17-25-37-49-65-81-...
#
# For a 5x5 grid, you sum up A[0:5]+B[0:5]-1 (-1 because you counted the "1" at the centre twice)
#
# A) is pretty straightforward to generate: the difference grows by 2n:
# 3-1 = 2
# 7-3 = 4
# 13-7 = 6 etc.
GRID_SIZE = 1001
def generateNextA(previousVal, position):
return previousVal + 2*position
seriesA = [1]
for i in range(1,GRID_SIZE):
seriesA.append(generateNextA(seriesA[-1],i))
sumSeriesA = sum(seriesA)
# B) is a little more tricky. The increment between the terms is 4,4,8,8,12,12,16,16,...
# Repeats twice, then jumps by 4... So (n//2)*4
def generateNextB(previousVal, position):
return previousVal + 4*((position+1)//2)
seriesB = [1]
for i in range(1,GRID_SIZE):
seriesB.append(generateNextB(seriesB[-1],i))
sumSeriesB = sum(seriesB)
# and the answer for a is...
print(sumSeriesA+sumSeriesB-1) |
8bf98b8bd11962c739b4d82c65a2d0dbc0ecfb60 | StefanRvO/ProjectEuler | /Solved/problem51.py | 1,641 | 3.828125 | 4 | #/usr/bin/python
import sys
from itertools import combinations
def isprime(num):
if num<1:
return False
prime=0
for i in range(2,int(num**0.5)+1):
if num%i==0:
prime=1
break
if prime==0:
return True
else:
return False
def GetPrimeCount(numberList): #Return how many primenumbers the list contian
primes=0
for num in numberList:
if isprime(num):
primes+=1
return primes
def DoThisReplacement(number,places):
numlist=[]
strnumber=str(number)
numlen=len(strnumber)
for i in range(10):
for l in places:
strnumber=strnumber[:l]+str(i)+strnumber[l+1:]
numlist.append(int(strnumber))
strnumber=str(number)
for i in range(len(numlist)):
if not (len(str(numlist[i]))==numlen):
numlist.remove(numlist[i])
break
return list(set(numlist))
def GenerateReplacements(number):
global maxprimes
global BestCase
numlenght=len(str(number))
replacelist=range(numlenght)
for i in range(1,numlenght):
Replacements=combinations(replacelist,i)
for case in Replacements:
group=DoThisReplacement(number,case)
primesInGroup=GetPrimeCount(group)
if primesInGroup>maxprimes:
print "New Record",number,"with",primesInGroup,"primes in group", sorted(group)
maxprimes=primesInGroup
BestCase=number
global BestCase
BestCase=0
global maxprimes
maxprimes=0
for i in range(1,10000000,2):
if isprime(i):
GenerateReplacements(i)
|
428834812b707058cab25b0e252703754a25979c | sheikh210/LearnPython | /functions/star_examples.py | 922 | 4.96875 | 5 | numbers = (1, 2, 3, 4, 5)
# Using * unpacks the sequence (tuple in this example)
# The first print statement won't print any separators, as it is only 1 value
# This ensures that Python is, in fact, unpacking our sequence type, then printing it as separate values
print(numbers, sep=";")
print(*numbers, sep=";")
print(1, 2, 3, 4, 5, sep=";")
print('\n' + "-" * 25 + '\n')
# We can also use * the other way around - pass in 'n' number of arguments to a function
# In this example, *args will unpack all the arguments passed into the function
# Printing 'args' will give us the tuple, while iterating over args, prints each argument individually
def test_star(*args):
print(args)
for x in args:
print(x)
test_star(1, 2, 3, 4, 5)
# We can also pass no arguments to our function, as seen below - The output produces an empty tuple
# More importantly, our function didn't crash
print()
test_star()
|
792145573e43f93b292693392934792c7093ab0f | jonnor/datascience-master | /inf250/assignment3/bd_backend.py | 3,840 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Backend for the blob detection coursework for INF250 at NMBU.
"""
__author__ = "Yngve Mardal Moe"
__email__ = "yngve.m.moe@gmail.com"
import numpy as np
from threshold import threshold, histogram
import sys
def _remove_and_relabel_blobs(labeled, wanted_blobs):
"""This function removes unwanted blobs.
"""
labeled = labeled.copy()
wanted_blobs = np.array(wanted_blobs)
no_blobs = len(wanted_blobs)
unwanted_blobs = np.arange(1, no_blobs+1)[np.logical_not(wanted_blobs)]
wanted_blobs = np.arange(1, no_blobs+1)[wanted_blobs]
for unwanted_blob in unwanted_blobs:
labeled[labeled == unwanted_blob] = 0
for new_label, wanted_blob in enumerate(wanted_blobs):
new_label += 1
labeled[labeled == wanted_blob] = -new_label
return -labeled
def region_labeling(image, th=None, black_blobs=True, set_recursion_limit=True,
recursion_limit=10000):
"""Uses flood fill labeling to detect and label blobs in an image.
The flood-fill algorithm is one of the simplest blob-detection
algorithms that exists. As part of this algorithm, the image needs
to be binarised. This is done using global thresholding at given threshold
value, or, if no threshold value is given, Otsu's method is used to find
the optimal value. the output of this algorithm is a new image, of same
size as the input image, however it is thresholded and each blob
has its own gray-value. The BLOBs are assumed to be black on white
background after binarisation, if this is not the case set `black_blobs`
to False.
Parameters:
-----------
image : np.ndarray
Image to detect blobs in. If this image is a colour image then
the last dimension will be the colour value (as RGB values).
th : numeric
Threshold value for binarisation step. Uses Otsu's method if
this variable is None.
black_blobs : Bool
Whether the blobs should be black or white
set_recursion_limit : Bool
Whether or not the system recursion limit should be updated (reset after function)
recursion_limit : int
Recursion limit to use for this function.
Returns:
--------
labeled : np.ndarray(np.uint)
Image where the background is completely black and the blobs each have
their own grayscale value (starting at 1 and increasing linearly)
"""
# Setup
shape = np.shape(image)
old_recursion_limit = sys.getrecursionlimit()
if set_recursion_limit:
sys.setrecursionlimit(recursion_limit)
if len(shape) == 3:
image = image.mean(axis=2)
elif len(shape) > 3:
raise ValueError('Must be at 2D image')
# Threshold image
labeled = threshold(image, th=th).astype(int)
labeled = 255-labeled if black_blobs else labeled
labeled[labeled == 255] = -1
# Label blobs
blobs = 0
for i in range(shape[0]):
for j in range(shape[1]):
if labeled[i, j] == -1:
blobs += 1
flood_fill(labeled, y=i, x=j, colour=blobs)
# Cleanup
sys.setrecursionlimit(old_recursion_limit)
return labeled
def flood_fill(image, y, x, colour):
"""Performs depth-first-search flood fill on the image at given location.
"""
curr_colour = image[y, x]
image[y, x] = colour
if y > 0:
if image[y-1, x] == curr_colour:
flood_fill(image, y=y-1, x=x, colour=colour)
if x > 0:
if image[y, x-1] == curr_colour:
flood_fill(image, y=y, x=x-1, colour=colour)
if y+1 < image.shape[0]:
if image[y+1, x] == curr_colour:
flood_fill(image, y=y+1, x=x, colour=colour)
if x+1 < image.shape[1]:
if image[y, x+1] == curr_colour:
flood_fill(image, y=y, x=x+1, colour=colour)
|
1420b400e45bf4fe105d1410dc2c5636e29e7f8e | phillui-37/FP | /compose.py | 1,905 | 3.671875 | 4 | from functools import reduce
from typing import Callable, Union
class compose:
"""
Compose functions into a pipeline, which the result will pass over functions
Function invocation order: left->right(default)
Examples:
.. code-block:: python
# order is filter->map
compose(partial(map, lambda x,y,z: x+y+z)) | partial(filter, lambda x: x & 1 == 0)
# order is map->filter
partial(filter, lambda x: x & 1 == 0) | compose(partial(map, lambda x,y,z: x+y+z))
# order is map->filter
compose(partial(map, lambda x,y,z: x+y+z), from_left=False) | partial(filter, lambda x: x & 1 == 0)
"""
__slots__ = ('__from_left', '__f_list')
def __init__(self, *fs: Callable, from_left: bool=False):
self.__from_left = from_left
self.__f_list = list(fs)
def __call__(self, *args, **kwargs):
"""
[f1...fn]
from_left -> FIFO(pipe) -> fn(...f2(f1(x)))
from_right -> FILO(compose) -> f1(...fn(x))
so for compose, fn list will be reversed before invoking
"""
fs = self.__f_list if self.__from_left else list(reversed(self.__f_list))
return reduce(lambda result, f: f(result), fs[1:], fs[0](*args, **kwargs))
def __or__(self, other: Union[Callable, 'compose']):
# other must be callable, you know that
if isinstance(other, compose):
self.__f_list = [*self.__f_list, *other.get_fn_list]
else:
self.__f_list = [*self.__f_list, other]
return self
def __ror__(self, other: Union[Callable, 'compose']):
if isinstance(other, compose):
self.__f_list = [*other.get_fn_list, *self.__f_list]
else:
self.__f_list = [other, *self.__f_list]
return self
@property
def get_fn_list(self):
return self.__f_list.copy()
|
9d57e5e5138d777802b5bf598628a5e56b52239b | cseibm/19113016_ShreyaKishore | /print a range from a starting number.py | 128 | 4.15625 | 4 | a=int(input("enter the starting number:"))
n=int(input("Enter nth Number: "))
for i in range(a, n+1):
print (i, end = " ")
|
9dc27a1193dd4aaaed7517e5da680342459e26f9 | fdfzjxxxStudent/CS001 | /CS001-lesson3/relation.py | 102 | 3.5625 | 4 | print(5 > 3)
print('5' < '3')
print(5 >= 3)
print('A' <= 'a')
print(3 == 3.0)
print('A' != 'a')
|
5bb9f5fbeee4b12f3601c61317387e13f62a0e90 | Ahmet-Kirmizi/Fibbonaci-sequence | /fibonacci.py | 695 | 4.40625 | 4 | # lets create a input variable that ask for the sequence
nth_term = int(input('please enter the number of sequences you want to see: '))
# count variable that will be used to break the while loop
count = 0
# everytime the loop starts over it will update count
# it will have 2 numbers
number1, number2 = 0, 1
if nth_term <= 0:
print('Please enter a positive integer!')
elif nth_term == 1:
print('this is your sequence',nth_term,':')
print(number1)
else:
print('The Fibbonaci sequence:')
while count < nth_term:
print(number1)
nth = number1 + number2
number1 = number2
number2 = nth
count = count + 1
|
acd71875a340eef6303f23ef4d386049155b9e4c | leni1/python-fizzbuzz | /fizzbuzz.py | 379 | 3.625 | 4 | def fizzbuzz(a, b):
if isinstance(a, list) and isinstance(b, list):
len_sum = len(a) + len(b)
if len_sum % 3 == 0 and len_sum % 5 == 0:
return 'fizzbuzz'
if len_sum % 3 == 0:
return 'fizz'
if len_sum % 5 == 0:
return 'buzz'
else:
return len_sum
else:
return 'Invalid input'
|
ac1225f1825495ae659c0fec5b9149517d32f0ca | aditya-doshatti/Leetcode | /consecutive_characters_1446.py | 775 | 3.8125 | 4 | '''
1446. Consecutive Characters
Easy
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
https://leetcode.com/problems/consecutive-characters/
'''
class Solution:
def maxPower(self, s: str) -> int:
if len(s) <= 1:
return len(s)
curr, retVal = 1, 0
prev = s[0]
for i in range(1, len(s)):
if s[i] == prev:
curr += 1
else:
prev = s[i]
retVal = max(curr, retVal)
curr = 1
return max(retVal, curr)
|
e9c180bbf754bc3cce0081988dc4289410a25f11 | mariojerez/Space-Impact | /Space Impact final.py | 16,594 | 3.703125 | 4 | ## Mario Jerez
## Mini Project
## Space Impact
import os
os.chdir("/Users/mariojerez/Documents/Computer Science/MarioMiniProject")
from graphics import *
import math, time, random
##Button code borrowed from class
class Button:
# constructor
def __init__(self, win, graphicsObject, color, label):
graphicsObject.setFill(color)
graphicsObject.draw(win)
centerPoint = graphicsObject.getCenter()
text = Text(centerPoint, label)
text.draw(win)
# information Button objects need to remember:
self.graphicsObject = graphicsObject
self.color = color
self.label = label
def __str__(self):
s = "{:s} Button".format(self.label)
return s
def press(self):
self.graphicsObject.setFill("gray")
time.sleep(0.2)
self.graphicsObject.setFill(self.color)
#---------------------------------------------------------------------
# RoundButton inherits from Button
class RoundButton(Button):
def __init__(self, win, centerX, centerY, diameter, color, label):
radius = diameter/2
circle = Circle(Point(centerX, centerY), radius)
Button.__init__(self, win, circle, color, label)
# information RoundButton objects need to remember:
self.x = centerX
self.y = centerY
self.radius = radius
def contains(self, point):
pointX = point.getX()
pointY = point.getY()
distance = math.sqrt((pointX - self.x)**2 + (pointY - self.y)**2)
if distance <= self.radius:
return True
else:
return False
#---------------------------------------------------------------------
# SquareButton inherits from Button
class SquareButton(Button):
def __init__(self, win, centerX, centerY, size, color, label):
leftX = centerX - size/2
rightX = centerX + size/2
topY = centerY - size/2
bottomY = centerY + size/2
rect = Rectangle(Point(leftX, bottomY), Point(rightX, topY))
Button.__init__(self, win, rect, color, label)
# information SquareButton objects need to remember:
self.x1 = leftX
self.x2 = rightX
self.y1 = topY
self.y2 = bottomY
def contains(self, point):
pointX = point.getX()
pointY = point.getY()
if (pointX >= self.x1 and pointX <= self.x2 and
pointY >= self.y1 and pointY <= self.y2):
return True
else:
return False
#---------------------------------------------------------------------
# ButtonPanel extends GraphWin, so all GraphWin methods, including
# setBackground, getMouse, close, etc. are inherited by ButtonPanel
class ButtonPanel(GraphWin):
def __init__(self, title, width, height):
GraphWin.__init__(self, title, width, height)
self.allButtons = []
self.buttonFunctions = {}
def addButton(self, button, callbackFunction):
self.allButtons.append(button)
self.buttonFunctions[button] = callbackFunction
def processEvent(self, point):
for button in self.allButtons:
if button.contains(point) == True:
callbackFunction = self.buttonFunctions[button]
callbackFunction()
return True
return False
#---------------------------------------------------------------------
# main program
def main():
panel = ButtonPanel("Space Impact", 300, 300)
panel.setBackground("dark gray")
# create the buttons
b1 = RoundButton(panel, 100, 100, 50, "green", "Play Now")
b2 = RoundButton(panel, 200, 100, 50, "red", "Scores")
b3 = SquareButton(panel, 220, 180, 55, "orange", "quit")
# create the callback functions
def HighScores():
f = open('scores.txt')
allLines = f.readlines()
f.close()
scores = []
addSpace = 0
for line in allLines:
scores.append(line)
for score in scores:
message = Text(Point(150,200 + addSpace), score)
message.setTextColor('white')
message.setSize(10)
message.draw(panel)
addSpace = addSpace + 10
def playGame():
game = SpaceImpact()
game.play()
def close():
panel.close()
# add the buttons to the panel
panel.addButton(b1, playGame)
panel.addButton(b2, HighScores)
panel.addButton(b3, close)
# event loop
while panel.isClosed() == False:
p = panel.getMouse()
buttonPressed = panel.processEvent(p)
if buttonPressed == False:
message.setText("Click a button")
#-----------------------------------------------------------------
class Heart(Polygon):
def __init__(self, win, center, size):
x = center.getX()
y = center.getY()
self.win = win
unit = size #unit is the number of pixels in a unit
p1 = Point(x, y-unit/2)
p2 = Point(x + unit, y - unit*1.5)
p3 = Point(x + unit*2, y - unit/2)
p4 = Point(x + unit, y + unit/2)
p5 = Point(x, y + unit*1.5)
p6 = Point(x - unit, y + unit/2)
p7 = Point(x - unit*2, y - unit/2)
p8 = Point(x - unit, y - unit*1.5)
Polygon.__init__(self, p1, p2, p3, p4, p5, p6, p7, p8)
self.setFill('red')
self.draw(self.win)
self.alive = True
def die(self):
self.setFill('dim gray')
self.alive = False
def revive(self):
self.setFill('red')
self.alive = False
#-------------------------------------------------------------------------
class Spaceship(Rectangle):
def __init__(self, win, RGB, centerPoint, width, height, shootRate, movePixels, lives):
p1 = Point(centerPoint.getX() - width / 2, centerPoint.getY() + height / 2)
p2 = Point(centerPoint.getX() + width / 2, centerPoint.getY() - height / 2)
Rectangle.__init__(self, p1, p2)
self.RGB = RGB
self.r, self.g, self.b = self.RGB[0], self.RGB[1], self.RGB[2]
self.setFill(color_rgb(self.r, self.g, self.b))
self.setOutline(color_rgb(self.r, self.g, self.b))
self.draw(win)
self.win = win
self.center = centerPoint
self.width = width
self.height = height
self.shootRate = shootRate
self.health = lives
self.movePixels = movePixels
def leftEdge(self):
p1 = self.getP1()
leftBound = p1.getX()
return leftBound
def rightEdge(self):
p2 = self.getP2()
rightBound = p2.getX()
return rightBound
def topEdge(self):
p2 = self.getP2()
topBound = p2.getY()
return topBound
def bottomEdge(self):
p1 = self.getP1()
bottomEdge = p1.getY()
return bottomEdge
def isDestroyed(self):
destroyed = False
if self.health == 0:
destroyed = True
return destroyed
def hurt(self):
self.setFill('gray')
self.health = self.health - 1
## lighten color to suggest weakened structure
self.RGB = lighten(self.RGB)
self.r, self.g, self.b = self.RGB[0], self.RGB[1], self.RGB[2]
self.setFill(color_rgb(self.r, self.g, self.b))
self.setOutline(color_rgb(self.r, self.g, self.b))
def reachedAtmosphere(self):
p1 = self.getP1()
x = p1.getX()
if x <= 0:
return True
else:
return False
def shoot(self):
misile = Rocket(self.win, Point(self.leftEdge(), self.topEdge() + self.height / 2),self.height / 5, 'orange', 'left', random.uniform(-4,4))
return misile
#--------------------------------------------------------------------------
# Used to lighten the color of the ships when they are hit
def lighten(RGB):
for i in range(len(RGB)):
newIntensity = RGB[i] + 30
if newIntensity > 255:
newIntensity = 255
RGB[i] = newIntensity
return RGB
#-------------------------------------------------------------------------
class Rocket(Circle):
def __init__(self, win, center, radius, color, dxDirection, dy):
Circle.__init__(self, center, radius)
xDirection = 1
if dxDirection == 'left':
xDirection = -1
elif dxDirection == 'right':
pass
dxSlow = 45 * xDirection
dxFast = 50 * xDirection
dxSuper = 55 * xDirection
dxSuperSlow = 5 * xDirection
colorToSpeed = {'red': dxSlow, 'blue': dxFast, 'purple': dxSuper, 'orange': dxSuperSlow}
self.xDirection = dxDirection
self.radius = radius
self.setFill(color)
self.setOutline(color)
self.draw(win)
self.win = win
if color in colorToSpeed:
self.dx = colorToSpeed[color]
else:
self.dx = dxSlow
self.dy = dy
def leftEdge(self):
xCoord = self.getCenter().getX()
leftBound = xCoord - self.radius
return leftBound
def rightEdge(self):
xCoord = self.getCenter().getX()
rightBound = xCoord + self.radius
return rightBound
def topEdge(self):
yCoord = self.getCenter().getY()
topBound = yCoord - self.radius
return topBound
def bottomEdge(self):
yCoord = self.getCenter().getY()
bottomBound = yCoord + self.radius
return bottomBound
def move(self):
if self.topEdge() <= 0 or self.bottomEdge() >= self.win.getHeight():
self.dy = self.dy * -1
Circle.move(self, self.dx, self.dy)
def checkContact(self, ships, invaders, misiles):
contact = False
fatal = False
if len(ships) == 0:
pass
else:
for ship in ships:
fatal = False
x1 = ship.getP1().getX() # left edge of ship
y1 = ship.getP1().getY() # bottom edge of ship
x2 = ship.getP2().getX() # right edge of ship
y2 = ship.getP2().getY() # top edge of ship
contact = False
if (self.rightEdge() >= x1 and self.leftEdge() <= x2
and self.topEdge() <= y1 and self.bottomEdge() >= y2):
contact = True
self.undraw()
misiles.remove(self)
ship.hurt()
if ship.isDestroyed() == True:
fatal = True
ship.undraw()
ships.remove(ship)
if ship in invaders:
invaders.remove(ship)
return contact, misiles, ships, invaders, fatal
#--------------------------------------------------------------
class SpaceImpact(GraphWin):
def __init__(self):
GraphWin.__init__(self, "Space Impact", 800, 500)
self.width = 800
self.height = 500
spacePic = Image(Point(400,250), 'space.gif')
spacePic.draw(self)
self.ship = Spaceship(self,[0,0,255],Point(100,250),50,20,8,20,5)
##draw hearts
numHeartsDrawn = 0
self.hearts = []
self.deadHearts = []
for _ in range(self.ship.health):
size = 5
heart = Heart(self, Point(self.width - 4*size - 25*numHeartsDrawn, size*4), size)
self.hearts.append(heart)
numHeartsDrawn = numHeartsDrawn + 1
self.aliveHearts = self.hearts
self.invaders = []
self.misiles = []
self.kills = 0
self.myBullet = 'red'
self.invaderRate = 50
def highScores(self):
f = open('scores.txt')
allLines = f.readlines()
f.close()
scores = []
addSpace = 0
for line in allLines:
scores.append(line)
for score in scores:
message = Text(Point(400,250 + addSpace), score)
message.setTextColor('white')
message.setSize(20)
message.draw(self)
addSpace = addSpace + 50
def play(self):
prompt = Text(Point(400,400), "Click the mouse to begin. The fate of humanity is in your hands.")
prompt.setSize(20)
prompt.setTextColor('white')
prompt.draw(self)
self.getMouse() # wait for a mouse click to begin
prompt.undraw()
timeStep = 0
ships = [self.ship]
while self.gameOver() == False:
if len(self.aliveHearts) < self.ship.health:
heart = self.deadHearts[0]
heart.revive()
self.deadHearts.remove(heart)
self.aliveHearts.append(heart)
if len(self.aliveHearts) > self.ship.health:
heart = self.aliveHearts[0]
heart.die()
self.aliveHearts.remove(heart)
self.deadHearts.append(heart)
key = self.checkKey()
if key == 'Up' and key == 'Right':
self.ship.move(self.ship.movePixels * -1, self.ship.movePixels)
elif key == 'Down' and key == 'Right':
self.ship.move(self.ship.movePixels, self.ship.movePixels)
elif key == 'Up' and key == 'Left':
self.ship.move(self.ship.movePixels * -1, self.ship.movePixels * -1)
elif key == 'Down' and key == 'Left':
self.ship.move(self.ship.movePixels, self.ship.movePixels * -1)
elif key == 'Up':
self.ship.move(0, self.ship.movePixels * -1)
elif key == 'Down':
self.ship.move(0, self.ship.movePixels)
elif key == 'Left':
self.ship.move(self.ship.movePixels * -1, 0)
elif key == 'Right':
self.ship.move(self.ship.movePixels, 0)
elif key == 'space':
misile = Rocket(self, Point(self.ship.rightEdge(), self.ship.topEdge() + self.ship.height / 2),self.ship.height / 5, self.myBullet, 'right', 0)
self.misiles.append(misile)
for misile in self.misiles:
if misile.xDirection == 'right' and misile.leftEdge() <= self.getWidth():
misile.move()
elif misile.xDirection == 'left' and misile.rightEdge() >= 0:
misile.move()
else:
misile.undraw()
self.misiles.remove(misile)
contact, self.misiles, ships, self.invaders, fatal = misile.checkContact(ships, self.invaders, self.misiles)
if contact == True:
if fatal == True:
self.kills = self.kills + 1
if self.kills < 5:
shootRate = random.randrange(100,140) #make shootrate a ship object
lives = 5
elif self.kills < 10:
shootRate = random.randrange(80,100)
lives = 7
self.myBullet = 'blue'
else:
shootRate = random.randrange(70,90)
lives = 10
self.myBullet = 'purple'
if timeStep % 100 == 0:
invader = Spaceship(self, [0,200,0], Point(self.getWidth(), random.randrange(5,self.getHeight() - 5)), 50, 20, shootRate, random.randrange(2,4), lives)
self.invaders.append(invader)
ships.append(invader)
for invader in self.invaders:
invader.move(-invader.movePixels, 0)
if timeStep % 80 == 0:
self.misiles.append(invader.shoot())
if timeStep % 1000 == 0:
for invader in self.invaders:
invader.movePixels = invader.movePixels + random.uniform(1,2)
self.invaderRate = self.invaderRate - 2
timeStep = timeStep + 1
time.sleep(0.01)
self.aliveHearts[0].die()
message = Text(Point(400, 100), 'GAME OVER! ALIENS INVADED EARTH!\nKills: {:d}\n Click anywhere to continue'.format(self.kills))
message.setSize(25)
message.setTextColor('white')
message.draw(self)
self.highScores()
self.getMouse()
self.close()
def gameOver(self):
gameIsOver = False
for invader in self.invaders:
if invader.reachedAtmosphere() or self.ship.isDestroyed():
gameIsOver = True
return gameIsOver
|
c7b91c51f3a9ef49798c53e321c86df3a93d1ddf | dpmanoj/Kaio-machine-learning-human-face-detection | /server/predicting.py | 4,856 | 3.625 | 4 | #############################################################
# Predict methods supporting to test accuracy and perfomance
#############################################################
# Import
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import learning_curve
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
# Generate a simple plot of the test and training learning curve.
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
"""
Generate a simple plot of the test and training learning curve.
Parameters
----------
estimator : object type that implements the "fit" and "predict" methods
An object of that type which is cloned for each validation.
title : string
Title for the chart.
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape (n_samples) or (n_samples, n_features), optional
Target relative to X for classification or regression;
None for unsupervised learning.
ylim : tuple, shape (ymin, ymax), optional
Defines minimum and maximum yvalues plotted.
cv : int, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is used.
Refer :ref:`User Guide <cross_validation>` for the various
cross-validators that can be used here.
n_jobs : integer, optional
Number of jobs to run in parallel (default 1).
"""
plt.figure()
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Training examples")
plt.ylabel("Score")
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.grid()
plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1,
color="r")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
plt.legend(loc="best")
return plt
### Get the accuracy score for input truth and predictions.s
def accuracy_score(nome, modelo, X_train, y_train):
k = 10
# Ensure that the number of predictions matches number of outcomes using k-fold
scores = cross_val_score(modelo, X_train, y_train, cv = k)
# Calculate and return the accuracy as a percent
taxa_de_acerto = np.mean(scores) * 100
msg = "Taxa de acerto do {0}: {1:.2f}%".format(nome, round(taxa_de_acerto, 2))
print msg
return taxa_de_acerto
### Get the perfomance score for one algorithm.
def performance_metric(resultados, X_train, X_test, y_train, y_test):
# A eficacia do algoritmo que chuta, tudo em um unico valor
acerto_base = max(Counter(y_test).itervalues())
taxa_de_acerto_base = 100.0 * acerto_base / len(y_test)
print("Taxa de acerto base: {0:.2f}%".format(round(taxa_de_acerto_base, 2)))
vencedor = resultados[max(resultados)]
print "\nVencedor:"
print vencedor
real_world(vencedor, X_train, X_test, y_train, y_test)
total = len(y_train) + len(y_test)
print("Total de elementos : {}".format(total))
return vencedor
def real_world(clf, X_train, X_test, y_train, y_test):
clf.fit(X_train, y_train)
resultado = clf.predict(X_test)
total_de_elementos = len(y_test)
acertos = (resultado == y_test)
total_de_acertos = sum(acertos)
taxa_de_acerto = 100.0 * total_de_acertos / total_de_elementos
print("\nTaxa de acerto do algoritmo vencedor entre os algoritmos no mundo real : {0:.2f}% ".format(round(taxa_de_acerto, 2)))
|
67a6ade34169bbe8226562b49ed975b10869afea | pheninmay/practice | /challenge7/challenge7_4.py | 867 | 3.78125 | 4 | # 無限ループする数字当てプログラムを書こう。ユーザーに文字を入力してもらい
# qが入力されたら終了、数字が入力されたら正解がどうか判定しよう。正解の数値は
# プログラム内にいくつかリストで持たせておいて、ユーザーが入力した数字がそのどれかと
# 一致したら「正解」、一致しなかったら「不正解」と表示しよう。もし数字かq以外の文字が
# 入力されたら、「数字を入力するか、qで終了します」と表示しよう。
ans = ["1","5","7"]
while True:
f = input("数字を入力するか、qで終了します")
if f == "q":
break
elif f in ans:
print("正解")
else:
try:
int(f)
print("不正解")
except ValueError:
continue |
1824b0ef9897f7602e41827c17e2c2b6aa0c1ac3 | aabramson/python | /Alunos com média e aprovação.py | 2,535 | 4.03125 | 4 | # Cadastro de alunos com notas e médias
print ()
print ('Bem vindo ao sistema de cadastro da escola Raimundão. CHAMA!!!')
print ()
alunos = []
notas_p1 = []
notas_p2 = []
notas_p3 = []
notas_p4 = []
while 1:
aluno = input ('Por favor, insira o nome do aluno, ou aperte ENTER para terminar a operação: ')
if not aluno:break
alunos.append(aluno)
quantidade = len(alunos)
i=0
while i < quantidade:
try:
p1 = float(input('Insira a nota P1 do aluno %s: ' % alunos[i]))
while p1 >= 0 and p1 <= 10:
notas_p1.append(p1)
print('Nota do aluno %s inserida com sucesso!' % alunos[i])
break
else:
print('A nota deve ser entre 0 e 10. Por favor, corrija o erro!')
continue
p2 = float(input('Insira a nota P2 do aluno %s: ' % alunos[i]))
while p2 >= 0 and p2 <= 10:
notas_p2.append(p2)
print('Nota do aluno %s inserida com sucesso!' % alunos[i])
break
else:
print('A nota deve ser entre 0 e 10. Por favor, corrija o erro!')
continue
p3 = float(input('Insira a nota P3 do aluno %s: ' % alunos[i]))
while p3 >= 0 and p3 <= 10:
notas_p3.append(p3)
print('Nota do aluno %s inserida com sucesso!' % alunos[i])
break
else:
print('A nota deve ser entre 0 e 10. Por favor, corrija o erro!')
continue
p4 = float(input('Insira a nota P4 do aluno %s: ' % alunos[i]))
while p4 >= 0 and p4 <= 10:
notas_p4.append(p4)
print('Nota do aluno %s inserida com sucesso!' % alunos[i])
break
else:
print('A nota deve ser entre 0 e 10. Por favor, corrija o erro!')
continue
i+=1
except:
print ('Por favor, digite um valor numérico válido!')
while 1:
try:
media = float (input ('Insira a nota média para aprovação: '))
break
except:
print ('Por favor, digite um valor numérico adequado.')
print ()
print ('Calculando médias dos alunos, com resultado de aprovação ou reprovação...')
print ()
i = 0
while i < quantidade:
final = (notas_p1 [i] + notas_p2 [i] + notas_p3 [i] + notas_p4 [i]) / 4
if final >= media:
print ('Aluno %10s APROVADO, com média %.2f' % (alunos [i], final))
else:
print ('Aluno %10s REPROVADO, com média %.2f. SE FODEU!!!' % (alunos [i], final))
i+=1
print ('-'*50)
print ('Tenha um bom dia!') |
a41cdb0113b5a984a0f3e26f62699d8f697e15fd | Isoxazole/Python_Class | /HW1/hm1_william_morris.py | 4,549 | 4.375 | 4 | """Homework1
William Morris
1/29/2019
This is a 'security program' that will loop through a series of questions until the user answers all the questions
successfully. If the user fails to answer a question correctly, the program will restart. After answering all the
questions successfully, the secret message will be displayed!"""
import random
hasNotSucceeded = True
stagesComplete = 0
print("Hello, welcome to the new Security2000 system. This system is designed to protect a \nsecret message with the"
"utmost protection. The secret message will be displayed only \nafter answer each "
"and every question successfully. Good luck!\n")
print("Please enter your name: ")
userName = input()
print("\nHello %s, you seem to be new in our system, we'll go ahead \nand ask you a few question to make "
"sure you have access to the secret message.\n" % userName)
# returns a random number between 1 and 9
def randomInt():
return random.randint(1, 9)
# loops until
while hasNotSucceeded:
word = "supercalifragilisticexpialidocious"
print("Question 1: How many letters does the word '%s' have in it?\n" % word)
# get user input for how many letters and store as int
userGuess = int(input())
# Block 1 start / check if user guess is correct
if userGuess == len(word):
print("Correct!")
stagesComplete = 1
elif userGuess == 0:
print("Are you even trying?")
else:
print("Incorrect! Try again...\n")
# continue used to go to beginning of while loop
continue
# Block 1 ends
print("Question 2: What are the first 10-digits of pi?")
pi = 3.14159265359
userGuess = float(input())
# Block 2 start / ask user about guessing digits of pi
if userGuess == pi:
print("Correct!")
stagesComplete = 2
elif userGuess == 0:
print("Are you even trying?")
else:
print("Incorrect! Try again...\n")
continue
# Block 2 ends
# generate random integers for below for loop
x = randomInt()
y = randomInt()
z = randomInt()
print("Question 3: Challenge Mode!\n")
loopCounter = 0
# Block 3 start / prints three questions in sequence for user to answer
for i in range(3):
if i == 0:
print("What is %d+%d-%d?" % (x, y, z))
userGuess = int(input())
if userGuess == (x + y - z):
print("Correct!")
loopCounter += 1
else:
print("Incorrect! Try again...")
break
elif i == 1:
print("\nWhat is %d*%d//%d?" % (x, y, z))
print("Hint: This uses integer division")
userGuess = int(input())
if userGuess == (x * y // z):
print("Correct!")
loopCounter += 1
else:
print("Incorrect! Try again...")
break
elif i == 2:
print("What is %d+%d+%d?" % (x, y, z))
userGuess = int(input())
if userGuess == (x + y + z):
print("Correct!")
loopCounter += 1
print(loopCounter)
else:
print("Incorrect! Try again...")
break
# Block 3 ends
print(loopCounter)
# check if user was able to answer all questions in for loop correctly
if loopCounter != 3:
continue
else:
stagesComplete = 3
# check if user has completed the past 3 stages
if stagesComplete == 3:
print("\nCongratulations %s, you have answered all the questions correctly, "
"the secret message is. . .\n" % userName)
print("Before giving you the secret message, please enter any comments or suggestions \nat this time "
"about the new Security 2000 system:")
userSuggest = ""
userSuggest += str(input())
if userSuggest:
print("The message you have entered is:\n %s" % userSuggest)
print("\nNow, what you've been waiting for this whole time, the secret message is:")
print("THE END IS NEAR!")
print("\nThank you and please come again!")
hasNotSucceeded = False
# if user does not enter any text for suggestions, program restart (because no comments isn't very nice, right?
else:
print("Warning! Warning! ***User has not offered any comments or suggestions, "
"program will now restart!***\n")
continue
|
5d1e38c30ff8ea0dd885e93db5e982f1839488f7 | green-fox-academy/balazsbarni | /week04/11-sharpie-set.py | 696 | 3.796875 | 4 | #### Sharpie Set
#- Reuse your `Sharpie` class
#- Create `SharpieSet` class
# - it contains a list of Sharpie
# - count_usable() -> sharpie is usable if it has ink in it
# - remove_trash() -> removes all unusable sharpies
class Sharpie(object):
def __init__(self, color, width, ink):
self.color = color
self.width = width
self.ink = ink
def use(self):
self.ink_amount -=1
def __repr__(self):
return '[{}, {}, {}]'.format(self.color, self.width, self.ink)
class SharpieSet(object):
def __init__(self):
self.sharpie = [Sharpie("red", 0.25, 5), Sharpie("blue", 0.5, 3)]
sharpieset = SharpieSet()
print(sharpieset.sharpie) |
b224bdd749e6827209502c081609a1c9d018322c | rajput-shivam/BSC-CS-Sem4-FundamentalOfAlgoPracticals | /MergeSortAlgorithm.py | 932 | 4.0625 | 4 | def mergeSort(a):
if len(a)>1:
mid = len(a)//2
left= a[:mid]
right= a[mid:]
print("before left and right: ",left,right)
mergeSort(left)
mergeSort(right)
print("after left and right: ",left,right)
i=j=k=0
print("\nbefore a:",a)
while i<len(left) and j<len(right):
if left[i] < right[j]:
a[k] = left[i]
i=i+1
else:
a[k] = right[j]
j=j+1
k=k+1
print("after 1st loop a:",a)
while i<len(left):
a[k]=left[i]
i=i+1
k=k+1
print("after 2nd loop a:",a)
while j<len(right):
a[k]=right[j]
j=j+1
k=k+1
print("after last loop a:",a,"\n")
a = [534,246,933,933,127,277,321,454,565,2201]
mergeSort(a)
print("\n\n\nANSWER",a)
|
2ea945fc304127793364d9b2fb05c6ad03f8f250 | Ressull250/code_practice | /part4/268.py | 252 | 3.578125 | 4 | class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
summ = sum(nums)
return n*(n+1)/2 - summ
print Solution().missingNumber([0,1,3]) |
08848d4a5dc8bed2ba25214cd700e114eecdfc3b | willykurmann/PythonScriptingCourse | /PythonAutomation/classes.py | 322 | 3.53125 | 4 | class A:
d = 100
def __init__(self):
print("This is constructor")
def display(self):
print("This is display method")
def sum(self,a,b):
print(a+b)
def classvar(self):
print("this is class variable d: {}".format(A.d))
a = A()
a.display()
a.sum(1,2)
a.classvar()
|
498914bf0789e4a8d8b48876e99757ca2ffd6ee5 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2346/60635/242681.py | 1,080 | 3.71875 | 4 | count = int(input())
def add_to_list (matrix, ans):
if len(matrix) == 0:
return
elif len(matrix) == 1:
for m in matrix[0]:
ans.append(m)
return
elif len(matrix) <= 2:
for m in matrix[0]:
ans.append(m)
for i in range(len(matrix[0])-1,-1,-1):
ans.append(matrix[1][i])
return
row, col = 0,len(matrix[0])-1
for i in range(col+1):
ans.append(matrix[0][i])
while row < len(matrix)-1:
row += 1
ans.append(matrix[row][col])
for i in range(col-1,-1,-1):
ans.append(matrix[row][i])
for i in range(row-1,0,-1):
ans.append(matrix[i][0])
del matrix[row]
del matrix[0]
add_to_list([x[1:col] for x in matrix], ans)
return
for i in range(count):
info = input().split()
m = int(info[0])
n = int(info[1])
matrix = [[] for i in range(m)]
src = input().split()
for j in range(len(src)):
matrix[j // n].append(src[j])
ans=[]
add_to_list(matrix,ans)
print(' '.join(ans),end = ' \n') |
b79c016c80d8e48b35abc08c819a22ac01e5ecde | miyagipipi/studying | /最长回文子串.py | 1,387 | 3.953125 | 4 | '''5 最长回文子串'''
'''给定一个字符串 s,找到 s 中最长的回文子串'''
#优化解法
def longestPalindrome(self, s):
if not s: return ""
length = len(s)
if length == 1 or s == s[::-1]: return s
max_len,start = 1,0
for i in range(1, length):
even = s[i-max_len:i+1]
odd = s[i-max_len-1:i+1]
if i - max_len - 1 >= 0 and odd == odd[::-1]:
start = i - max_len - 1
max_len += 2
continue
if i - max_len >= 0 and even == even[::-1]:
start = i - max_len
max_len += 1
continue
return s[start:start + max_len]
#我的解法
length = len(s)
if length == 1: return s
if length == 2: return s if s[0] == s[1] else s[0]
if s[::] == s[::-1]: return s
for size in reversed(range(2, length)):
for loc in range(length - size + 1):
part = s[loc: loc + size]
if part == part[::-1]:
return part
return s[0]
'''一开始一直在想怎么给回文左右加上相同的数,后面发现
实现不了,所以没办法写了一个类似于遍历的算法,先是
看s整体是不是回文,然后遍历查询长度为len(s)-1的子串
是不是回文,最后一直遍历到长度为2.
如果找到了,那它肯定是最长的,所以不用再遍历
如果没有找到,说明没有长度大于1的回文,直接返回s[0]即可''' |
ca026b4eb27dd9e38577713e81eed7ba66bb3b4a | eminem18753/hackerrank | /Problem solving/Algorithm/between_two_sets.txt | 939 | 3.59375 | 4 | #!/bin/python
from __future__ import print_function
import os
import sys
import math
#
# Complete the getTotalX function below.
#
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
def getTotalX(a, b):
#
# Write your code here.
#
count=0
first=1
second=b[0]
for i in a:
first*=i/gcd(first,i)
for i in b:
second=gcd(second,i)
if math.floor(second/first)!=math.ceil(second/first):
return 0
else:
output=second/first
for i in range(1,output+1):
if output%i==0:
count+=1
return count
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
nm = raw_input().split()
n = int(nm[0])
m = int(nm[1])
a = map(int, raw_input().rstrip().split())
b = map(int, raw_input().rstrip().split())
total = getTotalX(a, b)
f.write(str(total) + '\n')
f.close()
|
a31b58c56d15c32b7633163c65c503ea7f75b54e | juneltx/qcb-78 | /python_class/ui_lesson_01.py | 1,548 | 3.796875 | 4 | """接口自动化、UI自动化(人工点、浪费时间,效率低下。枯燥)、APP自动化
UI自动化是人和浏览器界面的互动,代码代替人实现和浏览器之间的互动
代码---通过 浏览器驱动 将代码指令翻译给浏览器,使得浏览器做出响应
Chromedriver(如果用最新的可以,没有最新的可以用71版本,比较稳定,可以向前兼容高版本。低版本的驱动可以翻译高版本的浏览器
geckodriver
ieserverdriver
下载解压为chromedriver.exe,放至python安装目录文件夹下"""
##2、selenium工具,UI自动化工具,也是第三方库文件
'''selenium工具包括三个部分:
1、ide 用来录制脚本,用得少,不好用,录制脚本的工具难免会出错;
2、webdriver,库,提供了对网页操作的一些方法,结合python或java来使用;
3、grid 分布式,同时对多个浏览器实现并发测试
'''
#1\selenium安装好,2、驱动下载---python对应的安装目录;3、导入selenium webdriver
#导入selenium工具中的webdriver库
from selenium import webdriver
import time
driver=webdriver.Firefox()#初始化一个浏览器,初始化一个会话session
driver.get("http://baidu.com") #打开浏览器对应的网址
driver.maximize_window()
driver.get("https://taobao.com")
time.sleep(2)
driver.back()
time.sleep(2)
driver.forward()
time.sleep(2)
driver.refresh()
driver.close()
#关闭浏览器 close():关闭窗口,不会退出浏览器,,quit()退出当前会话,关闭浏览器,清楚缓存
|
3e77e9357c2028d159e3263c2c7ecc3aa4ef8d57 | AChen24562/Python-QCC | /Week-13-File-Day2/FilesExamples_II/Ex6_file_append.py | 423 | 4.375 | 4 | # To write to an existing file,
# you must add a parameter to the open() function:
# "a" - Append - will append to the end of the file
# "w" - Write - will overwrite any existing content
# Open the file and append content to the file:
file = 'myfile1.txt'
f = open(file, "a")
f.write("Now the file has more content!\n")
#f.close()
#Open and read the file after the appending:
f = open(file)
print(f.read())
f.close()
|
940905bb36d700f194bf6e28645a9b0174e1c692 | SinghHrmn/PythonProgramsV2 | /start printing.py | 119 | 3.875 | 4 | i=1
n=int(input("enter the number of stars "))
ans=""
for i in range(1,n+1):
ans=ans+"*"
print (ans)
i=i+1
|
8c7ab83cc7a2d37745ff4b9549e8e4b639e48100 | Chrisgarlick/Python_Projects | /My_Projects/Mean_median_mode.py | 517 | 3.84375 | 4 | import math
lst = [1, 4, 5, 67, 2, 3, 5, 6, 1, 23, 4, 6, 7, 1, 2, 2, 234, 3, 32, 1, 12, 2, 2]
# Mean - Add all up and divide by length
def mean(lst):
total = sum(lst)
average = total / len(lst)
return average
# Median - Sort and find middle number
def median(lst):
lst.sort()
length = len(lst)
mid = length / 2
mid = math.ceil(mid)
return lst[mid]
# Mode - most occuring number - Without using the counter module
mode = [[x, lst.count(x)] for x in set(lst)]
mean(lst)
median(lst)
|
ee811133389acbabdefc8dc0eb6e82690d530673 | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_397.py | 799 | 4.0625 | 4 | def main():
userTemp = float(input("Please enter the temperature: "))
tempVari = input("Please enter 'C' for Celsius, or 'K' for Kelvin: ")
if userTemp <= 0 and tempVari == C:
print("At this temperature, water is a (frozen) solid.")
if userTemp > 0 or userTemp < 100 and tempVari == C:
print("At this temperature, water is a liquid.")
if userTemp > 100 and tempVari == C:
print("At this temperature, water is a gas.")
if userTemp <= 273.15 and tempVari == K:
print("At this temperature, water is a (frozen) solid.")
if userTemp > 273.15 or usertemp < 373.15 and tempVari == K:
print("At this temperature, water is a liquid.")
if userTemp > 373.15 and tempVari == K:
print("At this temperature, water is a gas.")
main()
|
0ecb51ea9cde416e316a0d2d4f36221b2296477e | dalexach/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/0-norm_constants.py | 540 | 3.9375 | 4 | #!/usr/bin/env python3
"""
Normalization Constants
"""
import numpy as np
def normalization_constants(X):
"""
Function that calculates the normalization (standardization)
constants of a matrix:
Arguments:
- X: is the numpy.ndarray of shape (m, nx) to normalize
* m is the number of data points
* nx is the number of features
Returns:
The mean and standard deviation of each feature, respectively
"""
mean = np.mean(X, axis=0)
st_dev = np.std(X, axis=0)
return mean, st_dev
|
aece6d1fa40aa6b2ca3da1decb18948521d72c89 | BHUVANESHWARI12/py | /b-8.py | 109 | 3.984375 | 4 | s=0
print("sum of natural numbers upto N")
n= int(input("N="))
for x in range(1,n+1):
s=s+x
print(s)
|
e89dc35b5897cd9c7003969dc42e91fa5c09be2f | yasas100/Python | /beginner/madlibs.py | 749 | 4.1875 | 4 | #!/usr/bin/env python
"""
File: madlibs.py
Author: Tem Tamre
A madlibs adventure!
Concepts covered: Strings, IO, printing
"""
__author__ = "Tem Tamre"
__copyright__ = "ttamre@ualberta.ca"
def main():
name = input("Enter a name: ")
place = input("Enter a place: ")
vehicle = input("Enter the name of a vehicle: ")
verb = input("Enter a verb: ")
adverb = input("Enter an adverb: ")
print("{name} went to visit their best friend at {place}. While he was there, he saw a {adverb} {verb} {vehicle} speeding down the road! While unsure of what was going on at first, {name} soon found out\
that it was a street race!".format(name=name, place=place, vehicle=vehicle, verb=verb, adverb=adverb))
if __name__ == "__main__":
main()
|
c62eb787de5a33b3e6dcf5db50bf08a5da118224 | angelxehg/utzac-python | /Unidad 2/Ejercicios Clases/Ejercicio3.py | 637 | 3.921875 | 4 | class Numbers():
def __init__(self, num1, num2):
self.__num1 = num1
self.__num2 = num2
def added(self):
return self.__num1 + self.__num2
def subtracted(self):
return self.__num1 - self.__num2
def multiplied(self):
return self.__num1 * self.__num2
def divided(self):
return self.__num1 / self.__num2
numbs = Numbers(
int(input("Ingrese el primer número: ")),
int(input("Ingrese el segundo número: "))
)
print("Sumado:", numbs.added())
print("Restado:", numbs.subtracted())
print("Multiplicado:", numbs.multiplied())
print("Dividido:", numbs.divided())
|
d92d752f1f34f63eb77649741754b0091ee6a949 | sohag2018/Python_G5_6 | /FromAnkur/password_generate.py | 327 | 3.65625 | 4 | import string
import random
'''def add(x,y,z=0):
return x+y+z
print(add(5,6))
print(add(5,6,10))'''
def pw_generate (size=1,chars=string.ascii_letters+string.digits+string.punctuation):
return ''.join(random.choice(chars) for _ in range (size))
print(pw_generate(int(input('How many characters in your password?')))) |
618a07b7b92daab28be4fd1911611699e33e4846 | arahant/Science-Simulator-Calculator | /python/physics/mechanics/motion/generic/Projectile.py | 1,902 | 3.6875 | 4 | import math
import numpy as nm
import matplotlib.pyplot as plt
def calculateTime(iVy,g):
return float(iVy)/g
def calculateRange(time,iVx):
return float(iVx)*time
def calculateHeight(iVy,g):
return float(math.pow(iVy,2))/(2*g)
def getY_X_TrajectoryEquation(x,iVx,g,angle):
return nm.tan(nm.pi*angle/180)*x - float(g)/(2*iVx*iVx)*(x*x)
def getY_Time_TrajectoryEquation(iVy,g,t):
return float(iVy)*t - float(g)/2*(t*t)
def getVy_Time_Equation(iVy,g,t):
return float(iVy) - float(g)*t
#
def initiate():
g = 9.86
angle = input("Enter the initial projectile angle: ")
iVelocity = input("Enter the initial projectile velocity: ")
calculate(g,angle,iVelocity)
def calculate(g,angle,iVelocity):
iVx = float(iVelocity)*nm.cos(nm.pi*float(angle)/180)
print("Initial velocity along x axis is "+str(iVx)+" m/s")
iVy = float(iVelocity)*nm.sin(nm.pi*float(angle)/180)
print("Initial velocity along y axis is "+str(iVy)+" m/s")
time = calculateTime(iVy,g)
print("The projectile duration is "+str(time*2)+" s")
range = calculateRange(time*2,iVx)
print("The max. projectile range is "+str(range)+" m")
height = calculateHeight(iVy,g)
print("The max. projectile height is "+str(height)+" m")
plot_graphs(g,angle,iVelocity,iVx,iVy,time,range)
def plot_graphs(g,angle,iV,iVx,iVy,time,range):
t = nm.arange(0,2*time,float(time)/10)
plt.figure(1)
plt.subplot(211)
plt.plot(t,getY_Time_TrajectoryEquation(iVy,g,t),'r--')
plt.title("Projectile motion - Height Trajectory(t)")
plt.subplot(212)
plt.plot(t,getVy_Time_Equation(iVy,g,t),'r--')
plt.title("Projectile motion - Vy(t)")
x = nm.arange(0,range,0.1)
plt.figure(2)
plt.subplot(111)
plt.plot(x,getY_X_TrajectoryEquation(x,iVx,g,angle),'r--')
plt.title("Projectile motion - Height Trajectory(x)")
plt.show()
#
initiate()
|
ca3cb64788663f8024317fd9fc0f08c7c627b422 | programmingkids/python-level1 | /chapter06/work10.py | 91 | 3.53125 | 4 | num = 10
if :
print("5以上です")
else :
print("5より小さいです")
|
ba16629db78b9de869df678c1fb86173ef837412 | uutzinger/BucketVision | /2018 Pipeline/framerate.py | 1,180 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 24 20:46:25 2017
@author: mtkes
"""
import time
class FrameRate:
def __init__(self):
# store the start time, end time, and total number of frames
# that were examined between the start and end intervals
self._start = None
self._end = None
self._numFrames = 0
self._rate = 0.0
def start(self):
# start the timer
self._numFrames = 0
self._start = time.time()
return self
def reset(self):
self.start()
def stop(self):
# stop the timer
self._end = time.time()
def update(self):
# increment the total number of frames examined during the
# start and end intervals
self._numFrames += 1
def elapsed(self):
# return the total number of seconds between the start and
# end interval
return (time.time() - self._start)
def fps(self):
# compute the (approximate) frames per second
if (self._numFrames > 10):
self._rate = self._numFrames / self.elapsed()
self.reset()
return self._rate
|
2528f5525d9f0d6928ed7eb1df8198b98f8a70b9 | goodluckcwl/LeetCode-Solution | /树/687. 最长同值路径/longestUnivaluePath.py | 582 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if __name__ == '__main__':
s = Solution()
t1 = TreeNode(1)
t1.left = TreeNode(4)
t1.right = TreeNode(5)
t1.left.right = TreeNode(4)
t1.left.left = TreeNode(4)
t1.right.left = TreeNode(5)
r1 = s.longestUnivaluePath(t1)
print '' |
77c1879079cfe2338a272d7690caf34f93220263 | savourylie/cracking_the_code_interview | /ch1/1_8_zero_matrix.py | 607 | 3.828125 | 4 | def zero_matrix(mat):
zero_rows = set()
zero_cols = set()
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] == 0:
zero_rows.add(i)
zero_cols.add(j)
return [[mat[i][j] if i not in zero_rows and j not in zero_cols else 0 for j in range(len(mat[0]))] for i in range(len(mat))]
if __name__ == '__main__':
mat1 = [[1, 2, 0], [1, 1, 0], [1, 1, 1]]
mat_result1 = [[0, 0, 0], [0, 0, 0], [1, 1, 0]]
mat2 = [[1, 2, 1], [1, 1, 0], [1, 1, 1]]
mat_result2 = [[1, 2, 0], [0, 0, 0], [1, 1, 0]]
assert zero_matrix(mat1) == mat_result1
assert zero_matrix(mat2) == mat_result2
|
b2bae9ea05229da1a496eb0e7a0425a9e17f0bdf | fausrguez/python-exercises | /4/main.py | 2,442 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Crea un programa en Python que pida un número n al usuario, y a continuación cree una lista con las n palabras pedidas al usuario. Una vez creada la lista la imprimes en pantalla, y a continuación le pide al usuario dos palabras más pal1 y pal2. Se pide que cuente la cantidad de veces que aparece pal1 en la lista, y que reemplace con pal2 cada ocurrencia de pal1. Vuelve a mostrar la lista en pantalla. Por último elimina de la lista el elemento n-1 (sólo si n>1) y vuelve a mostrar la lista en pantalla.
# Salida del programa:
# Introduzca la cantidad de palabras: 5
# Introduce la palabra 1: Pepe Introduce la palabra 2: Ordenador Introduce la palabra 3: Pepe Introduce la palabra 4: Tableta Introduce la palabra 5: Móvil
# Se imprime la lista:
# [‘Pepe’, ‘Ordenador’, ‘Pepe’, ‘Tableta’, ‘Móvil’]
# Introduce la palabra a buscar: Pepe
# Introduce la palabra para reemplazar: Computadora
# Se sustituye Pepe por Computadora, la lista queda así: [‘Computadora’, ‘Ordenador’, ‘Computadora’, ‘Tableta’, ‘Móvil’]
# Se elimina el elemento en la posición 4, la lista queda así: [‘Computadora’, ‘Ordenador’, ‘Computadora’, ‘Móvil’]
import sys
sys.path.append('../')
from printTools import PrintTools, Colors
PrintTools = PrintTools()
Colors = Colors()
def askToUser(msg):
return raw_input(msg)
def getOccurrences(str, arr):
return [i for i, x in enumerate(words) if x == word1]
try:
_n = int(askToUser('How many words would you like to enter?: '))
except ValueError:
PrintTools.error('That\'s not a number')
quit()
words = []
for n in range(_n):
words.append(str(askToUser('Give the word #' + str(n) + ': ')))
PrintTools.emptyLine()
PrintTools.valueWithColor('First List: ', Colors.OKGREEN, words)
word1 = words[0]
occurrences = getOccurrences(word1, words)
PrintTools.valueWithColor('Occurences of "' + word1 + '": ' , Colors.WARNING, len(occurrences))
PrintTools.emptyLine()
for i in occurrences:
words[i] = words[1]
PrintTools.valueWithColor('Second List: ', Colors.OKGREEN, words)
occurrences = getOccurrences(word1, words)
PrintTools.valueWithColor('Occurences of "' + word1 + '": ' , Colors.WARNING, len(occurrences))
PrintTools.emptyLine()
if(len(words) > 1):
del words[len(words) - 1]
PrintTools.valueWithColor('Third List: ', Colors.OKGREEN, words)
|
cb7ce78db7d8eb358281114d39fba3d2077201ed | coreyadkins/codeguild | /practice/tic-tac-toe/coords_board.py | 3,711 | 4.15625 | 4 | """This module performs the functions for Tic-Tac-Toe (TTT) program of placing a token on the board, determining the
winner of a game, and returning a str version of the board, using tuples data type.
"""
from operator import itemgetter
class CoordsTTTBoard:
"""Contains a blank TTT board as list of tuples items, and commands to modify the board, score game, and return str
version of board.
"""
def __init__(self):
"""Defines input value."""
self._list_of_tokens = []
def __repr__(self):
"""Returns real version.
>>> repr(CoordsTTTBoard())
'CoordsTTTBoard()'
"""
return 'CoordsTTTBoard()'
def __eq__(self, other):
"""Defines eauality.
>>> CoordsTTTBoard() == CoordsTTTBoard()
True
"""
return self._list_of_tokens == other._list_of_tokens
def place_token(self, x, y, token):
"""Adds token to a running list of tuples which represents board layout.
>>> X = CoordsTTTBoard()
>>> X.place_token(1, 1, 'X')
>>> X._list_of_tokens
[(1, 1, 'X')]
"""
self._list_of_tokens.append((x, y, token))
def calc_winner(self):
"""Calculates what token character string has won or None if no one has.
>>> X = CoordsTTTBoard()
>>> X._list_of_tokens = [(1, 1, 'X'), (1, 0, 'X'), (1, 2, 'X'), (1, 1, 'O'), (2, 1, 'O')]
>>> X.calc_winner()
'X'
>>> X = CoordsTTTBoard()
>>> X._list_of_tokens = [(1, 0, 'X'), (1, 1, 'O'), (2, 1, 'X')]
>>> X.calc_winner() is None
True
>>> X = CoordsTTTBoard()
>>> X._list_of_tokens = [(1, 1, 'X'), (1, 0, 'X'), (1, 2, 'O'), (1, 1, 'O'), (2, 1, 'O')]
>>> X.calc_winner() is None
True
"""
key = itemgetter(0)
winning_combinations = _get_winning_combinations()
winner = None
tokens_to_coords = [(token[2], (token[0], token[1])) for token in self._list_of_tokens]
coords_to_token = _group_by(tokens_to_coords, key)
for token in coords_to_token:
if sorted(coords_to_token[token]) in winning_combinations:
winner = token
return winner
def __str__(self):
"""Returns a pretty-printed string of the board.
>>> X = CoordsTTTBoard()
>>> X._list_of_tokens = [(0, 2, 'X'), (2, 0, 'X'), (2, 2, 'O'), (1, 0, 'X'), (1, 2, 'O'), (1, 1, 'O'), \
(2, 1, 'O')]
>>> print(X.__str__())
|X|X
|O|O
X|O|O
"""
print_list = [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']
for token in self._list_of_tokens:
x = token[0]
y = token[1]
print_list[y][x] = token[2]
joined_rows = ['|'.join(row) for row in print_list]
return '\n'.join(joined_rows)
def _get_winning_combinations():
"""Generates all of the possible winning combinations in a tic tac toe board."""
winning_col_combinations = [[(x, y) for y in range(3)] for x in range(3)]
winning_row_combinations = [[(x, y) for x in range(3)] for y in range(3)]
winning_diag_combinations = [(i, i) for i in range(3)] + [(3 - i, i) for i in range(3)]
return winning_col_combinations + winning_row_combinations + winning_diag_combinations
def _group_by(iterable, key):
"""Place each item in an iterable into a bucket based on calling the key
function on the item."""
group_to_items = {}
for item in iterable:
group = key(item)
if group not in group_to_items:
group_to_items[group] = []
group_to_items[group].append(item[1])
return group_to_items
|
2d411489254cb6e7ff470bb4a20e8cb2c732dc03 | mEyob/ds-challenge | /prepare_data.py | 1,187 | 3.65625 | 4 | import boto3
from zipfile import ZipFile
BUCKET_NAME = "fairmarkit-hiring-challenges"
OBJECT_NAME = "California Purchases.zip"
def download_from_s3(download_path, bucket_name=BUCKET_NAME, object_name=OBJECT_NAME):
"""Utility function for downloading data from S3
Args:
download_path (string): The file/path to save the data to
bucket_name (string, optional): S3 bucket name. Defaults to BUCKET_NAME.
object_name (string, optional): S3 object name. Defaults to OBJECT_NAME.
"""
s3 = boto3.client('s3')
s3.download_file(bucket_name, object_name, download_path)
def unzip_data(zip_file, unzip_loc):
"""Unzip a file...
Args:
zip_file (string): filename/path to be unzipped
unzip_loc (string): path to unzip to
"""
with ZipFile(zip_file) as zip:
zip.printdir()
zip.extractall(unzip_loc)
def to_float(number):
"""Converts a dollar formatted data into float
Args:
number (string): [value to be converted]
Returns:
float: converted value
"""
try:
converted = float(number.replace("$", ""))
except:
converted = number
return converted
|
420350a9edbfe751376913fb6bdf65cb7565a6b5 | GrantRedfield/SemesterProject | /TimeAnalysis/Day_Of_The_Week.py | 1,286 | 3.515625 | 4 | import datetime
import pandas as pd
import matplotlib.pyplot as plt
import folium
import folium.plugins as fplug
from IPython.display import display
import os
Path = 'C:\\Users\\Grant\\Desktop\\Random\\CS_Group_Project\\'
Path_alt = "C:/Users/Grant/Desktop/Random/CS_Group_Project/map.html"
week_days_lookup = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
week_days= {"Monday" : 0,"Tuesday" :0 ,"Wednesday": 0,"Thursday": 0,"Friday": 0 ,"Saturday": 0 ,"Sunday": 0 }
terrordata = pd.read_csv(
Path + 'GDT_2000_2019.csv')
def countWeekdays(year, month, day,counts):
try:
weekday=week_days_lookup[datetime.date(year,month,day).weekday()]
week_days[weekday] = week_days[weekday] + counts
except:
pass
collect_dates = terrordata.groupby(['iyear','imonth','iday']).size().reset_index(name='counts')
result = [countWeekdays(row[0],row[1],row[2],row[3]) for row in collect_dates[['iyear','imonth','iday','counts']].to_numpy()]
print(collect_dates.head())
print("HERES THE RESULT",week_days)
plt.bar(week_days.keys(), week_days.values())
plt.title('Number of Terrorist Events On Each Day (2000 - 2019)')
plt.xlabel('Weekday')
plt.ylabel('Number of Attacks')
plt.show()
|
f239617568f5b65cb1013d0d909a7043de125fb7 | 1van-me/telebot | /ivan-me/12.py | 385 | 3.5625 | 4 | spisok=[["qwerty", "12345"]]
while True:
answer=input("Введите команду: ")
if answer=="войти":
user=enter(spisok)
if user==True:
print:("Вход выполнен")
elif user==False:
print:("Ошибка входа")
elif answer=="выход":
exit()
elif answer=="вход":
newuser=[] |
fb85be46a92c302c8b231548624f5c2030e969b2 | flyingdutch20/tiny_python_projects | /07_gashlycrumb/gashlycrumb.py | 1,420 | 3.796875 | 4 | #!/usr/bin/env python3
"""
Author : Ted <ted@bracht.uk>
Date : 25 June 2020
Purpose: Return a name and a ghastly way to end
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description="Return a name and a ghastly way to end",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('letters',
metavar='letter',
nargs='+',
help='One or more letters')
parser.add_argument('-f',
'--file',
help='A file with the text to parse',
metavar='FILE',
type=argparse.FileType('r'),
default='.\gashlycrumb.txt')
return parser.parse_args()
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
fh = args.file
# lookup = {}
# for line in fh:
# if len(line.strip()) > 0:
# lookup[line[0].upper()] = line.strip()
lookup = { line[0].upper(): line.rstrip() for line in fh }
for letter in args.letters:
print(lookup.get(letter.upper(), 'I do not know "{}".'.format(letter)))
# --------------------------------------------------
if __name__ == '__main__':
main()
|
93a4b5fe38655a57586201d63daea2213da13f5c | SupakornNetsuwan/Prepro64 | /I N T E G E R is useful (Extra).py | 150 | 3.8125 | 4 | """function print"""
def func():
"""Convert base of number"""
number = input()
base = int(input())
print(int(number, base))
func() |
00d8754d65a4900323ec8f8eb744272d6902843c | Ivaylo-Atanasov93/The-Learning-Process | /Python Advanced/Functions_Advanced-Exercise/Function Executor.py | 659 | 3.796875 | 4 | def func_executor(*args):
result = []
for argument in args:
func = argument[0]
arguments = argument[1]
result.append(func(*arguments))
return result
# def func_executor1(*args):
# result = []
# for element in args:
# func_name = element[0]
# func_input = element[1]
# result.append(func_name(*func_input))
# return result
def sum_numbers(num1, num2):
return num1 + num2
def multiply_numbers(num1, num2):
return num1 * num2
print(func_executor((sum_numbers, (1, 2)), (multiply_numbers, (2, 4))))
# print(func_executor1((sum_numbers, (1, 2)), (multiply_numbers, (2, 4))))
|
f1c69510db8950c6019234a6e817b4031c75d2a6 | nationalarchives/ds-alpha-es-ingest | /date_handling.py | 3,911 | 3.5625 | 4 | from datetime import datetime
import calendar
from collections import namedtuple
import json
import requests
def parse_eras():
era_data = {}
r = requests.get("https://alpha.nationalarchives.gov.uk/staticdata/eras.json")
if r.status_code == requests.codes.ok:
eras = r.json()
else:
with open("eras.json", "r") as f:
eras = json.load(f)
for k, v in eras.items():
era_start = datetime.strptime(v["start_date"], "%Y-%m-%d")
era_end = datetime.strptime(v["end_date"], "%Y-%m-%d")
era_data[k] = {"era_start": era_start, "era_end": era_end}
return era_data
def check_date_overlap(start_obj, end_obj, start_era, end_era):
"""
taken, initially, from:
https://stackoverflow.com/a/9044111
:param start_obj:
:param end_obj:
:param start_era:
:param end_era:
:return:
"""
Range = namedtuple("Range", ["start", "end"])
# Just make a date that spans the entire history of tNA if no bound provided
if not start_obj:
s = datetime(974, 1, 1) # Start of medieval period
else:
s = datetime(start_obj["year"], start_obj["month"], start_obj["day"])
if not end_obj:
e = datetime.today() # Today
else:
e = datetime(end_obj["year"], end_obj["month"], end_obj["day"])
r1 = Range(start=s, end=e)
r2 = Range(start=start_era, end=end_era)
latest_start = max(r1.start, r2.start)
earliest_end = min(r1.end, r2.end)
delta = (earliest_end - latest_start).days + 1
overlap = max(0, delta)
if overlap > 0:
return True
else:
return False
def identify_eras(era_dict, item_start, item_end):
if era_dict and item_start and item_end:
eras = []
for k, v in era_dict.items():
match = check_date_overlap(
start_obj=item_start,
end_obj=item_end,
start_era=v["era_start"],
end_era=v["era_end"],
)
if match:
eras.append(k)
return eras
else:
return []
def fallback_date_parser(datestring):
"""
This date might have something wonky happening, e.g.
29th of Feb, when it's not a leap year
:param datestring:
:return:
"""
try:
month = int(datestring[4:6])
year = int(datestring[0:4])
day = int(datestring[-2:])
last_day_of_month = calendar.monthrange(year, month)[1]
if day > last_day_of_month:
day = last_day_of_month
fixed_date = datetime.strptime("".join([str(year), str(month), str(day)]), "%Y%m%d")
d_dict = {"year": fixed_date.year, "month": fixed_date.month, "day": fixed_date.day}
d_string = fixed_date.strftime("%Y-%m-%d")
return d_string, d_dict
except ValueError: # Changed this to avoid confusion where it returns a dict, rather than None
return None, None # {"year": None, "month": None, "day": None}
def gen_date(datestring, identifier, catalogue_ref):
"""
:param datestring:
:param identifier:
:param catalogue_ref:
:return:
"""
try:
d = datetime.strptime(datestring, "%Y%m%d")
d_dict = {"year": d.year, "month": d.month, "day": d.day}
if d.year:
d_dict["century"] = int(str(d.year)[:-2])
d_string = d.strftime("%Y-%m-%d")
return d_string, d_dict
except ValueError:
with open("date_errors.txt", "a") as df:
df.writelines(
f"ID: {identifier} - Cat Ref: {catalogue_ref} - Date with " f"error: {datestring}\n"
)
return fallback_date_parser(datestring)
if __name__ == "__main__":
a_, a = gen_date("09740101", "foo", "bar")
b_, b = gen_date("14851231", "foo", "bar")
e = parse_eras()
print(e)
eras_ = identify_eras(era_dict=e, item_start=a, item_end=b)
print(eras_)
|
cf50fd569f432e1e3fb54b2e9fefcf5fe27674b5 | akhileshcheguisthebestintheworld/pythonrooom | /menu.py | 280 | 4.21875 | 4 | # author: akhileshcheguisthebestintheworld
menu = ["pizza","pasta","cake"]
for thing in menu:
answer = input("Do you like " + thing +"?")
if answer == "yes":
print "Have it" + "."
elif answer == "no":
print "Okay."
else:
print "I do not understand what that was" + "." |
6cf069ae7c7973604be3a67851ab37539a2c43ee | dotKuro/vorsemesterWISE19-20 | /loesung/blatt1b_4d.py | 321 | 3.578125 | 4 | # Hier sollen alle Zahlen von 1 bis 4 in jeder Kombination mit einander
# multipliziert und sinnvoll ausgegeben werden.
for factor1 in range(1, 5):
for factor2 in range(1, 5):
# Die Platzhalter werden von links nach rechts eingesetzt.
print("{} * {} = {}".format(factor1, factor2, factor1*factor2))
|
50dbfb31aa5ae3b6cd03f3dde738db91a5e3bb59 | Arun101308/Arun101308 | /fibonacci.py | 485 | 4.0625 | 4 | n = int(input("ENTER NUMBER")) # INPUT VALUE
def fibonacci(n): # FIBONACCI IN VAL N
a = 0
b = 1
if n < 0: # IF VAL N GRATERTHEN 0
print("Incorrect input")
elif n == 0: # ELSE IF N INEQUALEN 0
return 0
elif n == 1: # ELIF N INEQUALEN 1
return b
else:
for i in range(1, n): # FOR I IN RANGE VALUE IS 1,N
c = a + b
a = b
b = c
return b
print(fibonacci(n)) #PRINT OUTPUT
|
6d755034bf6d3cefc1a453a179f9b8618e6c699d | doubleZ0108/Mathematic-Model | /DataVisualization/Plot/subplot.py | 387 | 3.578125 | 4 | # -*- coding: utf-8 -*-
'''
@program: subplot.py
@description: 子图
@author: doubleZ
@create: 2020/02/10
'''
import matplotlib.pyplot as plt
import numpy as np
def drawSubplots():
x = np.linspace(0,5,10)
fig, axes = plt.subplots(figsize=(8,6),dpi=100)
axes.plot(x, x**2, 'r')
axes.set_title('y=x^2')
plt.show()
if __name__ == '__main__':
drawSubplots() |
1d2b37893687ef2246a1eea28c068d0258a4db9e | smohapatra1/scripting | /python/practice/start_again/2021/06022021/valid_mountain_array.py | 520 | 3.921875 | 4 | #Valid Mountain Array
# 353 - > A mountain Array
# 01321 - > Not an montain array
def ma(nums):
# Need minimum 3 inputs
if len(nums) <3:
return False
i = 1
#Increasing hill
while i < len(nums) and nums[i] > nums[i-1]:
i+=1
if i == 1 or i ==len(nums):
return False
#Decreasing hill
while i < len(nums) and nums[i] < nums[i-1]:
i+=1
#Reached at the end of the array
return i == len(nums)
nums = [1,2,5,4,2,1]
result = ma(nums)
print (result) |
9db62ab284e542e4d3269c308dd63ec89d75fde8 | tshev/pybind-experiments | /python_example/usage.py | 389 | 3.578125 | 4 | import python_example
import numpy as np
import timeit
n = 10**7
a = np.random.random(n)
b = np.random.random(n)
def dot_product(x, y):
r = 0.0
for a, b in zip(x, y):
r += a * b
return r
print(timeit.timeit(lambda: python_example.dot_product(a, b), number=1))
print(timeit.timeit(lambda: a.dot(b), number=1))
print(timeit.timeit(lambda: dot_product(a, b), number=1))
|
bd66561939c33ccc90275a4e1ce3a6edc40c7d99 | BTomlinson/PFB_problemsets | /python_probset6.py | 751 | 3.796875 | 4 | #! /usr/bin/env python3
opPython = open('Python_06.txt', 'r')
newPython = open('NewPython.txt','w')
#simply open and read the contents of Python_06.txt
print(opPython.read())
print()
#uppercase everything line by line in Python_06.txt and print the result
opPython = open('Python_06.txt','r')
for line in opPython:
line = line.upper()
line = line.rstrip()
print(line)
#for space
print()
#do the same but instead write the results to a new file Python_06.uc.txt
with open('Python_06.txt','r') as songread, open('Python_06_uc.txt','w') as songwrite:
for line in songread:
line = line.strip()
capitalizedlines = line.upper()
songwrite.write(str(capitalizedlines+'\n'))
newsong = open('Python_06_uc.txt','r')
print(newsong.read())
|
a5d832ce3b9fbea2f294c8b0bd7aee6e37fba9f8 | half-cat/gu-chatbot-01 | /clients/exceptions.py | 713 | 3.59375 | 4 | """Модуль исключений, связанных с работой клиентов социальных платформ."""
class OkServerError(Exception):
"""Возникает при возврате invocation-error в заголовках ответа от ОК."""
def __init__(self, code: str, text: str) -> None:
super().__init__(
f'OK error: code {code} -> {text}"'
)
class JivoServerError(Exception):
"""Возникает при возврате ключа error в теле ответа json от Jivo."""
def __init__(self, code: str, text: str) -> None:
super().__init__(
f'JIVO error: code {code} -> {text}"'
)
|
be5f965a5026f5c62f98600f321ecf39807fb02b | sunyi1001/leetcode | /49.py | 990 | 3.640625 | 4 | class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
# find_map = {}
# returnData = []
# for item in strs:
# sortedStr = ''.join(sorted(item))
# if sortedStr in find_map.keys():
# find_map[sortedStr].append(item)
# else:
# find_map[sortedStr] = [item]
# for k, v in find_map.items():
# returnData.append(v)
# print(returnData)
# return returnData
find_map = {}
# returnData = []
for item in strs:
sortedStr = ''.join(sorted(item))
if sortedStr in find_map.keys():
find_map[sortedStr].append(item)
else:
find_map[sortedStr] = [item]
return list(find_map.values())
parstrs = ["eat", "tea", "tan", "ate", "nat", "bat"]
sol = Solution()
res = sol.groupAnagrams(parstrs)
print(res) |
7fc2d1ab4aa20cfc5b35316eef60d38297785b12 | bmoretz/Daily-Coding-Problem | /py/dcp/leetcode/hashtable/duplicate_subtrees.py | 1,420 | 3.78125 | 4 | '''
652. Find Duplicate Subtrees
Example 1:
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
Example 2:
Input: root = [2,1,1]
Output: [[1]]
Example 3:
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
Constraints:
The number of the nodes in the tree will be in the range [1, 10^4]
-200 <= Node.val <= 200
'''
from collections import defaultdict, Counter
class Node:
def __init__(self, val):
self.value = val
self.left, self.right = None, None
def build_tree(values):
if not values:
return None
root = Node(values[0])
values.pop(0)
nodes = [root]
it = iter(values)
for val in it:
parent = nodes[0]
parent.left = Node(val)
if parent.left.value != None:
nodes += [parent.left]
parent.right = Node(next(it, None))
if parent.right.value != None:
nodes += [parent.right]
nodes.pop(0)
return root
def findDuplicateSubtrees(values : list[int]):
root = build_tree(values)
trees = defaultdict()
trees.default_factory = len(trees)
count = Counter()
ans = []
def lookup(node):
if node:
uid = trees[node.value, lookup(node.left), lookup(node.right)]
count[uid] += 1
if count[uid] == 2:
ans.append(node)
return uid
lookup(root)
return ans |
b4afe175a25e09a6ba0e0752ad6ca12ee2914ae2 | rdsilvalopes/python-exercise | /estruturasequencial04.py | 876 | 3.828125 | 4 | #! usr/bin/env python3
##################################################################
#Faça um Programa que peça as 4 notas bimestrais e mostre a média.
##################################################################
def media_prova():
#uma lista para armazenar números.
lista_numeros = []
try:
#iterar quatro vezes para solicitar os números para armazenar.
for index in range(4):
#solicitar um valor e armazená-lo na lista_numeros.
lista_numeros.append(float(input("Informe a nota:")))
except ValueError:
#Imprimir na tela o "valor inválido".
print ("Valor inválido!")
media_prova()
#calcular a média.
media = sum(lista_numeros) / len(lista_numeros)
#Imprimir na tela o resultado da média.
print ("Média: %.1f" % media)
|
45c63f2733cee7c8fcb70a3ae1d5c9fbcd166cee | zhangwei1989/algorithm | /Python/242-valid_anagram_first_2.py | 645 | 3.59375 | 4 | # Difficulty - Easy
# Url - https://leetcode.com/problems/valid-anagram/
# Time complexity: O(N);
# Space complexity: O(1);
class Solution:
def isAnagram(self, s, t):
dict = {}
li = [chr(i) for i in range(ord("a"), ord("z") + 1)]
for i in li:
dict[i] = 0
for i in s:
dict[i] = dict[i] + 1 if dict[i] else 1
for i in t:
if dict[i]:
dict[i] = dict[i] - 1
if dict[i] < 0: return False
else:
return False
for key, value in dict.items():
if value > 0: return False
return True
|
63e2cf18e18d3e52142efed40810667feebff805 | HeatherHeath5/progcon | /08/spring/failed/quodigious/1.py | 473 | 3.546875 | 4 | def digits(n):
return [int(digit) for digit in str(n)]
def prod(li):
return reduce(lambda x, y: x*y, li)
def quodigious(n):
return n % sum(digits(n)) == 0 and n % prod(digits(n)) == 0
if __name__ == '__main__':
while 1:
try: inp = int(raw_input())
except: break
for i in xrange(10**(inp-1)+1, 10**inp+1):
if '0' in str(i) or '1' in str(i): continue
if quodigious(i): print i
print
|
05c36fafea97cac580118af7f81aa3b4483fb1b6 | karimm25/Karim | /TSIS 2/Lecture6/4.py | 58 | 3.890625 | 4 | # Python program to reverse a string
print(input()[::-1]) |
2d1562551b73c03be83864f84b7ed326f191db24 | DalavanCloud/UGESCO | /functions/test_levensthein.py | 1,459 | 3.53125 | 4 | import Levenshtein as L
string1 = "Musée royal de l'Afrique centrale"
string2 = "musée colonial de Tervueren"
print('Levenshtein is ', L.distance(string1, string2))
print('jaro-winkler is ', L.jaro_winkler(string1, string2))
print('jaro is ', L.jaro(string1, string2))
from difflib import SequenceMatcher
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
print('difflib is ', similar(string1, string2))
##########################################################################
data = "place gilson bruxelles belgique"
target = ["Place Charles Gilson", "avenue Gilson", "Gilson"]
import jellyfish
def get_jw_match(data, target):
"""Uses the jaro-winkler algorithm to match strings(names) from the target(the set from which you want to find matches) to the data(the set for which you are trying to find matches."""
score_dict = dict()
for i, item_target in enumerate(target):
for j, item_data in enumerate(data):
jw_score = jellyfish.jaro_winkler(item_data, item_target)
score_dict[i] = j
return score_dict
print(get_jw_match(data, target))
######################################################""
from ngram import NGram
def get_similar(data, target):
G = NGram(target)
return G.find(data)
def get_similars(data, target, threshold):
G = NGram(target)
return G.search(data, threshold=threshold)[0][0]
print(get_similar(data, target))
print(get_similars(data, target, 0.1)) |
195f6ca5897a34a376237e69c400b9d093bc00da | YunsongZhang/lintcode-python | /VMWare/380. Intersection of Two Linked Lists.py | 913 | 3.765625 | 4 | class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class Solution:
"""
@param headA: the first list
@param headB: the second list
@return: a ListNode
"""
def getIntersectionNode(self, headA, headB):
if headA is None or headB is None:
return None
len_a, len_b = self.get_length(headA), self.get_length(headB)
node_a, node_b = headA, headB
while len_a > len_b:
node_a = node_a.next
len_a -= 1
while len_b > len_a:
node_b = node_b.next
len_b -= 1
while node_a != node_b:
node_a = node_a.next
node_b = node_b.next
return node_a
def get_length(self, head):
length = 0
while head is not None:
head = head.next
length += 1
return length
|
f18eb6e4269d282b98c74646ef1acc41e4f3cf55 | jduell12/cs-module-project-hash-tables | /d2_lecture.py | 1,795 | 4.09375 | 4 | #linked list for Hash tables
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.count = 0
def insert_at_head(self, node):
node.next = self.head
self.head = node
self.count += 1
def find(self, value):
cur = self.head
#traverses linked list
while cur is not None and cur.value != value:
cur = cur.next
#checks if node is None or has a value
if cur:
return "Node(%d)" %cur.value
else:
return None
def delete(self, value):
#empty list case
if self.head is None:
return None
#deleting head of list
if self.head.value == value:
old_head = self.head
self.head = old_head.next
old_head.next = None
self.count -= 1
return old_head.value
cur = self.head
while cur is not None and cur.value != value:
prev = cur
cur = cur.next
if cur:
prev.next = cur.next
cur.next = None
self.count -= 1
return cur.value
else:
return None
def __str__(self):
r = f"count: {self.count}\n"
#traverse the list
cur = self.head
while cur is not None:
r += " %d " % cur.value
if cur.next is not None:
r += '-->'
cur = cur.next
return r
ll = LinkedList()
ll.insert_at_head(Node(10))
ll.insert_at_head(Node(40))
ll.insert_at_head(Node(20))
print(ll)
ll.delete(40)
print(ll) |
e89084c121b88ccdeb8269d231e2c57fd71ad6dd | cwebrien/tiger-sat-generator | /tigersatgenerator/uniformksat/generator.py | 1,820 | 3.75 | 4 | #!/usr/bin/env python3
""" tigersatgenerator/uniformksat/generator.py
Generates k-SAT formulae. """
from typing import List
import random
def random_ksat_clauses(k: int, num_clauses: int, num_variables: int, seed: int = None) -> List[List[int]]:
'''
Generates a list of lists which represent SAT clauses. Ensures that the result conforms to k-SAT.
Args:
k: Number of literals per clause
num_clauses: Number of clauses to generate
num_variables: Number of variables across all clauses
seed: Optional seed for reproducibility of results
Returns: A list of clauses where each clause itself is a list
'''
if k <= 0:
raise Exception("k-SAT requires k >= 1, although trivial for k = 1")
if num_clauses <= 0:
raise Exception("k-SAT requires num_clauses >=1")
if num_variables < k:
raise Exception("k-SAT requires num_variables >= k to generator clauses without repeated variables")
clauses = []
random.seed(seed)
for clause_count in range(0, num_clauses):
new_clause = []
variables_used = {} # only use a variable once in a clause
literal_count = 0
# Randomly select a variable and then randomly produce a literal (i.e. keep variable as is, or invert)
while literal_count < k:
# Randomly select a variable
variable = random.randint(1, num_variables)
# Use the variable if possible
if variable not in variables_used:
pos_or_neg = 1 if random.random() < 0.5 else -1 # produce a literal by possibly inverting
new_clause.append(pos_or_neg * variable)
variables_used[variable] = 1
literal_count += 1
clauses.append(new_clause)
return clauses
|
82de1455f60d8a35b7cb52aae5799f973f6e3816 | Nordenbox/Nordenbox_Python_Fundmental | /.history/sortAlgorithm_20201120222047.py | 800 | 3.765625 | 4 | import random
import time
def findMin(L): # find a minist element in a certain list
min = L[0] # surppose the first element in the list is the minist element
for i in L: # map every element of the list
if i < min: # if some element is less than surpposed minist, it replace the minist
min = i
return min
def my_sort(l):
sorted_list = []
for i in range(len(l)):
sorted_list.append(findMin(l)) # put the minist element into the empty list
l.remove(findMin(l)) # remove above minist elemnt from original list
return sorted_list
a = [random.randint(1, 99) for i in range(1, 100)]
print(a, '\n*******************************')
time_start = time.time()
print(my_sort(a))
time_end = time.time()
print(time_end-time_start, 'second')
|
9573f6207433978dc8aa73d7f54606f6117c4d9b | Danang691/Euler.Py | /euler/solutions/euler35.py | 1,507 | 3.5625 | 4 | # -*- coding: utf-8 -*-
from euler.baseeuler import BaseEuler
from euler.sequences import PrimeRange
from euler.util import is_prime
class Euler(BaseEuler):
def solve(self):
# all primes less than 1M
primes = list(PrimeRange(1, 1000000))
res = []
for prime in primes:
if self._check_rotations([int(d) for d in str(prime)], prime):
res.append(prime)
return len(res)
def _check_rotations(self, l, n):
'''
Checks the circular rotations of each prime number for primes
Returns True if all rotations are also prime, false otherwise
l - a list of digits that makes up the prime nunber n
n - The prime number to check
'''
k = 0
while n != k:
cdr = l[1:]
car = l[0]
cdr.append(car)
k = int(''.join([str(s) for s in cdr]))
if not is_prime(k):
return False
l = cdr
return True
@property
def answer(self):
return ('There are %d circular primes below 1 million.' % self.solve())
@property
def problem(self):
return '''
Project Euler Problem 35:
The number, 197, is called a circular prime because all rotations of the
digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37,
71, 73, 79, and 97.
How many circular primes are there below one million?
'''
|
dcc6aa5ca326063a7b4ed9eb1c2b4f9f67229e86 | nanjekyejoannah/ginter | /Cracking-the-coding-interview-solutions/Datastructures/chapter-3-stacks-and-queues/stack.py | 301 | 3.65625 | 4 | class Stack(object):
def __init__(self):
self.stack = []
def pop(self):
self.stack.pop()
def push(self, data):
return self.stack.append(data)
def peek(self):
return self.stack[len(slef.stack)-1]
def size(self):
return len(self.stack)
def is_empty(self):
return self.stack == []
|
121062666fbd2e39ff7efe9dff2f5e3b9e0f4818 | alexbenko/pythonPractice | /classes/ticTac.py | 4,633 | 3.9375 | 4 | class TicTacToe:
player1 = ''
player2 = ''
currentPiece = ''
row1 = ['','','']
row2 = ['','','']
row3 = ['','','']
moves = 0
def __init__(this):
print('Tic Tac Toe Game Initialized...')
this.render()
def displayBoard(this):
print('-----------Tic-Tac-Toe------------')
print('\n')
print(f'1. {this.row1}')
print(f'2. {this.row2}')
print(f'3. {this.row3}')
print('\n')
print('-----------Tic-Tac-Toe------------')
def isEven(this):
return this.moves % 2 == 0
def validMove(this,row,column):
if row[column - 1] == '':
return True
else:
return False
def getRow(this):
while True:
try:
if this.currentPiece == 'X':
whichRow = int(input(f'{this.player1} which row would you like to play your piece? [1,2,3]: '))
else:
whichRow = int(input(f'{this.player2} which row would you like to play your piece? [1,2,3]: '))
except ValueError:
print('Invalid Input, Please Only type the numbers 1,2,3. Please Try Again')
continue
if whichRow == 1 or whichRow == 2 or whichRow == 3:
return whichRow
else:
print('Invalid input, only enter 1,2, or 3')
continue
def getCol(this):
while True:
try:
column = int(input('Which column would you like to place your piece [1,2,3]: '))
except ValueError:
print('Invalid Input, Please Only type the numbers 1,2,3. Please Try Again')
continue
if column == 1 or column == 2 or column == 3:
return column
else:
print('Invalid input, only enter 1,2, or 3')
continue
def checkRows(this):
rows = [this.row1,this.row2,this.row3]
for row in rows:
if len([i for i in row if i == this.currentPiece]) == 3:
return True
return False
def checkCols(this):
if this.row1[0] == this.currentPiece and this.row2[0] == this.currentPiece and this.row3[0] == this.currentPiece:
return True
elif this.row1[1] == this.currentPiece and this.row2[1] == this.currentPiece and this.row3[1] == this.currentPiece:
return True
elif this.row1[2] == this.currentPiece and this.row2[2] == this.currentPiece and this.row3[2] == this.currentPiece:
return True
else:
return False
def checkDiags(this):
if this.row1[0] == this.currentPiece and this.row2[1] == this.currentPiece and this.row3[2] == this.currentPiece:
return True
elif this.row1[2] == this.currentPiece and this.row2[1] == this.currentPiece and this.row3[0] == this.currentPiece:
return True
return False
def checkForWinner(this):
if this.checkRows() or this.checkCols() or this.checkDiags():
if this.currentPiece == 'X':
print(f'{this.player1} is the Winner!')
this.displayBoard()
else:
print(f'{this.player2} is the Winner!')
this.displayBoard()
return True
else:
return False
def render(this):
this.player1 = input('Enter name of Player 1: ')
this.player2 = input('Enter name of Player 2: ')
print(f'Welcome {this.player1} and {this.player2}. {this.player1} is X and {this.player2} is O. {this.player1} goes first')
while this.moves <= 9:
this.displayBoard()
if this.isEven():
this.currentPiece = 'X'
else:
this.currentPiece = 'O'
while True:
row = this.getRow()
col = this.getCol()
if row == 1:
if this.validMove(this.row1,col):
this.row1[col - 1] = this.currentPiece
this.moves += 1
break
else:
print(f'A piece already exists at row: {row} and column: {col}, try a different spot')
continue
elif row == 2:
if this.validMove(this.row2,col):
this.row2[col - 1] = this.currentPiece
this.moves += 1
break
else:
print(f'A piece already exists at row: {row} and column: {col}, try a different spot')
continue
elif row == 3:
if this.validMove(this.row3,col):
this.row3[col - 1] = this.currentPiece
this.moves += 1
break
else:
print(f'A piece already exists at row: {row} and column: {col}, try a different spot')
continue
if this.moves >= 3:
print(f'{this.moves} total moves detected, checking for Winner...')
if this.checkForWinner():
break
print('No Winner Detected,Continuing Game...')
if this.moves >= 10:
print('Tie Game :/')
game = TicTacToe() |
fd5e24f97c7a979d2e96097f1ad4986a93a2a2b0 | adamdevelops/Anagram | /q1.py | 698 | 4 | 4 | '''
Question 1
Given two strings s and t, determine whether some anagram of t is a substring of s.
For example: if s = "udacity" and t = "ad", then the function returns True.
Your function definition should look like: question1(s, t) and return
a boolean True or False.
'''
# is_anagram()
def ques1(s, t):
string_dict = {}
if len(t) > len(s): # O(1)
return "Anagram not possible"
for char in t:
string_dict[char] = 1
if char in s:
string_dict[char] += 1
return all(string_dict[char]==2 for char in string_dict)
print ques1("stackoverflow", "rover")
print ques1("udacity", "ad")
print ques1("animal", "fan")
# O(nlogn + nlogn + n^2)
|
8d32fe3b441d9e2a7345822b5fec33e2ba5645ef | AlexGeorgeLain/SSD_CodeSnippets | /towers_of_hanoi.py | 413 | 4.03125 | 4 | """A recursive solution for the Towers of Hanoi problem."""
def hanoi(n, A, C, B):
if n == 1:
print(f'{n} from {A} to {C}')
else:
hanoi(n-1, A, B, C)
print(f'{n} from {A} to {C}')
hanoi(n-1, B, C, A)
# 2^n - 1 moves.
# this solution allows that positions can be passed over.
# i.e. you can pass from A to C without having to stop on B first.
hanoi(10, 'A', 'C', 'B')
|
2c1cac12783dddaf0534d0c5d8025c79e639be34 | jkmeyer1010/DSC530_Course_Assignments | /Week_2/Exercise_2.1_Jake_Meyer.py | 989 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Author: Jake Meyer
Assignment 2.1: Preparing for EDA
Date: 03/25/2021
"""
# Display the text “Hello World!
# I wonder why that is always the default coding text to start with”
print("Hello World! I wonder why that is always "
"the default coding text to start with")
# Add two numbers together
x = 2
y = 3
z = x + y
print(x,"+",y,"=",z)
# Subtract a number from another number
a = 10
b = 20
c = b - a
print(b,"-",a,"=",c)
# Multiply two numbers
i = x * y
print(x,"*",y,"=",i)
# Divide between two numbers
k = b // a
print(b,"/",a,"=",k)
# Concatenate two strings together (any words)
first_name = "John "
last_name = "Doe"
name = first_name + last_name
print(name)
# Create a list of 4 items (can be strings, numbers, both)
list = [1, "John", 8, "a"]
print(list)
# Append an item to your list (again, can be a string, number)
list.append(9)
print(list)
# Create a tuple with 4 items (can be strings, numbers, both)
t = (1, "a", 2, "b")
print(t) |
f324e01d5250fdc871fa16610dd6c823df5b0ef7 | ShadowLore/hw_3 | /ito.py | 849 | 4.375 | 4 | homework_list = ['Пропылесосить', 'Помыть полы', 'Погладить белье', 'Приготовить ужин', 'Повесить полку', 'Отдохнуть', 'Помочь с уроками']
# 0 1 2 3 4 5 6
print(homework_list[2])
print(homework_list[len(homework_list) - 1])
print(homework_list[-1])
print(homework_list[-4])
print(homework_list[len(homework_list) - 4])
homework_list.append('Почистить обувь')
print(homework_list)
homework_list.insert(6, 'Поиграть с котом')
print(homework_list)
last_work = homework_list.pop()
print(last_work)
print(homework_list)
print(homework_list.count('Отдохнуть'))
print(homework_list.index('Отдохнуть'))
|
dcc20982f7141004b20e0d70c52a379d51decfb9 | MiniWong101/rock-paper-scissors | /main.py | 930 | 4.21875 | 4 | print("Welcome to rock paper scissors games")
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
choice = [rock,paper,scissors]
user = int(input("What whould you choose? Type 0 for rocks, 1 for paper or 2 for scissors\n"))
if user >=3 or user<0:
print("Invalid Number")
else:
print(choice[user])
computer = random.randint(0,2)
print("computer choose: ")
print(choice[computer])
if user == 0 and computer == 2:
print("You win!")
elif computer == 0 and user == 2:
print("You lose!")
elif computer > user:
print("You lose!")
elif user > computer:
print("You win!")
elif user == computer:
print("Draw")
|
75c08ea66b0faa2cb49b766226d5cc169f6256e2 | skjha1/Algo_Ds | /Sorting Algorithms/Python/bubblesort.py | 255 | 4.03125 | 4 | def bubble_sort(arr):
changed = True
while changed:
changed = False
for i in range(len(arr) - 1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
changed = True
return None
|
164c0a872d37c6cb55426f1fd75b432e735b590d | BCookies222/Python-Codes | /Ch11_ch1.py | 5,557 | 4.125 | 4 | """Challenge 1: Increase the difficulty as the game progresses.
+Increase the speed of the pizzas and chef.
+Raise the pan to a higher level.
+Increase the number of crazy chef's flinging pizzas."""
# Import the games and color module from livewires package for creating a game and allowing to choose from a set of colors
from livewires import games, color
import random # for setting the random position of the pizzas
# Initialize the screen and provide access to the games mouse object
games.init(screen_width=640,screen_height=480, fps=50) # fps: Frames per second
# Create a Pan class
class Pan(games.Sprite): # Pan inherits from its super class (Sprite)
# Upload the image of Pan
pan_pic=games.load_image("pan.jpg")
# Constructor to initialize new Pan Object with its image, position (x and y)
def __init__(self):
super(Pan,self).__init__(image=Pan.pan_pic,
x=games.mouse.x,
bottom=games.screen.height-5) # Raised the pan from height to height-5
self.score=games.Text(value=0, color=color.red, size=25, right=games.screen.width-10, top=5)
games.screen.add(self.score) # The score is always 10 pixels left of the right edge of the screen i.e games.screen.width-10
# Method to move player's pan
def update(self):
# start by placing pan in accordance with mouse position
self.x=games.mouse.x #? Why not using right instead of x
# If pan goes out of left edge then reset the left edge to 0
if self.left<0: # Update method has left and right properties
self.left=0
# If Pan goes out of the right edge then reset the right edge to the width of the screen
if self.right>games.screen.width:
self.right=games.screen.width
# Call the check_catch() to see if pan caught any pizza or not
self.check_catch()
def check_catch(self):
for pizza in self.overlapping_sprites:
self.score.value+=10 # Increase the score by 10
self.score.right=games.screen.width-10#place the new score again 10 pixels away from the right edge of the screen
pizza.handle_caught()# Call the Pizza's handle_caught()
#Create the Pizza class
class Pizza(games.Sprite):
#Upload the Pizza Image
pizza_pic=games.load_image("pizza.jpg")
speed=2 # Falling speed of Pizzas-increased from 1 to 2
#set the initial values for the pizza-Constructor
def __init__(self,x,y=90): # Place the pizza at chef's chest level ?? Not clear its not defined in angles
super(Pizza,self).__init__(image=Pizza.pizza_pic, x=x,y=y,dy=Pizza.speed) #dx=? and what is x=x and y=y
# Method to check the screen boundary for pizzas
def update(self):
if self.bottom > games.screen.height: # if the pizza moves out of the screen then call end_game() and destroy the pizza sprite object;
self.end_game()
self.destroy()
def handle_caught(self):
self.destroy()
def end_game(self):
# At the end of the game just display the message and destroy the Pizza Sprite
end_msg=games.Message(value="Game Over!",
color=color.brown,
size=90,
x=games.screen.width/2,
y=games.screen.height/2,
lifetime=5*games.screen.fps, # Number of frames in 1 second=5*50=250 so 250/50=5 seconds
after_death=games.screen.quit)
games.screen.add(end_msg)
class Chef(games.Sprite):
# Upload the Chef's Image
chef_pic=games.load_image("chef.jpg")
#Contsructor to initialize the chef ?? Why is x not defined for chef
def __init__(self,y=55, speed=6,odds_change=200): # Increased the speed of chef dropping pizzas fall from 2 to 6
super(Chef,self).__init__(image=Chef.chef_pic,
x=games.screen.width/2, # Chef is in the middle and on the top of the brick wall
y=y,
dx=speed) # Chef only moves in the x-direction
self.odds_change=odds_change # Odds_change is an integer that represents odds that chef will change his direction
#e.g if odd_change=200 then there is 1 in 200 chance that chef will change his direction, you will see it's use in update()
self.time_til_drop=0 # It is an integer in mainloop cycles that represents time till chef drop the next pizza. It is set to 0 initially so
#that when chef spring to life a pizza is immediately dropped. See its use in the check_drop()
#Method that discusses how the Chef moves
def update(self):
if self.left <0 or self.right>games.screen.width:
self.dx=-self.dx
elif random.randrange(self.odds_change)==0: # ? what is meant by this statement
self.dx=-self.dx
# This method is called every mainloop cycle-DOES NOT MEAN that: A new pizza is dropped every 50 seconds
self.check_drop()
def check_drop(self):
#Countdown for the chef to drop the pizza
if self.time_til_drop >0:
self.time_til_drop-=2 # Increased from 1 to 2 to show the change in number of pizzas dropping
else:
new_pizza=Pizza(x=self.x) # new pizza created at x position of the Chef Sprite
games.screen.add(new_pizza)
self.time_til_drop=int(new_pizza.height*1.1/Pizza.speed)+1 #Next pizza is dropped when the distance from the previous pizza is about
#30% of pizza height(increasing the time delay b/w new pizza by 30%), independent of how fast the pizzas are falling -changed from 1.3 to 1.1 that should increase the #number of pizzas
def main():
wall_pic=games.load_image("Wall.jpg", transparent=False)
games.screen.background=wall_pic
the_chef=Chef()
games.screen.add(the_chef)
the_pan=Pan()
games.screen.add(the_pan)
games.mouse.is_visible=False
games.mouse.event_grab=True
games.screen.mainloop()
main()
|
c3315098c4b84554bda9e88d7236a2f8621e5e6f | mepallabiroy/Hacktoberfest2020 | /Algorithms/Python/Probability of item drop/items_drop_chance.py | 2,206 | 4.1875 | 4 | # This is a small script I've made for counting how many times you should fight
# an enemy, in any RPG game, in order to get a specific drop.
# If you enter the percentage of this specific item drop, this script will tell
# you how many times you should fight this enemy or event, in order to be almost
# sure you are going to get that item.
# For example, let assume in some game an enemy has a 1% chance of dropping an
# epic sword. You do really want that sword. Well, as it drop rate is 1/100 you
# are expected to get 1 sword for every 100 enemies you kill. But there is a
# chance you kill 100 enemies and you still don't get any sword. So this script
# tell you how many enemies you need to kill to get that epic sword!
# This program will ask the user for a value between 0 and 100 and then it will
# return:
#
# * The expected times
# * The nearly guaranteed 90% value
# * The nearly guaranteed 99% value
# NOTE: expected time refers to the total number of attemps a player can expect
# to get 1 drop.
# Nearly guaranteed value refers to how many times to have a that chance to get
# 1 item
# This scripts is based on the statics Bernoulli distribution
import math, sys
def enter_value(x = None):
while True:
try:
if x == None:
x = float(input("Enter the probability number: "))
else:
x = float(x)
break
except ValueError:
print("Wrong value, please try again")
return x
def values(percent):
if percent == 0:
return 0, 0, 0
elif percent > 100:
return 1, 1, 1
prob = percent / 100
expected = math.ceil(100 / percent)
comp = 1 - prob
n = 0; m = 1
res = 1
while res > 0.01:
res = res * comp
n = n+1
if res > 0.1:
m = m+1
return expected, m, n
def bernoulli(x = None):
p = enter_value(x)
aux = values(p)
print("The expected number of times are: {}\n The nearly guaranteed times"
"to drop are:\n 90% of chances: {} \n 99% of chances: {}\n"\
.format(aux[0], aux[1], aux[2]))
while True:
h = input("Enter a percentage value or enter 'q' to exit\n")
sys.exit(0) if h == 'q' else bernoulli(h)
|
30fb71aca94fc814dd4deacfd51f439db978a04b | JuniorMSG/python_study | /Coding_Test/CodingTest/01_Level_01_for/Q_2438.py | 614 | 4.09375 | 4 | """
https://www.acmicpc.net/step/3
Subject : Coding Test For
"""
"""
https://www.acmicpc.net/problem/2438
def Q_2438():
첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제
입력
첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.
출력
첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다.
예제 입력 1
5
예제 출력 1
*
**
***
****
*****
"""
def Q_2438():
a = int(input())
b = ""
for i in range(1, a+1):
print("*" * i)
return
Q_2438() |
8c18f4f0963e08ca10cdc416c4aa3901b5e2b43e | EuganeLebedev/Python_for_test | /lections/lesson7/my_files/lesson_7_decorator.py | 354 | 3.828125 | 4 | def square(number):
return number ** 2
def cube(fn):
def wrapper(number):
result = fn(number)
result = result + number
return result
return wrapper
def square_2(number):
return number**2
decorated_square = cube(square_2)
@cube
def square(number):
return number**2
a = 10
b = square(a)
print(b)
|
3a16d67663722d4281518119f2606a18131dafe8 | ArturAlvs/filomilitar | /code/classes/conhecimento.py | 2,644 | 3.75 | 4 | class Conhecimento():
def __init__(self, tipo_conhecimento, valor_inicial_conhecimento, n_ru):
self.tipo_conhecimento = tipo_conhecimento #
self.n_ru = n_ru # numero de filosofos ou militares
self.lista_conhecimento = [valor_inicial_conhecimento] # valor inicial do conhecimento eh o valor inicial da lista, mesmo valor de pessoas que "ajudaram no conhecimento"
# usa as pessoas para desenvolver o conhecimento, dependendo do nivel para o tipo de conhecimento, o desenvolvimento pode ficar mais rapido ou mais lento
def DesenvolverConhecimento(self, pessoas, taxa_desenvolvimento_anual, player):
# se conhecimento ainda nao foi totalmente desenvolvido
if not (self.lista_conhecimento[-1] == 0):
# loop de 1 ate a taxa de desenvolvimente + 1 -> id das pessoas
x = 0
# n_ru pois so de trabalhar no desenvolvimento do conhecimento ele ja eh atualizado
# n_desenvolvimento = self.n_ru
n_desenvolvimento = 0
# print("pessoas----------")
# print(pessoas)
# print("pessoas----------")
for idp, pessoa in pessoas.items():
# 1 se a pessoa nao for da mesma ideologia do conhecimento, 2 se for
n_desenvolvimento_atual = 1
if pessoa.Ideologia() == "filosofo" and self.tipo_conhecimento == "f":
n_desenvolvimento_atual = 2
if pessoa.Ideologia() == "militar" and self.tipo_conhecimento == "m":
n_desenvolvimento_atual = 2
# quantidade para desenvolver conhecimento
n_desenvolvimento = n_desenvolvimento + n_desenvolvimento_atual
# quando X for igual taxa de desenvolvimento devo sair
# da pra salvar o X e continuar de onde parou na proxima, chegando no maximo eu preciso voltar pro 0, nao vou fazer agora por preguica
x = x + 1
if x == taxa_desenvolvimento_anual:
break
# se o n_desen for maior que a diferenca entre o ultimo elemento da lista e 0
# n_desen fica como a diferenca
if (self.lista_conhecimento[-1] - n_desenvolvimento) < 0:
n_desenvolvimento = abs(0 - self.lista_conhecimento[-1])
# n_desen = diferenca entre o ultimo elemento da lista e n_desen antigo
n_desenvolvimento = self.lista_conhecimento[-1] - n_desenvolvimento
self.lista_conhecimento.append(n_desenvolvimento)
# se desenvolveu tudo, player ganha numero de pontos igual ao valor inicial do conhecimento (dificiuldade do memso)
if n_desenvolvimento == 0:
player.AddPontos(self.lista_conhecimento[0])
def ExibirDados(self):
print("Tipo do conhecimento: {}".format(self.tipo_conhecimento))
print("Quantidade de RU: {}".format(self.n_ru))
print("Representacao do conhecimento: {}".format(self.lista_conhecimento))
|
e9ea1f7ac35a2886804f577291d0c070e7e127b5 | garyblocks/leetcode | /round1/22_GenerateParentheses.py | 777 | 3.5625 | 4 | class Solution(object):
def add(self,out,n,check,num,s,p,left,right):
if p=='(':
s+=p; check-=1; num+=1; left-=1
elif check<0:
s+=p; check+=1; num+=1; right-=1
else:
return None
if num<2*n:
if left>0:
self.add(out,n,check,num,s,'(',left,right)
if right>0:
self.add(out,n,check,num,s,')',left,right)
else:
out.append(s)
def generateParenthesis(self, n):
out = []
check = 0
num = 0
left, right = n,n
s = ''
self.add(out,n,check,num,s,'(',left,right)
return out
"""
:type n: int
:rtype: List[str]
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.