blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ec1ee8c046176956d28e9377c7963c531065714e | briansegs/narrow-valley | /narrow_valley.py | 25,509 | 3.671875 | 4 | import time
import random
# <--------------- Basic Functions --------------->
def coin_flip():
return random.choice(['heads', 'tails'])
def die_roll():
return random.randint(1, 6)
def time_print(string):
# test_speed = .5
play_speed = 2
print(string)
time.sleep(play_speed)
def time_print_loop(lst):
for element in lst:
time_print(element)
def time_print_img(lst):
# test_speed = .2
play_speed = .5
for element in lst:
print(element)
time.sleep(play_speed)
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 in response:
return option1
if option2 in response:
return option2
time_print("I don't understand.")
def continue_on():
input("Press (enter) to continue.\n")
# <--------------- Fight System --------------->
def intro_fight():
time_print('You are both still, waiting for the right time to make your'
' move, and then...\n')
def choose_stats(game_data):
opt1 = {
'boss_hp': 18,
'player_hp': 20,
'boss_name': 'Elijah'
}
opt2 = {
'boss_hp': 20,
'player_hp': 18,
'boss_name': 'Clover'
}
if game_data['bag'] == '*Primal Command*':
game_data.update(opt1)
else:
game_data.update(opt2)
return game_data
def play_again():
time_print("Would you like to play again?")
replay = valid_input("(1) Yes\n(2) No\n", "1", "2")
if replay == "1":
play()
elif replay == "2":
time_print("Ok, thanks for playing!")
# Prints an image that says Game Over in ascii
lst = [
"",
" ,----. ,-----. ",
"' .-./ ,--,--.,--,--,--. ,---. "
" ' .-. ',--. ,--.,---. ,--.--. ",
"| | .---.' ,-. || || .-. : "
" | | | | \\ `' /| .-. :| .--' ",
"' '--' |\\ '-' || | | |\\ --. "
" ' '-' ' \\ / \\ --.| | ",
" `------' `--`--'`--`--`--' `----' "
" `-----' `--' `----'`--' ",
""
]
time_print_img(lst)
# <----- Fight Flow ----->
def pick_who_attacks(game_data):
result = coin_flip()
if result == 'heads':
player_turn(game_data)
elif result == 'tails':
boss_turn(game_data)
# <-------------------- Boss Functions -------------------->
def dont_run(game_data):
lst = [
"I will not give up!",
"I'm not done yet!",
"That won't stop me!",
"I can do this!",
"I'm not afraid!"
]
time_print(f'''({game_data['player_name']}) "{random.choice(lst)}"\n''')
pick_who_attacks(game_data)
def run(game_data):
lst = [
f"{game_data['player_name']} runs from {game_data['boss_name']}.",
"You live to fight another day.",
f"{game_data['player_name']} returns to town.",
""
]
time_print_loop(lst)
town(game_data)
def clover_attack_shout(boss_name):
lst = [
f"{boss_name} thrust her hands out toward you and shouts"
" *Primal Command*!, as a torrent of earth, hail, and flames"
" crash into you.",
f"{boss_name} shouts *Primal Command*! as a mass of stones,"
" embers, and icy shards tornado around you, striking you"
" from every side.",
f"{boss_name} shouts *Primal Command*! and blast you with a"
" tempest infused with firey ash, molten rock, and blistering steam."
]
time_print(random.choice(lst))
def clover_attacks(game_data):
dmg = die_roll() + die_roll()
game_data['player_hp'] -= dmg
clover_attack_shout(game_data['boss_name'])
lst = [
"",
f"{game_data['boss_name']} hits you for {dmg} damage.",
f"your health is now at {game_data['player_hp']}",
""
]
time_print_loop(lst)
def elijah_attack_shout(boss_name):
lst = [
f"{boss_name} shouts *Banishing Light*! as a massive beam"
" of light strikes you from the sky.",
f"Dark clouds part as {boss_name} shouts *Banishing Light*!"
" and a column of light blasts you from above.",
f"{boss_name} chops his hand downward and shouts *Banishing"
" Light*! as a pillar of light collides with you."
]
time_print(random.choice(lst))
def elijah_attacks(game_data):
dmg = (die_roll() * 2) + 1
game_data['player_hp'] -= dmg
elijah_attack_shout(game_data['boss_name'])
lst = [
"",
f"{game_data['boss_name']} hits you for {dmg} damage.",
f"your health is now at {game_data['player_hp']}",
""
]
time_print_loop(lst)
def boss_turn(game_data):
if game_data['boss_name'] == 'Clover':
clover_attacks(game_data)
else:
elijah_attacks(game_data)
if game_data['player_hp'] > 0:
answer = valid_input('Continue fighting or run away?\n(1) Fight\n(2)'
' Run\n', '1', '2')
if answer == "1":
dont_run(game_data)
elif answer == "2":
run(game_data)
else:
time_print('You have died!')
play_again()
# <-------------------- Player Functions -------------------->
def player_attack_shout(player_name, boss_name, special_item):
lst = [
f"{player_name} bolts toward {boss_name}, shouting"
f" {special_item}!, and rams {boss_name} with a punishing strike.",
f"With outstretched arms and palms aimed at {boss_name},"
f" {player_name} shouts {special_item}! and hammers"
f" {boss_name} with a powerful blow.",
f"Shouting {special_item}!, {player_name} releases a mighty"
f" force that smashes {boss_name}."
]
time_print(random.choice(lst))
def player_attack(game_data):
if game_data['boss_name'] == 'Clover':
dmg = (die_roll() * 2) + 1
else:
dmg = die_roll() + die_roll()
game_data['boss_hp'] -= dmg
player_attack_shout(game_data['player_name'],
game_data['boss_name'], game_data['bag'])
lst = [
"",
f"You hit {game_data['boss_name']} for {dmg} damage points.",
f"{game_data['boss_name']}'s health is now at {game_data['boss_hp']}",
""
]
time_print_loop(lst)
continue_on()
def boss_taunt(boss_name):
taunts = [
"Not bad!",
"Just a scratch!",
"You're going to pay for that!",
"That made me angry!",
"That won't happen again!"
]
time_print(f'''({boss_name}) "{random.choice(taunts)}"\n''')
def winner_endings(boss_name, special_item):
time_print('You have Won!')
if boss_name == 'Elijah':
lst = [
"Keeping your promise to Clover, you made the world safe from"
" Elijah and his menacing.",
"A new journey is in front of you.",
f"Good people might need your assistance and the power"
f" of {special_item}.",
"You leave the narrow valley, never to return.",
""
]
time_print_loop(lst)
elif boss_name == 'Clover':
lst = [
"You have completed the task given to you by Elijah and"
" dispatched Clover.",
"Attainment of *Primal Command* doubles your power and desire"
" for more.",
"You return to Elijah and plot with him to find more prey.",
"You two leave the narrow valley, never to return.",
""
]
time_print_loop(lst)
def player_turn(game_data):
player_attack(game_data)
if game_data['boss_hp'] > 0:
boss_taunt(game_data['boss_name'])
pick_who_attacks(game_data)
else:
winner_endings(game_data['boss_name'], game_data['bag'])
play_again()
# <----- Fight ----->
def fight(game_data):
intro_fight()
pick_who_attacks(choose_stats(game_data))
# <--------------- Story --------------->
def title(): # Says Narrow Valley in ascii
lst = [
" ,--.",
" ,--.'| "
" ,--, ,--,",
" ,--,: : | "
" ,---. ,--.'| ,--.'|",
",`--.'`| ' : __ ,-. __ ,-. ,---. .---. "
" /__./| | | : | | :",
"| : : | | ,' ,'/ /|,' ,'/ /| ' ,'\\ /. ./| "
" ,---.; ; | : : ' : : '",
": | \\ | : ,--.--. ' | |' |' | |' | / / | .-'-. ' | "
" /___/ \\ | | ,--.--. | ' | | ' | ,---. .--,",
"| : ' '; | / \\ | | ,'| | ,'. ; ,. : /___/ \\: | "
" \\ ; \\ ' | / \\ ' | | ' | | / \\ "
" /_ ./|",
"' ' ;. ;.--. .-. |' : / ' : / ' | |: : .-'.. ' ' . "
" \\ \\ \\: | .--. .-. || | : | | : "
" / / |, ' , ' :",
"| | | \\ | \\__\\/: . .| | ' | | ' ' "
" | .; :/___/ \\: ' "
" ; \\ ' . \\__\\/: . .' : |__' : |__ . "
" ' / /___/ \\: |",
"' : | ; .' ,' .--.; |; : | ; : | | "
" : |. \\ ' .\\ | "
" \\ \\ ' ,' .--.; || | '.'| | '.'|' "
" ; /|. \\ ' |",
"| | '`--' / / ,. || , ; | , ; "
" \\ \\ / \\ \\ ' \\ | "
" \\ ` ; / / ,. |; : ; : "
" ;' | / | \\ ; :",
"' : | ; : .' \\---' ---' `----' \\ \\ |--' "
" : \\ |; : .' \\ , /| , "
" / | : | \\ \\ ;",
"; |.' | , .-./ "
" \\ \\ | "
" '---' | , .-./---`-' ---`-' "
" \\ \\ / : \\ \\ ",
"'---' `--`---' '---' "
" `--`---' "
" `----' \\ ' ;",
" "
" `--`",
]
time_print_img(lst)
def get_name(game_data):
game_data['player_name'] = input("To start enter your name\n")
return game_data
def intro_story():
lst = [
"A brave warrior wanders the world in search of great power.",
"Their journey leads them to two sacred mountains divided by a"
" village in a narrow valley.",
]
time_print_loop(lst)
# Prints an image of Narrow Valley in ascii
lst = [
" __ /\\ ",
" / \\ / \\_ /\\__ ",
" / \\ /\\ / \\ _/ / \\ ",
" /\\/\\ /\\/ :' __ \\_ _ / ^/_ `--.",
" / \\/ \\ _/ \\-'\\ / ^ _ \\_ ^ .'\\ ",
" /\\ .- `. \\/ \\ /''' `._ _/ \\ ^ `_/ \\_",
" / `-.__ ` / .-'.--\\ ''' / ^ `--./ .-' `- ^",
"/ `. / / `.''' .-' ^ '-._ `._ `-",
" ''' "
]
time_print_img(lst)
lst = [
"At the peak of each holy mountain a great master resides.",
"One has conquered the forces of nature.",
"The other manipulates spiritual energy.",
""
]
time_print_loop(lst)
continue_on()
# Prints an image of village inn in ascii
lst = [
" ) _ / \\ ",
" /\\ ( _ _._ / \\ /^ \\ ",
"\\ / \\ |_|-'_~_`-._/ ^ \\ / ^^ \\ ",
" \\ /\\/\\_.-'-_~_-~_-~-_`-._^/ ^ \\ ",
" _.-'_~-_~-_-~-_~_~-_~-_`-._ ^ ",
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",
" | [ ] [ ] [ ] [ ] |",
" | ___ __ ___ | ",
" | [___] | .| [___] | <inn>",
" |________ |__| _______| |",
"^^^^^^^^^^^^^^^ === ^^^^^^^^^^^^^|^^ ",
" ^^^^^ === ^^^^^^ ^^^ "
]
time_print_img(lst)
lst = [
"After a much-needed rest at the village inn, our hero sets out.",
""
]
time_print_loop(lst)
def get_location(player_name):
lst = [
f"What do you want to do {player_name}?",
"(1) Traverse the wooded mountain to the east.",
"(2) Hike the snow-covered mountain to the west."
]
time_print_loop(lst)
number = input("(3) Check bag.\n")
return number
def check_bag(game_data):
time_print(f"You have {game_data['bag']} in your bag.\n")
town(game_data)
# <----- Story Flow ----->
def town(game_data):
choice = get_location(game_data['player_name'])
if choice == '1':
clover(game_data)
elif choice == '2':
elijah(game_data)
elif choice == '3':
check_bag(game_data)
else:
town(game_data)
# <-------------------- Clover Functions -------------------->
def print_clover_house(): # Prints an image of Clover's house in ascii
lst = [
" "
" / \\ . ~ /\\ `",
" ~ /\\ . /\\ "
" / \\ /`-\\ ",
" / \\ ` /\\ "
" /^ \\/ ^ \\ /\\ * / ^ \\ .",
" . / ^ \\ / ^\\ "
" / ^/ ^ ) \\ /^ \\ / ^ ^ \\ ",
" /` \\ ` / ^ \\/^ ^/^ ( "
" \\ / ^ \\ / ^ \\ ",
" / ^ \\~ / ^ / ^/ ^ ^ ) ) ^ "
" \\/ ^^ \\ / ^ `_\\ ",
" /^ ^ ` \\ / ^ ^ ^ / ^ ( ( ^ "
" / ^ ^ \\/` ^ \\ ",
" / ^ ^ \\ / ^ ^ ^^ / ^ (____) ^ / "
" ^ / ^ ^ ^ \\ ",
" /` ^ ^ ^ \\ ^ ^ ______|__|_____^ ^ "
" / ^- ^ ^ \\ ",
" / `' ^ `-\\ ^ /_______________\\ ^ ^ "
" / ^ `` `- \\ ",
"/ ^ ^^ ^ ^\\^ /_________________\\ ^ / "
" ^ ^^ ^ \\ ",
" -^ ^ ^ ^^- ^ \\^ ^ |||||| |||__||| /`- ^ ^ ^^^ "
" ^^- \\ ",
" | | ||||||I |||__||| "
" | | ",
"||||||| [ ] |||||||||||||| ||||||___|||||||| |||||||||||| [ ]"
" |||||||||| ",
'""""""""""""""""""""""""""""""""===="""""""""""""""""""""""""'
'""""""""""""" ',
" |||||||||||||||||||||||||||=====|||||||||||||||||||||||||"
"||||||| "
]
time_print_img(lst)
def print_primal_command(): # Print an image of Primal Command in ascii
lst = [
" ... ",
" :::;(;::: ",
" .::;.) );:::::. ",
":::;`(,' (,;::::: ",
":::;;) .-. (';::: ",
":::;( ( * )'):;:: ",
"'::;`),'-' (;::' ",
" ':(____),_)::' ",
" |_______| ",
" \\_____/ ",
]
time_print_img(lst)
def clover_offer(player_name):
print_clover_house()
lst = [
"Clover, brown-haired and slender, with bright, dark eyes, comes out"
" to greet you.",
"She peers curiously into you, sensing your kind heart...",
""
]
time_print_loop(lst)
continue_on()
lst = [
f'''(Clover) "{player_name}, I am the master you seek."''',
'''(Clover) "Train under me and unearth the secrets only I and'''
''' Mother Nature know."''',
"",
"Will you accept her offer?"
]
time_print_loop(lst)
def clover_not_home(game_data):
lst = [
"Clover isn't home right now.",
"There doesn't seem to be much to do here.",
"You head back into town.",
""
]
time_print_loop(lst)
town(game_data)
def clover_fight(game_data):
print_clover_house()
lst = [
"Clover, brown-haired and slender, with bright, dark eyes, comes out"
" to greet you.",
f"She notices {game_data['bag']} in your possession and"
" understands why"
" you have come.",
""
]
time_print_loop(lst)
continue_on()
lst = [
'''(Clover) "I will not be intimidated by one of Elijah's'''
''' thugs!"''',
"Clover twirls her hands in the air, forming a bright green aura"
" around herself.",
""
]
time_print_loop(lst)
continue_on()
fight(game_data)
def clover_training(game_data):
lst = [
"For the next year, you apprentice yourself to Clover, cultivating"
" your skills.",
"You pick up that a man named Elijah has been trying to steal Clover's"
" power for many years.",
"You promise Clover that you will bring an end to Elijah's reign of"
" terror.",
"Clover is touched by your commitment.",
""
]
time_print_loop(lst)
continue_on()
lst = [
"To conclude your final day of training, Clover requests that you"
" meet her in front of her house.",
f'''(Clover) "{game_data['player_name']}, everything that you have'''
''' endured was to prepare you for this."''',
""
]
time_print_loop(lst)
continue_on()
print_primal_command()
lst = [
'''(Clover) "*Primal Command* is my greatest weapon and now it is'''
''' yours."''',
'''(Clover) "Remember your promise and good luck on your travels'''
f''' {game_data['player_name']}."''',
""
]
time_print_loop(lst)
game_data['bag'] = '*Primal Command*'
continue_on()
lst = [
"You receive *Primal Command!*",
"",
"With the training from Clover and the power of *Primal Command*, you"
" leave and head into town.",
""
]
time_print_loop(lst)
town(game_data)
def clover_turned_down(game_data):
lst = [
'''(Clover) "I hope you will reconsider my offer."''',
"You leave the small house and return to town.",
""
]
time_print_loop(lst)
town(game_data)
# <----- Clover Flow ----->
def clover(game_data):
time_print("You find yourself in front of a small wooden house surrounded"
" by tall grass and massive pine trees.")
if game_data['bag'] == '*Primal Command*':
clover_not_home(game_data)
elif game_data['bag'] == '*Banishing Light*':
clover_fight(game_data)
else:
clover_offer(game_data['player_name'])
answer = valid_input("(1) Yes\n(2) No\n", "1", "2")
if answer == "1":
clover_training(game_data)
elif answer == "2":
clover_turned_down(game_data)
# <-------------------- Elijah Functions -------------------->
def print_elijah_house(): # prints an image of Elijah's house in ascii
lst = [
" . . ( ) * *",
" * ) )",
" . ( ( . /\\ ",
" . (_) / \\ /\\ ",
" * * ___________[_]___________ /\\/ \\/ \\ ",
" /\\ /\\ * ______ * \\ "
" / /\\/\\ /\\/\\ ",
" / \\ //_\\ \\ /\\ \\ "
" /\\/\\/ \\/ \\ ",
" /\\ / /\\/\\ //___\\ * \\__/ \\ . "
" \\/ *",
" / \\ /\\/* \\//_____\\ \\ |[]| \\ ",
" /\\/\\/\\/ //_______\\ \\|__| \\ "
" .",
"/ __ \\ /XXXXXXXXXX\\ \\ __",
" / \\ \\ /_I_I___I__I_\\________________________\\ / \\ ",
" { () } I_I I__I_________[]_|_[]_________I ( () )",
" ( ) /\\ I_II I__I_________[]_|_[]_________I ( )",
" [] ( ) I I___I I XXXXXXX /\\ I []",
" ~~~[] ~~[] ~~~~~____~~~~~~~~~~~~~~~~~~~~~~~{ }~~~~~~~~~~[] ~~~~~",
" ~~~~~~_____~~~~~~~~~~~~~~~~~~~~~~~~[] ~~~~~~~~~"
]
time_print_img(lst)
def print_banishing_light(): # Prints an image of banishing light in ascii
lst = [
" ( ",
" ) )\\( . ",
" (( `.((_)) )) ",
"( ),\\`.' `-',' ",
" `.) /\\ (,') ",
" ,', ( ) '._,) ",
"(( ) '' (`--' ",
" `'( ) _--_,-.\\ ' ",
" ' /,' \\( )) `') ",
" ( `\\( ",
" ) ",
""
]
time_print_img(lst)
def elijah_offer(player_name):
print_elijah_house()
lst = [
"Elijah, tall with powerful shoulders, and fierce blue eyes, comes"
" out to greet you.",
"He sizes you up, feeling your desire for power...",
""
]
time_print_loop(lst)
continue_on()
lst = [
f'''(Elijah) "{player_name}, I am the master you seek."''',
'''(Elijah) "Take my guidance and uncover the limitless potential'''
''' of the spirit realm."''',
"",
"Will you accept his offer?"
]
time_print_loop(lst)
def elijah_not_home(game_data):
lst = [
"Elijah isn't home right now.",
"There doesn't seem to be much to do here.",
"You head back into town.",
""
]
time_print_loop(lst)
town(game_data)
def elijah_fight(game_data):
print_elijah_house()
lst = [
"Elijah, tall with powerful shoulders, and fierce blue eyes, comes"
" out to greet you.",
"He smiles at you and begins to form a bright red aura around"
" himself as he notices you"
f" possess {game_data['bag']}.",
""
]
time_print_loop(lst)
continue_on()
lst = [
f'''(Elijah) "I crave the power of {game_data['bag']} '''
'''and I will crush you to obtain it!"''',
"Elijah gets into a fighting stance.",
""
]
time_print_loop(lst)
continue_on()
fight(game_data)
def elijah_training(game_data):
lst = [
"For the next year, you memorize every mystical technique offered to"
" you by Elijah.",
"Elijah shares his desire to increase his capabilities by defeating"
" other masters and taking their power.",
"He wants you to assist him and share the bounty, both of you becoming"
" all-powerful.",
"Elijah feels that with you, his dreams can be realized.",
""
]
time_print_loop(lst)
continue_on()
lst = [
"To conclude your final day of training, Elijah requests that you meet"
" him in front of his house.",
f'''(Elijah) "{game_data['player_name']}, everything that you have'''
''' encountered has prepared you for this."''',
""
]
time_print_loop(lst)
continue_on()
print_banishing_light()
lst = [
'''(Elijah) "*Banishing Light* is my greatest technique and now it '''
'''is yours."''',
f'''(Elijah) "{game_data['player_name']}, I want you to'''
''' defeat a master'''
''' named Clover to the east and take her power.''',
'''(Elijah) "Leave now and only return when you have completed your'''
''' mission."''',
""
]
time_print_loop(lst)
continue_on()
game_data['bag'] = '*Banishing Light*'
lst = [
"You receive *Banishing Light*",
"",
"With the training from Elijah and the power of *Banishing Light*, you"
" leave and head into town.",
""
]
time_print_loop(lst)
town(game_data)
def elijah_turned_down(game_data):
lst = [
'''(Elijah) "I hope you will reconsider my offer." ''',
"You leave the sizable log cabin and return to town.",
""
]
time_print_loop(lst)
town(game_data)
# <----- Elijah Flow ----->
def elijah(game_data):
time_print("You find yourself in front of a sizable log cabin surrounded"
" by odd stone sculptures, both covered in snow.")
if game_data['bag'] == '*Banishing Light*':
elijah_not_home(game_data)
elif game_data['bag'] == '*Primal Command*':
elijah_fight(game_data)
else:
elijah_offer(game_data['player_name'])
answer = valid_input("(1) Yes\n(2) No\n", "1", "2")
if answer == "1":
elijah_training(game_data)
elif answer == "2":
elijah_turned_down(game_data)
# <----- Game Play / game_data ----->
# game_data holds important stats for the game.
def play():
game_data = {
'bag': 'dust and a few crumbs',
'player_name': None,
'boss_hp': None,
'player_hp': None,
'boss_name': None
}
title()
get_name(game_data)
intro_story()
town(game_data)
# <----- Play ----->
if __name__ == "__main__":
play()
|
3b91717e1ba451ad21c386ccb593b4a1e1cd918f | shankarkrishnamurthy/problem-solving | /coinchange.py | 2,179 | 3.53125 | 4 | class Solution(object):
def __init__(self):
self.mall = -1
def coinChange1(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
def do_cc(c, a, anc):
if a == 0:
self.mall = min(self.mall, len(anc))
print anc
return
if len(c)==0:
return
for i in range(len(c)):
cnt = 1
while c[i]*cnt <= a:
do_cc(c[:i]+c[i+1:], a-c[i]*cnt, anc + [c[i]]*cnt)
cnt += 1
self.mall = amount + 1
do_cc(coins, amount, [])
return self.mall if self.mall < amount+1 else -1
def coinChange2(self, coins, sum):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [ sum+1 for x in range(sum+1) ]
dp[0] = 0
for s in range(1,sum+1):
for k in coins:
cnt = 1
#while cnt*k <= s:
if cnt*k <= s:
dp[s] = min(dp[s], cnt + dp[s-cnt*k])
cnt += 1
return dp[sum] if dp[sum] < sum+1 else -1
def coinChange(self,coins,sum):
print coins, " ", sum
visited = [False]*sum
if sum == 0: return 0
queue = set([sum])
cnt = 0
while True:
cnt += 1
temp = set()
for s in queue:
for i in coins:
if s-i == 0:
return cnt
if s < i :
continue
if visited[s-i]:
continue
temp.add(s-i)
visited[s-i] = True
queue = temp
if not temp:
return -1
print Solution().coinChange([1, 2, 5], 11)
print Solution().coinChange([3,7,405,436],8839)
print Solution().coinChange([2], 5)
print Solution().coinChange([1], 0)
print Solution().coinChange([27,352,421,198,317,110,461,31,264],5303)
print Solution().coinChange([125,146,125,252,226,25,24,308,50],8402)
|
983349baeefec6ecedc3f8c63e8c51fbc3983e18 | AntonioCenteno/Miscelanea_002_Python | /Certámenes resueltos/Certamen 1 2014-2/pregunta3.py | 4,305 | 3.625 | 4 | #Las variables de control:
#Numero de ticket
num_ticket = 1
# Contadores de consultas de cada especialidad
consultas_cardiologia = 0
consultas_internista = 0
consultas_oncologia = 0
consultas_neurologia = 0
# Duraciones de las consultas de cada especialidad
duracion_cardio = 0
duracion_inter = 0
duracion_onco = 0
duracion_neuro = 0
# Hora de atencion de las distintas especialidades
hora_atencion_cardio = '08:00'
hora_atencion_onco = '08:00'
hora_atencion_inter = '08:00'
hora_atencion_neuro = '08:00'
while True: #Repetimos esta cosa de forma indefinida...
nombre_paciente = raw_input("Paciente: ")
#Si el nombre esta vacio, llegamos hasta aca
if nombre_paciente == "": break
especialidad = raw_input("Especialidad: ")
print "Ticket: ", num_ticket
num_ticket += 1
if especialidad == "Cardiologia":
#Agregamos una consulta a la cuenta
consultas_cardiologia += 1
print "Hora de atencion (aprox):", hora_atencion_cardio
if hora_atencion_cardio >= '12:00': #Si la espera es muy larga...
print "La paciencia es amarga, pero sus frutos son dulces"
# Actualizamos la hora de atencion
hora = int(hora_atencion_cardio[:2])
minuto = int(hora_atencion_cardio[3:])
hora += 1
if hora < 10:
hora_atencion_cardio = "0"+str(hora)+":"+str(minuto)
else:
hora_atencion_cardio = str(hora)+":"+str(minuto)
# Los pasos siguientes son los mismos que en Cardiologia, pero
# con la especialidad correspondiente.
elif especialidad == "Internista":
#Agregamos una consulta a la cuenta
consultas_internista += 1
print "Hora de atencion (aprox):", hora_atencion_inter
# Actualizamos la hora de atencion
hora = int(hora_atencion_inter[:2])
minuto = int(hora_atencion_inter[3:])
hora += 1
if hora < 10:
hora_atencion_inter = "0"+str(hora)+":"+str(minuto)
else:
hora_atencion_inter = str(hora)+":"+str(minuto)
if especialidad == "Oncologia":
#Agregamos una consulta a la cuenta
consultas_oncologia += 1
print "Hora de atencion (aprox):", hora_atencion_onco
# Actualizamos la hora de atencion
hora = int(hora_atencion_onco[:2])
minuto = int(hora_atencion_onco[3:])
hora += 1
if hora < 10:
hora_atencion_onco = "0"+str(hora)+":"+str(minuto)
else:
hora_atencion_onco = str(hora)+":"+str(minuto)
if especialidad == "Neurologia":
#Agregamos una consulta a la cuenta
consultas_neurologia += 1
print "Hora de atencion (aprox):", hora_atencion_neuro
# Actualizamos la hora de atencion
hora = int(hora_atencion_neuro[:2])
minuto = int(hora_atencion_neuro[3:])
hora += 1
if hora < 10:
hora_atencion_neuro = "0"+str(hora)+":"+str(minuto)
else:
hora_atencion_neuro = str(hora)+":"+str(minuto)
# Ahora, tenemos que ver que especialidad tiene la mayor cantidad de especialistas
mayor_atencion = max(consultas_neurologia, consultas_oncologia, consultas_internista, consultas_cardiologia)
menor_atencion = min(consultas_neurologia, consultas_oncologia, consultas_internista, consultas_cardiologia)
if mayor_atencion == consultas_cardiologia: especialidad_mayor = "Cardiologia"
elif mayor_atencion == consultas_neurologia: especialidad_mayor = "Neurologia"
elif mayor_atencion == consultas_oncologia: especialidad_mayor = "Oncologia"
elif mayor_atencion == consultas_internista: especialidad_mayor = "Internista"
if menor_atencion == consultas_cardiologia:
especialidad_menor = "Cardiologia"
hora_menor = hora_atencion_cardio
if menor_atencion == consultas_neurologia:
especialidad_menor = "Neurologia"
hora_menor = hora_atencion_neuro
if menor_atencion == consultas_oncologia:
especialidad_menor = "Oncologia"
hora_menor = hora_atencion_onco
if menor_atencion == consultas_internista:
especialidad_menor = "Internista"
hora_menor = hora_atencion_inter
# Ahora, imprimimos todos los datos.
print especialidad_mayor, "es la especialidad con mas pacientes"
print especialidad_menor, "sale a las", hora_menor |
7eff541cd38cd9420eda9c79882a8e44ab9a6a4f | tsupei/leetcode | /python/35.py | 721 | 3.8125 | 4 | class Solution(object):
def binary_search(self, nums, target, offset):
print(nums)
if not nums:
return offset
mid = len(nums) // 2
if nums[mid] < target:
return self.binary_search(nums[mid+1:], target, offset+mid+1)
elif nums[mid] > target:
return self.binary_search(nums[:mid], target, offset)
else:
return offset + mid
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return self.binary_search(nums,target,0)
if __name__ == "__main__":
sol = Solution()
ans = sol.searchInsert([1,3,5,6], 2)
print(ans) |
4059c6f18625b8042e7b0d75f0a27a9d182f1437 | CarloSegat/finalYearProject | /loss.py | 2,440 | 3.53125 | 4 | import sklearn
from keras import backend as K
from keras.backend import categorical_crossentropy
import tensorflow as tf
def weighted_categorical_crossentropy(weights):
"""
A weighted version of keras.objectives.categorical_crossentropy
This lets you apply a weight to unbalanced classes.
Variables:
weights: numpy array of shape (C,) where C is the number of classes
Usage:
weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x.
loss.py = weighted_categorical_crossentropy(weights)
model.compile(loss.py=loss.py,optimizer='adam')
We pick the cross-entropy as the loss function, and we weight it by the inverse
frequency of the true classes to counteract the imbalanced dataset.
y_pred = [[0.135464132 0.261906356 0.602629542]...]
y_true = [[1 0 0]...]
"""
weights = K.variable(weights)
def loss(y_true, y_pred):
# scale predictions so that the class probas of each sample sum to 1
y_pred /= K.sum(y_pred, axis=-1, keepdims=True)
# clip to prevent NaN's and Inf's
y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())
#y_true = K.print_tensor(y_true, message='y_true = ')
loss = y_true * K.log(y_pred) * weights
loss = -K.sum(loss, -1)
return loss
return loss
def f1_score(true,pred):
pred = K.cast(K.greater(pred,0.5), K.floatx())
groundPositives = K.sum(true) + K.epsilon()
correctPositives = K.sum(true * pred) + K.epsilon()
predictedPositives = K.sum(pred) + K.epsilon()
precision = correctPositives / predictedPositives
recall = correctPositives / groundPositives
m = (2 * precision * recall) / (precision + recall)
return m
def micro_f1(y_true, y_pred):
'''
https://www.kaggle.com/guglielmocamporese/macro-f1-score-keras
'''
return sklearn.metrics.f1_score(y_true, y_pred, average='micro')
def cat_crossentropy_from_logit(target, output,):
return categorical_crossentropy(target, output, from_logits=True)
def focal_loss(y_true, y_pred):
gamma = 2.0
alpha = 0.25
pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
return -K.sum(alpha * K.pow(1. - pt_1, gamma)
* K.log(pt_1))-K.sum((1-alpha)
* K.pow( pt_0, gamma) * K.log(1. - pt_0))
|
16cddb40c64193d6acb98c32701cd5194152296c | achoudh5/PythonBasics | /42.py | 377 | 3.53125 | 4 | import random
from random import shuffle
import zlib
import sys
import timeit
import collections
class Circle:
def rec(self):
list= [12, 24, 35, 24, 88, 120, 155, 88, 120, 155]
b=[]
print [b.append(i) for i in list if i not in b]
print b
def main():
l = Circle()
# j=NewYorker()
l.rec()
if __name__=="__main__":
main() |
0ca0ffaee2e6ee4a6846f98f36c4609c3f9772ec | aaditya-patil-0018/Excel-to-csv-converter | /main.py | 690 | 3.90625 | 4 | import pandas as pd
import csv
xlFileName = str(input('Enter name for Excel file : '))
try:
xlFile = pd.read_excel(f"{xlFileName}.xls")
except FileNotFoundError:
print('Excel file not found!')
quit()
for i in xlFile:
if 'Unnamed' in i:
xlFile.drop(i, axis=True, inplace=True)
rows = xlFile.shape[0]
columns = xlFile.shape[1]
csvFileName = str(input('Enter name for csv file : '))
csvFile = f"{csvFileName}.csv"
for i in range(int(rows)):
r = xlFile.iloc[i]
with open(csvFile, 'a') as cf:
c_writer = csv.writer(cf)
if i == 0:
c_writer.writerow(xlFile.columns)
c_writer.writerow(r)
#print('Script ran Successfully')
|
7981882a342b6bf18bae32c748790689cdd45c3a | nicky-code/password | /credentials_test.py | 3,443 | 3.828125 | 4 | import unittest
from credentials import Credentials
import pyperclip
class TestCredentials(unittest.TestCase):
'''
Test class that defines test cases for the credentials class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
#Items up here....
def setUp(self):
'''
Set up method to ru before each test cases.
'''
self.new_credentials = Credentials("Nicole","Facebook","Nicky","aline.nicole7@gmail.com","virgo7")
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_credentials.accountName,"Nicole")
self.assertEqual(self.new_credentials.siteName,"Facebook")
self.assertEqual(self.new_credentials.username,"Nicky")
self.assertEqual(self.new_credentials.email,"aline.nicole7@gmail.com")
self.assertEqual(self.new_credentials.password,"virgo7")
def test_save_credentials(self):
'''
test_save_credentials test case to test if the credentials object is saved into the credentials list
'''
self.new_credentials.save_credentials() #saving the new credentials
self.assertEqual(len(Credentials.Credentials_list),1)
#setup and class creation up here
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
Credentials.Credentials_list = []
#other test cases here
def test_save_multiple_credentials(self):
'''
test_save_multiple_credentials to check if we can save multiple credentials objects to our Credentials_list
'''
self.new_credentials.save_credentials()
test_credentials = Credentials("Jessica","Instagram","Jessy","jessy7@gmail.com","great7") #new credentilas
test_credentials.save_credentials()
credentials_exists = Credentials.credentials_exists("jessy7@gmail.com")
self.assertTrue(credentials_exists)
found_credentials = Credentials.find_by_email("jessy7@gmail.com")
self.assertEqual(found_credentials.username,test_credentials.username)
self.new_credentials.delete_credentials() #deleting credentials object
self.assertEqual(len(Credentials.Credentials_list),1)
#more tests above
def test_delete_credentials(self):
'''
test_delete_credentials to test if we can remove an credentials from our Credentials list
'''
def test_find_credentials_by_email(self):
'''
test to check if we can find the credentials by email and display information
'''
def test_credentials_exists(self):
'''
test to check if we can return a Boolean if we cannot find the credentials.
'''
def test_display_credential(self):
'''
method that retuns a list of all credential saved
'''
self.assertEqual(Credentials.display_credential(),Credentials.Credentials_list)
def test_copy_email(self):
'''
Test to confirm that we are copying the email address from a found credentials
'''
self.new_credentials.save_credentials()
Credentials.copy_email("aline.nicole7@gmail.com")
self.assertEqual(self.new_credentials.email,pyperclip.paste())
if __name__ == '__main__':
unittest.main()
|
3c607d7022ea433924111f8a30b75ea5cd2463a3 | vnallani259/VenkyPhython | /Python_Practice/math.py | 400 | 3.828125 | 4 | from math import sqrt, sin, cos, pi
p_x = 100
p_y = 0
radians = 10 * pi/180
COS10 = cos(radians)
SIN10 = sin(radians)
x, y = eval(input("Enter initial satellite coordinates (x,y):"))
d1 = sqrt((p_x - x)*(p_x - x) + (p_y - y)*(p_y - y))
x_old = x;
x = x*COS10 - y*SIN10
y = x_old*SIN10 + y*COS10
d2 = sqrt((p_x - x)*(p_x - x) + (p_y - y)*(p_y - y))
print("Difference in distances: %.3f" % (d2 - d1))
|
9f0c93f4c290be09b1c516d68759ffbe62db18ca | ynjacobs/Object-Oriented-Programming-Bank-Account | /exercise1.py | 1,247 | 3.890625 | 4 | class BankAccount:
def __init__(self, balance, interest_rate):
self.balance = balance
self.interest_rate = interest_rate
def __str__(self):
return "your balance is {} and the interest rate is {}".format(self.balance, self.interest_rate)
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
def gain_interest(self):
self.balance = (( self.interest_rate / 100 ) * self.balance) + self.balance
return self.balance
my_account = BankAccount( 80000, 1.1)
print(my_account.balance)
my_account = BankAccount( 180000, 1.1)
print(my_account.balance)
my_account = BankAccount( 280000, 1.1)
print(my_account.balance)
# my_account.deposit(3)
new_balance = my_account.deposit(3)
print(new_balance)
new_balance = my_account.withdraw(4)
print(new_balance)
new_balance = my_account.gain_interest()
print(new_balance)
my_other_account = BankAccount(45000, 1.2)
balance = my_other_account.deposit(100)
print(balance, my_other_account)
my_other_account.withdraw(300)
print(balance, my_other_account)
my_other_account.gain_interest()
print(balance, my_other_account)
|
b10f079d25c59094ddbdeb1f4f5cfc3c80442c6d | ramkishorem/pythonic | /session5_function_module/01.py | 1,131 | 4.71875 | 5 | """
Functions: The buildup
Remember this part of code that we used at various places
for key,value in details.items():
print('{:20}: {:20}'.format(key.title(),str(value)))
We used this to print info inside a dictionary in a pretty form.
It is quite a complex-looking code. Ideally, we would like to
do something like print_dict(dictionary) and get this result
in the long run.
Let us see how to do it
"""
def print_dict(dictionary):
"""Prints a dictionary in a pretty format"""
for key,value in dictionary.items():
print('{:20}: {:20}'.format(key.title(),str(value)))
sanchez = {
'name': 'Alexis Sanchez',
'age': 29,
'country': 'Chile',
}
print_dict(sanchez)
# Output:
# Name : Alexis Sanchez
# Age : 29
# Country : Chile
favourite_language = {
'Charlotte': 'C',
'Merlin': 'Python',
'Fiona': 'Ruby',
'Eli': 'Python',
'Sara': 'JavaScript',
}
print_dict(favourite_language)
# Output:
# Charlotte : C
# Merlin : Python
# Fiona : Ruby
# Eli : Python
# Sara : JavaScript |
d7023c5e739eb28501a6e3adec254f455296e2a7 | crudalex/microsoft-r | /leetcode/sortList.py | 1,677 | 3.703125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
"""
:rtype: ListNode
:type x: int
"""
self.val = x
self.next = None
def add(self, x):
"""
:type x: int
"""
if self.val is None:
self.val = x
return
if self.next is None:
self.next = ListNode(x)
return
self.next.add(x)
return
@classmethod
def from_list(cls, l):
# noinspection PyTypeChecker
n = cls(None)
for i in l:
n.add(i)
return n
class Solution:
def sortList(self, head):
dummyNode = ListNode(0)
dummyNode.next = head
if head is not None:
self.qsortList(dummyNode, None)
return dummyNode.next
def qsortList(self, dummyNode, tail):
pNode = self.partion(dummyNode, tail)
if dummyNode.next != pNode:
self.qsortList(dummyNode, pNode)
if pNode.next != tail:
self.qsortList(pNode, tail)
def partion(self, dummyNode, tail):
pivot = dummyNode.next
fastPre = dummyNode.next
while fastPre.next != tail:
if fastPre.next.val < pivot.val:
tmp = fastPre.next
fastPre.next = tmp.next
tmp.next = dummyNode.next
dummyNode.next=tmp
else:
fastPre = fastPre.next
return pivot
if __name__ == '__main__':
s = Solution()
j = ListNode.from_list([4, 2, 1, 3])
k = ListNode.from_list([-1, 5, 3, 4, 0])
x = s.sortList(j)
y = s.sortList(k)
|
3095c1b1b8b847cf59213b5bf86c196c2ebbbe63 | JsRicardo/python-study | /basepy/numpy/juzhen.py | 756 | 3.5 | 4 | # -*- coding: utf-8 -*-
import numpy as np
mat = np.mat('1,2,3; 4,5,6') #传入字符串 用分号隔开,代表一个数组,生成一个矩阵
re = mat.reshape(2, 3) #将原数组的数字按照原来的顺序,重新生成一个2 * 3 的矩阵
mat.shape
n=mat.T # 转置 将原矩阵的轴进行旋转
n.shape
# 矩阵乘法
# 一个 3 * 2 的矩阵 和一个 2 * 3的矩阵相乘
# mat的第一行和n的每一列对应位置的数相乘在相加 生成结果的第一行
# mat的第二行和n的每一列对应位置的数相乘在相加 生成结果的第二行
mat * n
# 如果两个数据不是numpy 矩阵 可以用matmul进行矩阵相乘
a = np.random.randint(12, size=(3, 4))
c = np.random.randint(12, size=(4, 3))
np.matmul(a, c) |
9b14cff8043e9cfea63afee05fa857247853a4a7 | miyahara1005/miyahara1005_day02 | /sample09.py | 242 | 3.546875 | 4 | # if と for の組み合わせ
# 60点以上なら合格、60点未満なら不合格としたい
scores = [33, 70, 99, 10]
for score in scores:
if score >= 60:
print('合格')
if score <= 60:
print('不合格')
|
8321994023bbe8623ef1a3984d6b2efe4a1f5244 | thecodearrow/LeetCode-Python-Solutions | /Set Matrix Zeroes.py | 1,102 | 3.5 | 4 | #https://leetcode.com/problems/set-matrix-zeroes/submissions/
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
#Lazy Propagation Approach! (without extra space!)
N=len(matrix)
if(N==0):
return
first_row=False
first_col=False
M=len(matrix[0])
for i in range(N):
for j in range(M):
if(matrix[i][j]==0):
if(i==0):
first_row=True
if(j==0):
first_col=True
matrix[i][0]=0
matrix[0][j]=0
for i in range(1,N):
for j in range(1,M):
if(matrix[i][0]==0 or matrix[0][j]==0):
matrix[i][j]=0
#Check first row and first col to see if they need to be set
if(first_col):
for i in range(N):
matrix[i][0]=0
if(first_row):
for i in range(M):
matrix[0][i]=0
|
5383c81617ff97f59acabb1e94ddc27f6d64f9d7 | alexandraback/datacollection | /solutions_5634697451274240_1/Python/Astrae/QualifB.py | 3,423 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 09 05:16:47 2016
@author: Fred
"""
def qualifB(L):
# On va tenter cette strat :
# si ya que des + : fini
# sinon :
#si la liste commence par un -, on parcourt la liste jusqu'au dernier - et on
#flip jusque là (comme ça on a mis des + à la fin)
#si la liste commence par un +, on flip les premiers + jusqu'à tomber sur un -
k=len(L)-1
exit1=True
while exit1 and k>0:
if L[k]=='+':
k=k-1
else:
exit1=False
# donc en sortie, on peut tout retirer de la fin jusqu'à k
L=L[:k+1]
if len(L)==0: # on commence par une liste avec que des +
return 0
elif L=='-': # on enlève la liste de longueur 1 qui contient juste un '-' en tête
return 1
else:
n=0 # compteur de flip
while True:
signe=L[0]
if signe=='+':
k=1
exit=True
while exit and k<len(L):
if L[k]=='-':
exit=False
else:
k=k+1
if exit: # dans ce cas, on a que des + dans la liste
return n
else: # dans ce cas, on a trouvé un -, on flippe jusqu'à l'indice k
L=k*'-'+L[k:]
n=n+1
else: # dans ce cas, la liste commence par un -
# on ne garde alors que ce qui est entre le - et la fin car par de + à la fin
k=0
while k<len(L) and L[k]=='-':
k=k+1
if k==len(L): # autrement dit on a que des - dans la liste
return n+1 # car on flip une fois et c'est fini
else:
n=n+1
L=L[k:] # on efface les - en augmentant le compteur
L=L[::-1] # on flip
newword=''
for j in L:
if j=='-':
newword=newword+'+'
else:
newword=newword+'-'
L=newword
import numpy as np
def main(ifn='B-large.in',ofn='output.txt'):
with open(ifn) as inf: # ouvre l'input et le renomme en inf
with open(ofn,'w') as ouf: # crée l'output dans lequel on va écrire
noc = int(inf.readline().strip()) # permet de lire la 1ere ligne
# en général le nbr de cas
# le .strip() permet de virer les espace
for tnoc in range(noc): # boucle en fonction du nbr de cas
ouf.write("Case #%d: " %(tnoc+1)) # case dans laquelle on écrit en sortie
L=inf.readline().strip().split(' ')[0]
resultat=qualifB(L)
ouf.write("%d\n" %resultat)
|
0f263f51c9bc27a0b900a28194eb2952252720d2 | EthanLaurenceau89/Final_Project | /SFCrimeProjectCode.py | 9,671 | 3.859375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
CrimeData = pd.read_csv("SFCD_2018.csv")
def CrimeFunc(data): ## Function that will take in crime dataset.
return data.head() ## Use head command to retrieve first five rows of data, to get a sense of what the data looks like.
Crime_Count = CrimeData['Incident Description'].value_counts().head(20) #Retrieve the top 20 incindents from SF Crime dataset
def top20Incidents(data): # Function Constructs a DataFrame/table from top 20 crimes in San Francisco and the number of times they have occured.
Crime_df = pd.DataFrame(Crime_Count).reset_index()
Crime_df.columns = ["Crime", "Occurences"]
return Crime_df
def plottop20(crimecount): # Creates a bar plot, that shows each of top 20 crimes, vs. # of occurences.
sns.set_style("whitegrid")
plt.title("Occurences of Crimes in San Francisco")
crimecount.plot(kind='bar')
plt.show()
def plot_week_occurence(data): # Function will plot the total occurence of crimes from dataset by days of week.
CrimePerDay = pd.concat([data["Incident Day of Week"], data["Incident Description"]], axis = 1) # Create a table that lists Weekdays with the number of crime occurences. This is done by concatenating "Incident Day of the Week with the Incident Description".
CrimeDayCt = CrimePerDay["Incident Day of Week"].value_counts().reindex(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]) # What I do hear, is count how many times that the Weekday shows up in the Dataset, b/c this gives me how many crimes occured for each weekday.
print(CrimeDayCt)
plt.figure(figsize = (7,7)) # Plot the figure for the number of crimes that occur per weekday.
plt.title("Occurences of Crimes in San Francisco", fontstyle = "oblique", fontsize = 14)
CrimeDayCt.plot(kind = "bar", color = ['r','g','b','y', 'orange','purple', 'black'], fontsize = 13) #Set colors of bars for each weekday
plt.show()
def IncidentbyMonth(data):
# Retrieve the Month, Day, Hour for each of the incidents, and place construct respective column for them in the dataset.
data["Incident Date"] = pd.to_datetime(data["Incident Date"])
data['Incident Month'] = pd.DatetimeIndex(data['Incident Date']).month
data["Incident Date"] = pd.to_datetime(data["Incident Date"])
data['Incident Day'] = pd.DatetimeIndex(data['Incident Date']).day
data['Incident Hour'] = pd.DatetimeIndex(data['Incident Time']).hour
# Look at number of crimes for each month,, and then group them by the incident years which are 2018 and 2019.
Month_data = pd.DataFrame(data.groupby(["Incident Month"])["Incident Year"].value_counts())
Month_data.index = pd.MultiIndex.from_tuples([('Jan.', 2018), ('Jan.', 2019), ('Feb.', 2018), ('Feb.', 2019), ('Mar.', 2018), ('Mar.', 2019), ('Apr.', 2018), ('Apr.', 2019), ('May', 2018), ('May', 2019), ('Jun.', 2018), ('Jun.', 2019), ('Jul.', 2018), ('Jul.', 2019), ('Aug.', 2018), ('Sep.', 2018), ('Oct.', 2018), ('Nov.', 2018), ('Dec.', 2018)])
Month_data.columns = ["Incident Occurences"]
return Month_data
def plotIncidentbyMonth(data): #The plots the number of crimes for each month reported for 2018 and 2019
plt.title("Incident Occurenes in SF From 2018 - Jul. 1, 2019")
M = sns.countplot(data=data, x = "Incident Month", hue = "Incident Year")
M.set_xticklabels(['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.'])
M.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
def GetandPlotResolution(data): # This function will plot a pie chart from the Resolution for the Incidents documented in the Dataset.
Res_Vals = data["Resolution"].value_counts() # First it takes in the counts of the Resolution
print(Res_Vals)
# The below code is used to retrieve the districbution of the resolutions for the incidents in the dataset.
# These percentages will be used for the legend for my pie chart, they will be placed with names of the Resolutions to be plotted.
CrimeRes = pd.DataFrame()
CrimeRes["Resolution"] = list(Res_Vals.index)
CrimeRes["Occurence"] = list(Res_Vals)
CrimeRes["Percentages"] = (CrimeRes["Occurence"] / CrimeRes["Occurence"].sum() * 100).round(2)
CrimeRes["Percentages2"] = list(CrimeRes["Percentages"].astype(str))
CrimeRes["Res"] = CrimeRes["Resolution"] + " (" + CrimeRes["Percentages2"] + "%)"
# This code actually plots the piechart for the Resolutions of Crimes in San Franciso documented in the dataset with a legend.
plt.figure(figsize =(11,11))
plt.pie(list(CrimeRes["Percentages"]))
plt.title("Crime Resolutions in San Franciso", fontsize = 14)
plt.axes().set_ylabel('')
plt.legend(CrimeRes["Res"], loc='best')
plt.show()
# Now I'm in the stage of training my data and fitting a SVC model so that based on certain parameter which I will specify below, I can predict how the crime will be resolved.
# I'll import the modules from sklearn I'll need to train, fit, and retrieve the confusion matrix and classification report from applying SVM to crime data from certain parameters.
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report,confusion_matrix
from sklearn.svm import SVC
def SupVecMach(data): # Function used to train data and apply the SVM Model to predict Resolution, based on The Weekday, The Month, The Day number, The hour, and Longitude and Latitude coordinates for which the crime occured.
CrimeData2 = data[["Incident Day of Week", "Latitude", "Longitude", "Incident Month", "Incident Hour", "Incident Day", "Resolution"]]
CrimeData2.dropna(inplace = True) # Remove Nan values so that I can use SVM model
# Set dummy variables to Weekday Values, and Resolution Names because SVM model only takes in numeric types.
CrimeData2.replace(list(CrimeData2["Incident Day of Week"].value_counts().index), range(7), inplace = True)
CrimeData2.replace(list(CrimeData2["Resolution"].value_counts().index), range(6), inplace = True)
X = CrimeData2
y = X['Resolution']
X_train, X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2, random_state = 42)
svc_model = SVC()
svc_model.fit(X_train,y_train)
predictions = svc_model.predict(X_test)
# Here I output the Confusion Matrix and Classification Report for SVM model.
print("Confusion Matrix\n", confusion_matrix(y_test,predictions), "\n", sep = "\n")
print("Classification Report for Resolution\n", classification_report(y_test,predictions), "\n", sep ="\n")
return X |
25d3669cc518724dbc163587b3cb803f897c3e0a | he-is-james/Algorithmic-Toolbox | /Week 1 Programming Challenges/sum_of_two_digits.py | 180 | 4 | 4 | # python3
def sum_of_two_digits(first_digit, second_digit):
return first_digit + second_digit
num = input()
a, b = map(int, num.split())
print(sum_of_two_digits(a, b)) |
0d1c7a6f78ba84a3e7197a77fd89eab68d767d00 | Yukikazari/kyoupuro | /.提出一覧/AtCoder/abc186/c/main.py | 484 | 3.640625 | 4 | #!/usr/bin/env python3
#import
#import math
#import numpy as np
N = int(input())
ans = 0
def ten(num):
isok = True
while num > 0:
if num % 10 == 7:
isok = False
break
num //= 10
return isok
def eight(num):
isok = True
while num > 0:
if num % 8 == 7:
isok = False
break
num //= 8
return isok
for i in range(1, N + 1):
if ten(i) and eight(i):
ans += 1
print(ans) |
75b0c5722b4d15397f13865cbb8ff6be28721edc | Tikrong/sudoku | /sudoku.py | 6,784 | 3.546875 | 4 | """
high level support for doing this and that.
"""
import copy
class Variable():
""" create new variable with coordinates """
def __init__(self, y, x):
self.x = x
self.y = y
# define hashing of variable to use it as key in dicts and store them in sets
def __hash__(self):
return hash((self.x, self.y))
# define a way to determine whether to variables are equal
def __eq__(self, other):
return ((self.x == other.x) and (self.y == other.y))
# define string representation of class
def __str__(self):
return f"({self.y}, {self.x})"
def __repr__(self):
return f"Variable({self.y}, {self.x})"
class Sudoku():
""" define structure of a Sudoku puzzle """
def __init__(self, structure_file):
with open(structure_file) as f:
contents = f.read().splitlines()
#check that provided puzzle is correct (9x9 field)
if len(contents) != 9:
raise Exception("Not valid sudoku puzzle")
for row in contents:
if len(row) != 9:
raise Exception("Not valid sudoku puzzle")
#define structure for sudoku puzzle
self.structure = []
for y in range(9):
row = []
for x in range(9):
if contents[y][x].isdigit():
row.append(contents[y][x])
else:
row.append(False)
self.structure.append(row)
# determine variables set
self.variables = set()
for y in range(9):
for x in range(9):
self.variables.add(Variable(y, x))
# determine initial assignment
self.initial_assignment = dict()
for variable in self.variables:
if self.structure[variable.y][variable.x]:
self.initial_assignment[variable] = int(self.structure[variable.y][variable.x])
#return set of all variables that are constraining current variable (hirizontal and vertical row)
def neighbors(self, var):
neighbors = set()
for variable in self.variables:
if var == variable:
continue
elif (var.x == variable.x) ^ (var.y == variable.y):
neighbors.add(variable)
elif (var.x // 3 == variable.x // 3) and (var.y // 3 == variable.y // 3):
neighbors.add(variable)
return neighbors
class SudokuSolver():
counter = 0
def __init__(self, sudoku):
self.sudoku = sudoku
#initialize domains for all variables
values = set(i for i in range(1,10))
self.domains = {var : values.copy() for var in self.sudoku.variables}
#return 2D array representing current assignment
def grid(self, assignment):
# create empty grid with None for every cell
grid = [
[None for _ in range(self.sudoku.width)]
for _ in range(self.sudoku.height)
]
for var, value in assignment.items():
grid[var.y][var.x] = value
return grid
# print current assignment to the terminal
def print(self, assignment):
grid = self.grid(assignment)
for y in range(self.sudoku.height):
for x in range(self.sudoku.width):
print(grid[y][x] or "#", end="")
print()
def solve(self):
# Enforce node and arc consistency, and then solve the CSP.
self.ac3(self.sudoku.initial_assignment)
return self.backtrack(self.sudoku.initial_assignment)
# check that assignment is consistent: no same numbers in horizontal and vertical rows
def consistent(self, assignment):
for variable in assignment:
neighbors = self.sudoku.neighbors(variable)
for neighbor in neighbors:
if neighbor in assignment:
if assignment[variable] == assignment[neighbor]:
return False
return True
# return unassigned variable
def select_unassigned_var(self, assignment):
values_in_domain = 10
for var in self.sudoku.variables:
if var not in assignment:
if len(self.domains[var]) < values_in_domain:
unassigned_var = var
values_in_domain = len(self.domains[var])
return unassigned_var
# check whether the assignment is complete
def assignment_complete(self, assignment):
if not assignment:
return False
if len(assignment) != len(self.sudoku.variables):
return False
for key in assignment:
if assignment[key] == None:
return False
return True
# some heuristic to remove values from domain that are not in line with current assignment
def ac3(self, assignment, var = None):
# if algorithm initialized for the first time with only initial data
if not var:
for variable_x in self.sudoku.variables:
if variable_x in assignment:
continue
for variable_y in self.sudoku.neighbors(variable_x):
if variable_y not in assignment:
continue
for value in self.domains[variable_x].copy():
if value == assignment[variable_y]:
self.domains[variable_x].remove(value)
return True
def backtrack(self, assignment):
"""
Using Backtracking Search, take as input a partial assignment for the
crossword and return a complete assignment if possible to do so.
`assignment` is a mapping from variables (keys) to words (values).
If no assignment is possible, return None.
"""
if self.assignment_complete(assignment):
return assignment
#try new variable
var = self.select_unassigned_var(assignment)
for value in self.domains[var]:
self.counter += 1
new_assignment = assignment.copy()
new_assignment[var] = value
tmp_domain = copy.deepcopy(self.domains)
self.ac3(new_assignment)
if self.consistent(new_assignment):
result = self.backtrack(new_assignment)
if result is not None:
return result
self.domains = copy.deepcopy(tmp_domain)
return None |
3e2dabd91c825b908879d4cb97cbe5f5209e34bd | Kumarved123/Basic-Data-Structure-Algorithm | /Graph and priority Queue/N_Queen_problem.py | 692 | 3.65625 | 4 | ''' The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example,
following is a solution for 4 Queen problem.'''
N = 6
col = [i for i in range(N)]
def is_safe(arr):
n = len(arr)
for i in range(n):
for j in range(i+1,n):
val1 = arr[i]+i
val2 = arr[i]-i
if j+arr[j] == val1 or arr[j]-j == val2:
return False
return True
def permute(col, l, r):
if l == r and is_safe(col):
print(col)
for i in range(l,r+1):
col[i], col[l] = col[l], col[i]
permute(col, l+1, r)
col[i], col[l] = col[l], col[i]
permute(col, 0, N-1)
|
ef568050e0bd950e308679080ea65dada022e612 | Roboyantriki-SNU/Python_Workshop | /python basics/pro3.py | 271 | 3.828125 | 4 | while True:
print('Enter the username')
username = input()
if (username != 'Alex'):
continue
print('Enter the password')
pws = input()
if (pws == 'dog'):
break;
else:
print('Access not granted')
print('Access granted')
|
90ce8053afd00b0f547c1ddfd8be5537826271da | SongofG/Python_Basics | /Boolean Q1.py | 165 | 3.9375 | 4 | ## Q1)
def main():
num = input("type any number: ")
if num.isdigit():
print(int(num)**2)
else:
print("This is not an integer.")
main()
|
4d24e355bed69730c25202d490fdf4cc5d3a9c0b | Vovanuch/python-basics-1 | /happy_pythoning_cource/Part_13/13.1.1.Print_square/13.1.1.Print_square.py | 773 | 3.890625 | 4 | '''
Звездный прямоугольник 1
Напишите функцию draw_box(), которая выводит звездный прямоугольник с размерами 14×1014 \times 1014×10 в соответствии с образцом:
**********
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
**********
Примечание. Для вывода прямоугольника используйте цикл for.
'''
def to_print_horizontal_border():
print('**********')
def to_print_vertical_border(rows):
for _ in range(rows):
print('* *')
to_print_horizontal_border()
to_print_vertical_border(12)
to_print_horizontal_border() |
4f6e07c58ae3ce5b8bf7927778fe2e13dad3c4c4 | yidao620c/core-algorithm | /algorithms/c01_linear/linkedlist/linked_list_double_cycle.py | 1,524 | 3.640625 | 4 | # -*- encoding: utf-8 -*-
"""
双向循环链表数据结构
"""
from algorithms.c01_linear import NodeDouble
class LinkedListDouble:
"""
双向循环链表,带哨兵
"""
def __init__(self):
head = NodeDouble(None)
head.pre = head.next = head # 将pre和next都指向自己
self.head = head
def insert_node(self, node, new_node):
"""
:param node:插入点节点
:param new_node:新节点
:return:
"""
new_node.next = node.next
new_node.pre = node
node.next = new_node
def remove_node(self, node):
"""
:param node:待删除节点
:return:
"""
if node == self.head: # 不能删除头节点
return
node.pre.next = node.next
node.next.pre = node.pre
def search(self, data):
"""
直接比较原始数据
:param data: 待查询数据
:return: 查询到的节点
"""
target = self.head.next
while target != self.head and target.data != data:
target = target.next
return target
def search_equal(self, data, equal):
"""
通过传入equal比较函数来进行相等判断
:param data: 待查询数据
:param equal: 相等函数
:return: 查询到的节点
"""
target = self.head.next
while target != self.head and equal(target.data, data):
target = target.next
return target
|
d42e3efe4af61c29771da12a3fff3b7cdbe17819 | xkoma007/leetcode | /080RemoveDuplicatesfromSortedArrayII.py | 650 | 3.578125 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m_len = len(nums)
total_len = m_len
repeat_num, repeat_val = 0, 0
for i in range(m_len-1, -1, -1):
if repeat_num == 0 or nums[i] != repeat_val:
repeat_val = nums[i]
repeat_num = 1
elif nums[i] == repeat_val:
repeat_num += 1
if repeat_num > 2:
total_len -= 1
del nums[i]
return total_len
c = Solution()
print(c.removeDuplicates([1,1,1,2,2,3]))
|
bd9e4d75f9bf2c5c0d022841c44bc3b760bf7292 | allenpark/1412finalproject | /pairsPlayer.py | 1,835 | 3.875 | 4 | class PairsPlayer:
def __init__(self, pid):
self.type = "Default Player"
self.pid = pid
self.hand = []
self.score = 0
self.scored = []
def insert_into_hand(self, cards):
new_cards = [x for x in cards]
new_hand = []
while len(self.hand) > 0 or len(new_cards) > 0:
if len(self.hand) == 0:
new_hand += new_cards
break
if len(new_cards) == 0:
new_hand += self.hand
break
if self.hand[0] <= new_cards[0]:
new_hand.append(self.hand.pop(0))
else:
new_hand.append(new_cards.pop(0))
self.hand = new_hand
# Returns the pid of the player you want to steal from
# The player must have lowest in their hand
def handle_fold(self, lowest, players):
# OVERRIDE THIS IF YOU DEFINE A NEW PLAYER
print
for pid in xrange(len(players)):
print "Player " + str(pid) + " has hand " + str(players[pid].hand)
print "You are player " + str(self.pid) + " taking a " + str(lowest)
x = int(raw_input("Which player will you take from? "))
while lowest not in players[x].hand:
print "Player " + str(x) + " does not have " + str(lowest)
x = int(raw_input("Which player will you take from? "))
return x
# Returns true if hit and false if fold
def decide(self, players, deck):
# OVERRIDE THIS IF YOU DEFINE A NEW PLAYER
print
print "Player " + str(self.pid) + "'s hand is " + str(self.hand)
ans = raw_input("Will you hit or fold? (h/f) ")
while len(ans) == 0:
print "That's not an answer."
ans = raw_input("Will you hit or fold? (h/f) ")
return ans[0] == 'h'
|
33070dab541d884a2f5e3839a53037fb3f1de8ea | Ashanthe/van-input-naar-output | /feestlunch.py | 603 | 3.671875 | 4 | croissantjes = input("hoeveel croissants :")
prijsC = 0.39
stokbrood = input("hoveel stokbroden :")
prijsS = 2.78
kortingsbonnen = input("hoveel kortngsbonnen :")
korting = 0.50
#Prijs
print(int(croissantjes) * prijsC + int(stokbrood) * prijsS - int(kortingsbonnen) * korting)
prijs = (int(croissantjes) * prijsC + int(stokbrood) * prijsS - int(kortingsbonnen) * korting)
#Factuur
print("De feestlunch kost " + str(prijs) + " euro voor de " + str(croissantjes) + " croissantjes en de " + str(stokbrood) + " stokbroden als de " + str(kortingsbonnen) + " kortingsbonnen nog geldig zijn! ")
|
9c3d7acad8c4010fca3b22fcd4498b735552b6fd | suman2020/AlgorithmPractice | /linkedlist.py | 7,260 | 4.0625 | 4 | # listA = [1,2,3,4,5,6,7,8]
#
# class Node:
# def __init__(self, currentVal = None , cNodeNext = None):
# self.currentVal = currentVal
# self.cNodeNext = cNodeNext
# head = Node(listA[0])
# #1->None
#
# for value in listA[1:]:
# newNode = Node(value)
# currentNode = head
# while currentNode.cNodeNext!=None:
# currentNode= currentNode.cNodeNext
# currentNode.cNodeNext = newNode
#
# #temp = head
# # while temp:
# # temp.currentVal = 1
# # temp = temp.cNodeNext
# #while head:
# # head.currentVal = 1
# # head = head.cNodeNext
#
# while head:
# print(head.currentVal)
# head = head.cNodeNext
# # 1-> None
# # 1->None |||||||| 2->None
# # currentNode = 1->2->None
#
# LinkedList
# Creating a Node class
class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
#Creating a Linked List class
class LinkedList:
def __init__(self):
self.head = None
# method to inset a new element in the beginning
def insert_at_beginning(self, data):
if self.head is None:
self.head = Node(data)
return
newNode = Node(data,self.head)
self.head = newNode
# insert a new node at the last
def insert_at_end(self,data):
NewNode = Node(data,None)
if self.head is None:
self.head = NewNode
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = NewNode
# method to insert multiple values i.e elements in a list
def insert_list(self,list):
# self.head = None
for data in list:
self.insert_at_end(data)
"""
the above function can also be written as
def insert_list(self,list):
self.head = Node(list[0], None)
for value in list[1:]:
currentNode = Node(value)
itr = self.head
while itr.next:
itr = itr.next
itr.next = currentNode
"""
# method to print the list
def print_list(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
"""
def print_list(self):
temp = self.head
while temp.next:
print(temp.data)
temp = temp.next
# these two functions above prints the same value
# the difference is
in the second case: we iterated through the next node the current node points to
# A->B->C->none A has value 1, B has 2 and C has 3
# first iteration # second iteration # third iteration
temp = A temp = B temp = C
while loop runs while loop runs loop doesnot run because temp.next or C->next is null
prints 1 prints 2 loop ends
temp = B temp = C print function prints the value in C node i.e 3
In the first case: we iterated through the current nodes
# A->B->C->none A has value 1, B has 2 and C has 3
# first iteration # second iteration # third iteration
temp = A temp = B temp = C
while loop runs while loop runs while loop runs
prints 1 prints 2 prints 3
temp = B temp = C temp = None After this the loop ends. But if we try to print after this
it gives non type error
"""
# method to count the list
def count_list(self):
count = 0
curr = self.head
while curr:
count+=1
curr = curr.next
return count
# method to reverse the linked list
def reverse_list(self):
previousNode = None
currentNode = self.head
while currentNode is not None:
temp_currentNode = currentNode.next
currentNode.next = previousNode
previousNode = currentNode
currentNode = temp_currentNode
self.head = previousNode
def remove_node_withValue(self,value):
currentNode = self.head
while currentNode:
if currentNode.data == 3:
print('This node is to be removed')
tempNode = previousNode
previousNode= currentNode.next
currentNode = tempNode
currentNode.next = previousNode
break;
previousNode = currentNode
currentNode = currentNode.next
def remove_node_withIndex(self,index):
currentNode = self.head
count = 0
if index == 0:
self.head= self.head.next
while currentNode:
if count == index -1 :
print("Removal with index given")
currentNode.next = currentNode.next.next
break;
currentNode = currentNode.next
count += count
def insert_newNode_WithIndex(self, index, value):
if index < 0 and index >=self.count_list():
raise Exception('Invalid index')
newNode = Node(value)
if index ==0:
newNode.next = self.head
self.head = newNode.next
else:
currentNode = self.head
count = 0
while currentNode:
if count == index:
newNode.next = currentNode
currentNode = previousNode
currentNode.next = newNode
break
"""
can also be written as
if count == index-1:
newNode.next = currentNode.next
currentNode.next = newNode
break
"""
count +=1
previousNode = currentNode
currentNode = currentNode.next
def middleNode(self):
node_storage = {}
i = 0
while self.head:
node_storage[i] = self.head
self.head = self.head.next
i += 1
target = int(i/2)
for e in range(target,i):
print(node_storage[e].data)
if __name__ == '__main__':
list = [1,2,3,4,5,6,7,8,9,10]
list1 = LinkedList()
# list1.insert_at_end(5)
# list1.insert_at_end(10)
# list1.insert_at_end(15)
list1.insert_at_beginning(12)
list1.insert_at_beginning(13)
list1.insert_list(list)
print("Before reverse")
list1.print_list()
print("Count")
print(list1.count_list())
print("After Reverse")
list1.reverse_list()
list1.print_list()
print("Removal of a node")
list1.remove_node_withValue(2)
list1.print_list()
list1.remove_node_withIndex(1)
list1.print_list()
print("\nInsertion of a new node with index")
list1.insert_newNode_WithIndex(3,59)
list1.print_list()
print("\nPrinting from the middle node")
list1.middleNode()
|
753ed082cab938301ff87d93c7e21b2a705e2df9 | JJong-Min/Baekjoon-Online-Judge-Algorithm | /Data Structure(자료구조)/Data_Structure_9번.py | 573 | 3.546875 | 4 | #리스트가 아닌 딕셔너리 활용, 시간초과x
n = input()
res = dict()
for _ in range(int(n)):
per, stat = input().split(" ")
res[per] = stat
for i in sorted(res.keys(), reverse=True):
if res[i] == "enter": print(i)
# python3로는 시간초과, pypy3로는 통과
import sys
n = int(sys.stdin.readline())
person = []
for i in range(n):
name, status = sys.stdin.readline().split()
if status == 'enter':
person.append(name)
else:
del person[person.index(name)]
person.sort(reverse = True)
for p in person:
print(p)
|
e4acb495a5f4a4cefc198d4af15b8772537c5b1c | lim1202/LeetCode | /Algorithm/sort.py | 3,182 | 4.0625 | 4 | """Sort"""
import random
import time
def bubble_sort(nums):
"""Bubble Sort"""
if not nums:
return None
for i in range(len(nums)):
flag = False
for j in range(len(nums) - i - 1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
flag = True
if not flag:
break
return
def insertion_sort(nums):
"""Insertion Sort"""
if not nums:
return None
for i in range(1, len(nums)):
value = nums[i]
j = i - 1
while j >= 0:
if nums[j] > value:
nums[j + 1] = nums[j]
else:
break
j = j - 1
nums[j + 1] = value
return
def merge_sort(nums):
"""Merge Sort"""
if not nums:
return None
def merge(C, p, q, r):
A = C[p:q+1]
B = C[q+1:r+1]
i = r
j = len(A) - 1
k = len(B) - 1
while i >= p:
if (j >= 0 and k >= 0):
if A[j] > B[k]:
C[i] = A[j]
j -= 1
else:
C[i] = B[k]
k -= 1
elif j >= 0:
C[i] = A[j]
j -= 1
elif k >= 0:
C[i] = B[k]
k -= 1
i -= 1
return
def merge_sort_c(C, p, r):
if p >= r:
return
q = (p+r)//2
merge_sort_c(C, p, q)
merge_sort_c(C, q+1, r)
merge(C, p, q, r)
return
merge_sort_c(nums, 0, len(nums)-1)
return
def quick_sort(nums):
"""Quick Sort"""
if not nums:
return
def patition(A, p, r):
pivot = A[r]
i = p
for j in range(p, r):
if A[j] < pivot:
A[i], A[j] = A[j], A[i]
i = i + 1
A[i], A[r] = A[r], A[i]
return i
def quick_sort_c(C, p, r):
if p >= r:
return
q = patition(C, p, r)
quick_sort_c(C, p, q-1)
quick_sort_c(C, q+1, r)
return
quick_sort_c(nums, 0, len(nums)-1)
return
if __name__ == "__main__":
RANDOM_LIST = [i for i in range(1, 11)]
random.shuffle(RANDOM_LIST)
print('Test array: {}'.format(RANDOM_LIST))
BS_LIST = RANDOM_LIST.copy()
start_time = time.time()
bubble_sort(BS_LIST)
print('Bubble Sort result: {}'.format(BS_LIST))
print('Duration: {} ms'.format((time.time() - start_time) * 1000))
IS_LIST = RANDOM_LIST.copy()
start_time = time.time()
insertion_sort(IS_LIST)
print('Insertion Sort result: {}'.format(IS_LIST))
print('Duration: {} ms'.format((time.time() - start_time) * 1000))
MS_LIST = RANDOM_LIST.copy()
start_time = time.time()
merge_sort(MS_LIST)
print('Merge Sort result: {}'.format(MS_LIST))
print('Duration: {} ms'.format((time.time() - start_time) * 1000))
QS_LIST = RANDOM_LIST.copy()
start_time = time.time()
quick_sort(QS_LIST)
print('Quick Sort result: {}'.format(QS_LIST))
print('Duration: {} ms'.format((time.time() - start_time) * 1000))
|
5626346665b7ecb12d4dc2604405330acd546933 | rparthas/Repository | /Python/bfs.py | 959 | 3.75 | 4 | graph = {"cab": ["cat", "car"], "mat": ["bat"], "cat": ["mat", "bat"], "car": ["cat", "bar"]}
visited_nodes = {}
def get_neighbours(vertex):
vertices = []
if vertex in graph:
for node in graph[vertex]:
vertices.append({node: vertex})
return vertices
def print_path(dest):
path = []
route = dest
path.append(dest)
while route in visited_nodes:
parent_node = visited_nodes[route]
path.append(parent_node)
route = parent_node
path.reverse()
print(path)
start, end = "cab", "bat"
neighbours = get_neighbours(start)
while len(neighbours) > 0:
neighbour = neighbours.pop(0)
first_vertex = list(neighbour.keys())[0]
if first_vertex not in visited_nodes:
visited_nodes[first_vertex] = neighbour[first_vertex]
if first_vertex == end:
print_path(first_vertex)
break
neighbours = neighbours + get_neighbours(first_vertex)
|
564731e7d16b04ac19bd346a1fad56d81a5618f7 | NickyJay/PortfolioProject | /week3/using_sets.py | 501 | 3.78125 | 4 | # numbers_set = {1, 2, 3, 4, 4} #duplicate values removed
#numbers_set = {1, 2, 3, 4, [5, 6]} # cannot use mutable data types
# numbers_set = {1, 2, 3, 4, (5, 6)} #tuples are imutable, OK to use!
# print(numbers_set)
words_set = {"Alpha", "Bravo", "Charlie"}
# abcd = ""
# for word in words_set:
# abcd += word
# print(abcd)
words_set.add("Delta")
print(words_set)
words_set.discard("Bravo")
print(words_set)
userprofile = {"suspect" : "bill"}
print(userprofile)
userprofile["username"]="jdoe" |
aee80b42410f25dbe7c46c6912afa83610936ce5 | jperla/webify | /webify/templates/helpers/time.py | 1,289 | 3.703125 | 4 | import datetime
def fuzzy_time_diff(begin, end=None):
"""
Returns a humanized string representing time difference
between now() and the input timestamp.
The output rounds up to days, hours, minutes, or seconds.
4 days 5 hours returns "4 days"
0 days 4 hours 3 minutes returns "4 hours", etc...
"""
if end is None:
end = datetime.datetime.now()
timeDiff = end - begin
days = timeDiff.days
hours = timeDiff.seconds/3600
minutes = timeDiff.seconds%3600/60
seconds = timeDiff.seconds%3600%60
str = u''
tStr = u''
if days > 0:
if days == 1: tStr = u'day'
else: tStr = u'days'
str = str + u'%s %s' %(days, tStr)
return str
elif hours > 0:
if hours == 1: tStr = u'hour'
else: tStr = u'hours'
str = str + u'%s %s' %(hours, tStr)
return str
elif minutes > 0:
if minutes == 1:tStr = u'minutes'
else: tStr = u'minutes'
str = str + u'%s %s' %(minutes, tStr)
return str
elif seconds > 0:
if seconds == 1:tStr = u'second'
else: tStr = u'seconds'
str = str + u'%s %s' %(seconds, tStr)
return str
else:
return None
|
5cbc199946d914dfe1ef81a47f3e06b88b2f4717 | BaluAnush18/Machine-Learning-Basics | /linearregression1.py | 1,396 | 4.375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#REGRESSION IS TO PREDICT A REAL CONTINUOUS REAL VALUE.
#CLASSIFICATION IS TO PREDICT A CATEGORY OR A CLASS.
dataset = pd.read_csv('Salary_Data.csv')
x = dataset.iloc[:, :-1]
y = dataset.iloc[:, -1]
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=1/3, random_state=0)
# x_train -> Independent variable | y_train -. dependent variable.
from sklearn.linear_model import LinearRegression
regressor = LinearRegression() #to create a instance
regressor.fit(x_train, y_train) #used to train the model on the training set or predicts the future model.
#PREDICTING THE RESULT BASED ON TEST VALUES:
y_pred = regressor.predict(x_test)
#VISUALIZING THE TRAINING SET:
plt.scatter(x_train, y_train, color='red') #input the coordinates.
plt.plot(x_train, regressor.predict(x_train), color='blue') #used to plot the regression line(Coming close to the straight line).
plt.title("Salary vs Experience(Training set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()
#RUNNING THE TEST SET:
plt.scatter(x_test, y_test, color='green')
plt.plot(x_train, regressor.predict(x_train), color='orange')
plt.title("Salary vs Experience(Test set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show() |
96e9f6576fe030615de3dfb84af1f2f16d801db3 | rutvik2611/hw | /Task5/q3.py | 221 | 3.53125 | 4 | k = int(input("Enter 4 digit number: "))
convert = str(k)
l = len(convert)
while l != 4:
try:
k = input("TOO LONG OR SHORT , Try AGAIN ")
l = len(k)
except ValueError:
print("Value Error") |
c84257d1ec1572f050b3e8a4afe1eafee60d474f | fredericaltorres/fCircuitPython | /boot.py | 822 | 3.5625 | 4 | """
https://learn.adafruit.com/circuitpython-essentials/circuitpython-storage
"""
import board
import digitalio
import storage
#
# See output in file boot_out.txt
#
print('boot.py - start')
# For Gemma M0, Trinket M0, Metro M0/M4 Express, ItsyBitsy M0/M4 Express
# switch = digitalio.DigitalInOut(board.D2)
switch = digitalio.DigitalInOut(board.D5) # For Feather M0/M4 Express
# switch = digitalio.DigitalInOut(board.D7) # For Circuit Playground Express
switch.direction = digitalio.Direction.INPUT
switch.pull = digitalio.Pull.UP
if switch.value == False:
print('Pin D5 is grounded, authorize write mode')
else:
print('Pin D5 is high, read mode mode only')
# If the switch pin is connected to ground CircuitPython can write to the drive
storage.remount("/", switch.value)
print('boot.py - done')
|
9550da088684c38db8e5e0b98d75d047d3b57418 | cogito0823/learningPython | /data_structures/binary_tree/binary_tree.py | 2,456 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : binary_tree.py
@Time : 2020/03/17 11:40:06
@Author : cogito0823
@Contact : 754032908@qq.com
@Desc : 递归生成二叉树、遍历二叉树(层次遍历使用队列)
'''
import queue
class Node():
"""节点类"""
def __init__(self,data):
self.data = data
self.left_child = None
self.right_child = None
def __repr__(self):
return str(self.data)
__str__ = __repr__
def __eq__(self,other):
"""重构__eq__方法"""
return (self.__class__ == other.__class__ and
self.data == other.data and
((not self.left_child and not other.left_child) or self.left_child.data == other.left_child.data) and
((not self.right_child and not other.right_child) or self.right_child.data == other.right_child.data))
def create_binary_tree(array):
if array:
data = array.pop(0)
if data is not None:
node = Node(data)
node.left = create_binary_tree(array)
node.right = create_binary_tree(array)
return node
return None
def pre_order_traveral(node):
if node:
print(node.data)
pre_order_traveral(node.left)
pre_order_traveral(node.right)
def in_order_traveral(node):
if node:
in_order_traveral(node.left)
print(node.data)
in_order_traveral(node.right)
def post_order_traveral(node):
if node:
post_order_traveral(node.left)
post_order_traveral(node.right)
print(node.data)
def pre_order_traveral_via_stack(root):
if root:
stack = [root]
while stack:
node = stack.pop()
if node:
print(node)
stack.append(node.right)
stack.append(node.left)
def level_order_traveral(root):
if root:
queue = [root]
while queue:
node = queue.pop(0)
if node:
print(node)
queue.append(node.left)
queue.append(node.right)
if __name__ == "__main__":
node = create_binary_tree([1,0,2,3,4,None,None,5,None,None,6,None,None,None,None])
pre_order_traveral(node)
level_order_traveral(node)
node = create_binary_tree([1,2,4, 8, None, None, 9, None, None, 5, None, None, 3, 6, None, None, 7])
pre_order_traveral(node)
level_order_traveral(node)
|
7eae6bb0c01918f6661269b3bfb8e051c7fcc5fc | AprilCat/learnPython | /basicPractice/day009_salary.py | 1,239 | 3.6875 | 4 | from abc import ABCMeta, abstractmethod
class Employee(object, metaclass=ABCMeta):
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@abstractmethod
def get_salary(self):
pass
class Programmer(Employee):
def __init__(self, name):
super().__init__(name)
self._work_hour = 0
@property
def work_hour(self):
return self._work_hour
@work_hour.setter
def work_hour(self, hour):
self._work_hour = hour
def get_salary(self):
return self.work_hour * 50
class Manager(Employee):
def get_salary(self):
return 15000
class Sale(Employee):
def __init__(self, name):
super().__init__(name)
self._sales = 0
@property
def sales(self):
return self._sales
@sales.setter
def sales(self, sale):
self._sales = sale
def get_salary(self):
return 10000 + self.sales * 0.05
emps = [
Programmer("A"),
Manager("B"),
Sale("C")
]
for emp in emps:
if isinstance(emp, Programmer):
emp.work_hour = 240
elif isinstance(emp, Sale):
emp.sales = 1000000
print("%s:%d" % (emp.name, emp.get_salary()))
|
fcc5e539904815776e44748be99d608e07826d19 | enriquezc/DialogComps | /src/Dialog_Manager/Student.py | 1,670 | 3.625 | 4 | from src.Dialog_Manager import Course
'''Student object
Basically stores all our information about the student
There's some info we don't use, but could be used in the future
Variable names are self explanitory. '''
class Student:
def __init__(self):
self.name = None
self.current_classes = []
self.major = set()
self.concentration = set()
self.previous_classes = []
self.distributions_needed = []
self.major_classes_needed = []
self.terms_left = 12
self.total_credits = 0
self.current_credits = 0
self.interests = set()
self.abroad = None
self.all_classes = set()
self.potential_courses = []
self.relevant_class = Course.Course()
self.distro_courses= {}
'''Prints out relevant information about student
Never used outside of testing
'''
def __str__(self):
major_str = ""
if len(self.major) == 0:
major_str = "Undecided"
elif len(self.major) == 1:
major_str = "a {} major".format(self.major[0])
else:
major_str = "a {}-{} double-major".format(self.major[0], self.major[1])
concentration_str = ""
if len(self.concentration) == 1:
concentration_str = " and a {} concentration".format(self.concentration[0])
courses_str = ""
if len(self.current_classes) > 0:
courses_str += " and are registered for:\n"
for course in self.current_classes:
courses_str += "\t{}\n".format(course.name)
return "{}, {}{}{}".format(self.name, major_str, concentration_str, courses_str) |
115f758f7077d77f8694f14ffaceac683b73af96 | GolamRabbani20/PYTHON-A2Z | /DYNAMIC_PROGRAMMING/SumOfnNumbers.py | 92 | 3.734375 | 4 | def Sum(n):
if n == 0:
return 0
return n + Sum(n-1)
print(Sum(int(input()))) |
a7b13c6a216db18949fe11b30c298f330678a7d6 | Hamsike2021/Practice_6 | /5.py | 146 | 3.890625 | 4 | def is_sorted(t):
if sorted(t) == t:
return True
return False
print(is_sorted([1, 2, 3])) # example
print(is_sorted([3, 1, 2])) # example
|
c9c254513f4041b5a5d639a78e643e234dc2ef80 | Raphaelshoty/Python-Studies | /tryCatch.py | 556 | 3.78125 | 4 | try :
print("teste de try")
print("Im "+30+"Years old")
except TypeError as t:
print("Não se faz conversões implícitas de tipo ", str(t))
log = str(t)
saveLog = open("logDeErro.txt","w")
saveLog.write(log)
saveLog.close()
except Exception as e:
print("Deu ruim meu caro sabe porque ? \n" + str(e))
print(5 + int("5"))
'''
try to catch specific errors
like
except NameError as e - related to variables that not exist and was used
except TypeError as t
except ValueError as v
and so on
'''
|
5f1850205cc8305428d1d209f5953f65af3950fe | juliasgan/tennis_tracker | /game.py | 1,094 | 3.78125 | 4 | class Game(object):
'''game represents the tennis game with two teams and a winner'''
'''game also represents the individual games(made up of at least 4 points) that add up to a set'''
'''0, 15, 30, 40, Deuce, Advantage-In, Advantage-Out, Winner_of_game'''
def __init__(self, teamA, teamB, teamA_score, teamB_score):
self.teamA = teamA
self.teamB = teamB
self.teamA_score = teamA_score
self.teamB_score = teamB_score
def winner(self):
#Checking if teamA has enough points to win, if this is the case, then make sure the teamB score is not within 2 and vice versa
if self.teamA_score >= 4: #40-0, 40-15, 40-30, deuce, Ad-in, Ad-out 4, 5, or 6 points
if self.teamA_score - self.teamB_score >= 2: #difference must be at least 2
return self.teamA
if self.teamB_score >= 4: #40-0, 40-15, 40-30, deuce, Ad-in, Ad-out 4, 5, or 6 points
if self.teamB_score - self.teamA_score >= 2: #difference must be at least 2
return self.teamB
return None
|
91fef5f286db8ddeb0384e79112e3e626f231e44 | sundaygeek/book-python-data-minning | /code/3/3-1.py | 612 | 3.6875 | 4 | # -*- coding:utf-8 -*-
# 匿名函数
from math import log #引入Python数学库的对数函数
# 此函数用于返回一个以base为底的匿名对数函数
def make_logarithmic_function(base):
return lambda x:log(x,base)
# 创建了一个以3为底的匿名对数函数,并赋值给了My_LF
My_LF = make_logarithmic_function(3)
# 使用My_LF调用匿名函数,参数只需要真数即可,底数已设置为3。而使用log()函数需要
# 同时指定真数和对数。如果我们每次都是求以3为底数的对数,使用My_LF更方便。
print My_LF(9)
# result: 2.0
|
a58ce091a4b8db1d861328e4efcf9ac4bbf826f1 | nanako-chung/python-beginner | /Assignment 3/ChungNanako_assign3_problem3.py | 4,564 | 4 | 4 | #Nanako Chung (worked with Anusha Chintalapati)
#September 29th, 2016
#M/W Intro to Comp Programming
#Problem #3: Birthday Analyzer
#ask user for start and birth date
print("Instructions: Enter the start date and birthdate for an employee to determine their age at the start of employment.")
start_date=int(input("Enter start date MMDDYYYY: "))
birth_date=int(input("Enter birth date MMDDYYYY: "))
#extract ones place
startones=start_date%10
birthones=birth_date%10
#extract tens place
starttens=int((start_date%100)/10)
birthtens=int((birth_date%100)/10)
#entract hundreds
starthuns=int((start_date%1000)/100)
birthhuns=int((birth_date%1000)/100)
#extract thousands
startthou=int((start_date%10000)/1000)
birththou=int((birth_date%10000)/1000)
#extract ten thousands
starttenthou=int((start_date%100000)/10000)
birthtenthou=int((birth_date%100000)/10000)
#extract hundred thousands
starthunthou=int((start_date%1000000)/100000)
birthhunthou=int((birth_date%1000000)/100000)
#extract millions
startmil=int((start_date%10000000)/1000000)
birthmil=int((birth_date%10000000)/1000000)
#extract ten millions
starttenmil=int((start_date%1000000000)/100000000)
birthtenmil=int((birth_date%1000000000)/100000000)
#get the exact month
smonthten=str(starttenmil)
smonthone=str(startmil)
startmonth=smonthten+smonthone
bmonthten=str(birthtenmil)
bmonthone=str(birthmil)
birthmonth=bmonthten+bmonthone
#get exact day
sdayten=str(starthunthou)
sdayone=str(starttenthou)
startday=sdayten+sdayone
bdayten=str(birthhunthou)
bdayone=str(birthtenthou)
birthday=bdayten+bdayone
#get exact year
syearthou=str(startthou)
syearhun=str(starthuns)
syearten=str(starttens)
syearone=str(startones)
startyear=syearthou+syearhun+syearten+syearone
byearthou=str(birththou)
byearhun=str(birthhuns)
byearten=str(birthtens)
byearone=str(birthones)
birthyear=byearthou+byearhun+byearten+byearone
# list month
if birthmonth == "01":
m="January"
elif birthmonth == "02":
m="February"
elif birthmonth == "03":
m="March"
elif birthmonth == "04":
m="April"
elif birthmonth == "05":
m="May"
elif birthmonth == "06":
m="June"
elif birthmonth == "07":
m="July"
elif birthmonth == "08":
m="August"
elif birthmonth == "09":
m="September"
elif birthmonth == "10":
m="October"
elif birthmonth == "11":
m="November"
elif birthmonth == "12":
m="December"
else:
m="Invalid month."
#list day with the proper grammar
if birthday == "01":
d = "1" + "st"
elif birthday == "02":
d = "2" + "nd"
elif birthday == "03":
d = "3" + "rd"
elif birthday == "04":
d = "4" + "th"
elif birthday == "05":
d = "5" + "th"
elif birthday == "06":
d = "6" + "th"
elif birthday == "07":
d = "7" + "th"
elif birthday == "08":
d = "8" + "th"
elif birthday == "09":
d = "9" + "th"
elif birthday == "10" or "11" or "12" or "13" or "14" or "15" or "16" or "17" or "18" or "19" or "20" or "24" or "25" or "26" or "27" or "28" or "29" or "30":
d = birthday + "th"
elif birthday == "21" or "31":
d = birthday + "st"
elif birthday == "22":
d = birthday + "nd"
elif birthday == "23":
d = birthday + "rd"
else:
d = "Invalid day."
print("The contestant was born on", " ", m, " ", d, ",", " ", birthyear, sep="")
#convert strings to integers
numberbirthyear = int(birthyear)
numberbirthmonth = int(birthmonth)
numberbirthday = int(birthday)
numberstartyear = int(startyear)
numberstartmonth = int(startmonth)
numberstartday = int(startday)
#determine if age is eligible by using if statements
if (numberstartyear - numberbirthyear)>21:
print("ELIGIBLE: The contestant will be 21 by the time taping begins")
elif (numberstartyear - numberbirthyear)==21:
if numberstartmonth>numberbirthmonth:
print("ELIGIBLE: The contestant will be 21 by the time taping begins")
elif numberstartmonth==numberbirthmonth:
if numberstartday==numberbirthday:
print("ELIGIBLE: The contestant will be 21 by the time taping begins")
elif numberstartday<numberbirthday:
print("NOT ELIGIBLE: The contestant won't be 21 by the time taping begins")
else:
print("NOT ELIGIBLE: The contestant won't be 21 by the time taping begins")
else:
print("NOT ELIGIBLE: The contestant won't be 21 by the time taping begins")
else:
print("NOT ELIGIBLE: The contestant won't be 21 by the time taping begins")
|
d27af657c0e430a6d44c417c71a95d812620de9f | zhaocanhs/Python | /Day05/xmltest.py | 1,523 | 3.921875 | 4 | # -*- coding:utf-8 -*-
# 作者:火小森
# 日期: 20/1/21- 17:44
# 当前用户名: zc
# 文件名:xml
'''
# xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml
import xml.etree.ElementTree as ET
tree = ET.parse("xml_test.xml")
root = tree.getroot()
print(root.tag)
# 遍历xml文档
for child in root:
print(child.tag, child.attrib)
for i in child:
print(i.tag, i.text)
# 只遍历year 节点
for node in root.iter('year'):
print(node.tag, node.text)
'''
'''
# 修改和删除xml文档内容
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
#修改
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set("updated","yes")
tree.write("xmltest.xml")
#删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('output.xml')
'''
'''
# 自己创建xml文档
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'
et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
ET.dump(new_xml) #打印生成的格式
'''
|
b9ac3fa10d601aaad4e132f0d87e40398099a28c | jamesawgodwin/PythonMachineLearningTemplates | /Random_walk_game.py | 1,282 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
game that determines probability that you will reach height of 60 steps given
steps taken by roll of dice and clumsinesss. Start at 0 height and roll dice
100 times, simulate 10000 times. Display results. Calculate probability of
reaching height of 60 steps
"""
import matplotlib.pyplot as plt
import numpy as np
# set seed
np.random.seed(123)
all_walks = []
# number of interations
for i in range(500) :
random_walk = [0]
# roll dice range() times per iteration
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1, 7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step += 1
else:
step = step + np.random.randint(1, 7)
if np.random.rand() <= 0.001 :
step = 0
random_walk.append(step)
all_walks.append(random_walk)
# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
# Select last row from np_aw_t: ends
ends = np_aw_t[-1]
# Plot histogram of ends, display plot
plt.hist(ends)
plt.title("Number of Steps Taken Per Iteration")
plt.xlabel("Height")
plt.ylabel("Number of times Height reached")
plt.show()
plt.clf()
# winning percentage
wp = (sum(ends >= 60) / len(ends)) * 100
print(wp) |
0b12999a31b6cc1b51a7f40429bf64934927b682 | XinyuYun/cs1026-labs | /lesson9/task3/task.py | 664 | 4.15625 | 4 | # Replace the placeholders with code and run the Python program
sentence ="I had such a horrible day. It was awful, so bad, sigh. It could not have been worse but actually though "\
+"such a terrible horrible awful bad day."
makeItHappy ={"horrible":"amazing","bad":"good","awful":"awesome","worse":"better","terrible":"great"}
Split the sentence and assign to a variable
for word in Complete the range for the for:
if Check to see if word is in makeItHappy list in makeItHappy:
Replace old word with new one from makeItHappy
newString=""
Loop through words and make a sentence:
newString = newString + word + " "
print(newString)
|
1420151b7383bcda68349d53fa36d1a98c812945 | HaymanLiron/46_python_exercises | /q16.py | 250 | 3.625 | 4 | def filter_long_words(list_of_words, n):
# takes in a list_of_words and returns all words in list longer than n characters
output = []
for word in list_of_words:
if len(word) > n:
output.append(word)
return output
|
fdc782952b80f9e3df104cd69a5810e3c16226f6 | aoyerinde/python-learning | /Histogram Plotting.py | 1,391 | 3.703125 | 4 | #building histoograms on just python
a = (0,1,1,1,2,3,7,7,23)
def count_elements(seq) -> dict:
"""""Tally elements from `seq`"""
hist = {}
for i in seq:
hist[i] = hist.get(i,0) + 1
return hist
#count the number of each element in the sequence
counted = count_elements(a)
from collections import Counter
#do the same as above but with collection.counter and not function
recount = Counter(a)
#hist before the loop
def ascii_histogram(seq) -> None:
"""""a horizontal frq table """
counted = count_elements(seq)
for k in sorted(counted):
print('{0:5d} {}'.format(k,'+'* counted[k]))
#clarify#
import random
random.seed(1)
vals = [1,3,4,6,8,9,10]
#each number in vals will occur between 5 and 15 times
freq = (random.randint(5,15) for _ in vals)
data = []
for f,v in zip(freq, vals):
data.extend([v] * f)
ascii_histogram(data)
#now use numpy
import numpy as np
np.random.seed(444)
np.set_printoptions(precision = 3)
d = np.random.laplace(loc=15, scale=3, size=500)
hist, bin_edges = np.histogram(d)
first_edge, last_edge = a.min(), a.max()
n_equal_bins = 10
bin_edges = np.linspace(start=first_edge, stop=last_edge, num=n_equal_bins+1, endpoint=True)
#using matplotlib
import matplotlib.pyplot as plt
n, bins, patches = plt.hist(x=d, bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85)
|
4423358617f7ef096e8fe16d3e5f6618bb041645 | fonsidols/librarySlod | /asignaturas.py | 447 | 3.828125 | 4 | # encoding: utf-8
print("Asignaturas optativas Agno 2017")
print("Asignaturas optativas: Informatica grafica - Pruebas de software - Usabilidad y accesibilidad")
opcion=input("Escribe la asignatura escogida ")
asignatura=opcion.lower();
if asignatura in ("informatica grafica", "pruebas de software", "usabilidad y accesibilidad"):
print("Asignatura elegida es: " +asignatura)
else:
print("La asignatura escogida no esta completada") |
06f9e58d24b7022955f98583e4c53f5b20c742f3 | MariaSyed/Python-SelfStudy | /Chapter 2/2.6 String slices.py | 246 | 4.03125 | 4 | # -*- coding: cp1252 -*-
string = "desserts"
stringA = string[0:4]
stringB = string[-4:]
stringC = string[::-1]
print("The first 4 characters were:",stringA)
print("The last 4 characters were:",stringB)
print("The string backwards was:",stringC) |
5f2479f70eddab4b40b6ddc9b464111df0abb2ad | chati757/python-learning-space | /lambda/lambda_filter.py | 244 | 3.8125 | 4 | number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
# Output: [-5, -4, -3, -2, -1]
#use list comprehensions instread of using lambda and filter
print([i for i in number_list if i < 0]) |
1035073f319d003e3a9045b6acd7a167f415ab3b | lightbits/euler | /problem87.py | 1,177 | 3.546875 | 4 | # The smallest number expressible as the sum of a prime square, prime cube,
# and prime fourth power is 28. In fact, there are exactly four numbers below
# fifty that can be expressed in such a way:
# 28 = 2^2 + 2^3 + 2^4
# 33 = 3^2 + 2^3 + 2^4
# 49 = 5^2 + 2^3 + 2^4
# 47 = 2^2 + 3^3 + 2^4
# How many numbers below fifty million can be expressed as the sum of a prime square,
# prime cube, and prime fourth power?
############
# Solution #
############
import math
def isPrime(n):
# skip multiples of two
m = int(math.sqrt(n) + 1)
for i in range(3, m):
if n % i == 0:
return False
return True
prime_squares = [4]
prime_cubes = [8]
prime_quads = [16]
# We set the upper prime search limit to 7080,
# as 7080^2 > fifty million.
upper_limit = 100
for i in range(3, upper_limit, 2):
if not isPrime(i):
continue
i2 = i * i
i3 = i2 * i
i4 = i3 * i
prime_squares.append(i2)
prime_cubes.append(i3)
prime_quads.append(i4)
ans = []
dups = 0
for a in prime_squares:
for b in prime_cubes:
s = a + b
for c in prime_quads:
s += c
if s <= 50000000:
if (s in ans):
dups += 1
ans.append(s)
# ans.add(s + c)
print(dups)
print(len(ans)) |
9db60664676082b5ba7ad0bc21152352707b37ce | julianascimentosantos/cursoemvideo-python3 | /Desafios/Desafio044.py | 915 | 3.78125 | 4 | print('{:=^40}'.format('LOJAS NASCIMENTO'))
preço = float(input('Preço das compras R$'))
print('''Condições de pagamento:
[ 1 ] À VISTA DINHEIRO OU CHEQUE
[ 2 ] À VISTA CARTÃO
[ 3 ] DIVIDIDO EM ATÉ 2X NO CARTÃO
[ 4 ] DIVIDIDO EM 3X OU MAIS NO CARTÃO''')
condição = int(input('Qual é a opção:' ))
if condição == 1:
valor = preço - (preço * 0.10)
elif condição == 2:
valor = preço - (preço * 0.05)
elif condição == 3:
valor = preço
print('Sua compra será parcelada em 2X e a parcela será de R${:.2f}.'.format(valor/2))
elif condição == 4:
valor = preço + (preço*0.20)
parcela = int(input('Quantas parcelas: '))
print('Sua compra será parcelada em {}X e a parcela será de R${:.2f}.'.format(parcela, valor/parcela))
else:
print('Opção não identificada, tente novamente.')
print('Sua compra de {:.2f} ficará {:.2f} no final.'.format(preço, valor))
|
7da094ebb31eababce7dd99a2f6ae4a0bbb75b49 | hqs2212586/startMyPython3.0 | /第五章-面向对象/5 属性查找.py | 1,891 | 3.734375 | 4 | class LuffyStudent:
school = 'luffycity'
def __init__(self, name, sex, age): # 实例化时自动调用
self.Name = name
self.Sex = sex
self.Age = age
def learn(self):
print('%s is learning' % self.Name)
def eat(self):
print('%s is sleeping' % self.Name)
# 产生对象
stu1 = LuffyStudent('百合', '女', 12)
stu2 = LuffyStudent('李三炮', '男', 38)
stu3 = LuffyStudent('张铁蛋', '男', 48)
# print(stu1.__dict__)
# print(stu2.__dict__)
# print(stu3.__dict__)
# 对象:特征和技能的结合体
# 类:类是一系列对象相似的特征与相似技能的结合体
# 类中数据属性:是所有对象共有的(都是一样的)
print(LuffyStudent.school, id(LuffyStudent.school))
print(stu1.school, id(stu1.school))
print(stu2.school, id(stu2.school))
"""内存地址一样
luffycity 4325120112
luffycity 4325120112
luffycity 4325120112
"""
# 类中函数属性:是绑定给对象的,绑定到不同的对象是不同的绑定方法,对象调用绑定方法时,会把对象本身当做第一个参数传入,传给self
print(LuffyStudent.learn)
LuffyStudent.learn(stu1)
"""
<function LuffyStudent.learn at 0x1040211e0>
百合 is learning
"""
print(stu1.learn)
print(stu2.learn)
print(stu3.learn)
"""绑定方法,每个人的函数内存地址不同
<bound method LuffyStudent.learn of <__main__.LuffyStudent object at 0x10402cc18>>
<bound method LuffyStudent.learn of <__main__.LuffyStudent object at 0x10402cc50>>
<bound method LuffyStudent.learn of <__main__.LuffyStudent object at 0x10402cc88>>
"""
stu2.learn()
"""
李三炮 is learning
"""
# 属性查找,优先对象中查找,对象中没有在类中查找
# stu1.x = 'from stu1'
LuffyStudent.x = 'from Luffycity class'
print(stu1.__dict__)
print(stu1.x)
"""
{'Name': '百合', 'Sex': '女', 'Age': 12}
from Luffycity class
""" |
382a417bdaf7a8fbb33e33ffa687c1cb21abb3b1 | BondiAnalytics/Python-Course-Labs | /09_exceptions/09_05_check_for_ints.py | 453 | 4.46875 | 4 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
try:
nmbr = int(input("Enter a number: ", ))
except ValueError as error:
print("Please enter a number")
nmbr = int(input("Please retry: ", ))
print(f"Thank you for entering {nmbr}") |
5523c76b6c498a2a24e6e4a7d6b2a0cf44715e55 | lihaineng/little-projects | /plane_war/map.py | 824 | 3.515625 | 4 |
"""
因为地图要移动所以有属性有方法因而将地图看做一个类
"""
import pygame
import random
WIN_X = 512
WIN_Y = 768
class Map(object):
def __init__(self, win):
pygame.init()
self.window = win
self.num = random.randint(1, 5) # 通过随机数产生不一样的地图背景
self.img = pygame.image.load("res/img_bg_level_%s.jpg" % self.num)
self.map_y1 = 0
self.map_y2 = -WIN_Y
def blited(self):
self.window.blit(self.img, (0, self.map_y1))
self.window.blit(self.img, (0, self.map_y2))
def move(self):
if self.map_y1 >= WIN_Y:
self.map_y1 = -WIN_Y
else:
self.map_y1 += 1
if self.map_y2 >= WIN_Y:
self.map_y2 = -WIN_Y
else:
self.map_y2 += 1
|
db9792f1aaf271cf86e3046265f66123fa022ddc | varun2784/python | /qsort.py | 1,039 | 3.859375 | 4 | import random
def qsort_python(keys):
if not keys:
return []
rindex = random.randint(0, len(keys)-1)
pivot = [keys[rindex]]
less = [x for x in keys if x < keys[rindex]]
more = [x for x in keys if x > keys[rindex]]
return less + pivot + more
def qsort(keys):
if not keys:
return []
items = len(keys)
if items == 1:
return keys
rindex = random.randint(0, items-1)
rval = keys[rindex]
keys[rindex] = keys[0]
keys[0] = rval
end = items - 1
start = 1
while start <= end:
cur = keys[start]
if cur > rval:
keys[start] = keys[end]
keys[end] = cur
end -= 1
else:
start += 1
keys[0] = keys[start - 1]
keys[start - 1] = rval
less = qsort(keys[:start - 1])
more = qsort(keys[start:])
return less + [keys[start - 1]] + more
if __name__ == "__main__":
keys = range(20)
random.shuffle(keys)
print keys
sorted = qsort_python(keys)
print sorted
|
dae356181670e4ee363e585ac584c81f454dede2 | shenyiting2018/price-of-chair | /src/app.py | 717 | 3.515625 | 4 |
import requests
from bs4 import BeautifulSoup
request = requests.get("https://www.johnlewis.com/john-lewis-partners-miami-garden-dining-chair-grey/p3711083")
content = request.content
soup = BeautifulSoup(content, "html.parser")
element = soup.find("p", {"class": "price price--large"})
string_price = (element.text.strip()) # "40"
price_without_symbol = string_price[1:] # copy string
price = float(price_without_symbol)
if price < 200:
print("Buy it!")
print("The currnet price is {}.".format(price_without_symbol))
else:
print("Do not buy!")
# https://www.johnlewis.com/john-lewis-partners-miami-garden-dining-chair-grey/p3711083
# <p class="price price--large">£40.00</p>
#print(request.content) |
ac1740688364f5609e9d4535a7196305f8e693ff | jamdoran/euan | /Sess001/euan003.py | 229 | 3.75 | 4 |
def addup(a,b):
return a + b
def minus(a,b):
return a - b
# print (addup(1,1))
# print (minus(10,5))
# Loop
for x in range(1,10000000) :
print (x)
# x = 0
# while x < 12345:
# print (x)
# x = x + 1
|
a1e1b88291179a5584a15459ec2e96bb13358f59 | gabriel-cf/davil | /mymodule/src/backend/algorithms/normalization/standardized_normalization.py | 1,284 | 3.546875 | 4 | """
Standardized
"""
from __future__ import division
from ...util.df_matrix_utils import DFMatrixUtils
STANDARDIZED_ID = "Standardized"
def standardized(df, df_level=False):
""" Will normalize the DataFrame according to their mean and
standard deviation. This makes the normalized values to
have variance and standard deviation.
df: (pandas.DataFrame) dataframe with the values to normalize
[df_level=False]: (Boolean) Whether values mean/std
should be taken from dataframe or column level
"""
def _normalize_column(column, mean=None, std=None):
def _normalize_value(x, mean, std):
return (x - mean) / std
mean = mean if mean else DFMatrixUtils.get_mean_value(column)
std = std if std else DFMatrixUtils.get_std_value(column)
normalized = [_normalize_value(x, mean, std) for x in column]
return normalized
df_mean = None
df_std = None
if df_level:
df_mean = DFMatrixUtils.get_mean_value(df)
df_std = DFMatrixUtils.get_std_value(df)
df = df.apply(lambda column: _normalize_column(column,
mean=df_mean,
std=df_std), axis=0)
return df
|
bda95acfc9faabd6c8f556fa3dfb32711ded2e8b | voidrank/pythonLearning | /src/t64.py | 259 | 3.53125 | 4 | def flatten(nested):
try:
try:
nested + ''
except TypeError:
pass
else:
raise TypeError
for i in nested:
for j in flatten(i):
yield j
except TypeError:
yield nested
nested = ['1123',[1,2,1],[[1,2],1],1]
print list(flatten(nested)) |
22165b652570141a9e9bc16809fe9c395c5f232c | aussio/starveio-bot | /circle.py | 977 | 3.671875 | 4 | import pyautogui
import math
import sys
from time import sleep, time
def move_mouse_in_circle(radius, steps, duration=1):
distance = (math.pi * 2 * radius) / steps
step_duration = duration / steps
# generate 360 decimal coordiantes for a circle'ish shape mouse movement
for i in range(0,steps):
# Get the decimal coordinate of each 'tick' [0.0,1.0]
# using sin/cos function
j = (((i/steps)*2)*math.pi)
x = math.cos(j)
y = math.sin(j)
# plot the mouse coordinates along a oval shape that
# is centered on the middle of the screen.
pyautogui.moveRel(distance * x,
distance * y,
duration = step_duration, # How long it takes to move the mouse each step
_pause=False) # Don't add an arbitrary pause between movements
#if __name__ == '__main__':
# sleep(5)
# num_circles = 10
# for _ in range(num_circles):
# move_mouse_in_circle(200, 15, 1) |
df9bfbf7daab7c74164b9ccc3ac092027de19999 | Rubenoo/Python | /Les4/1. Catching exceptions.py | 724 | 3.546875 | 4 | hotelKosten = 4356
def programma():
while True:
try:
aantalPersonen = int(input('Hoeveel mensen gingen er mee?: '))
if aantalPersonen < 0:
raise Exception
elif aantalPersonen == 0:
raise ZeroDivisionError
else:
break
except ZeroDivisionError:
print('Kan niet delen door 0, voer geldig getal in')
except ValueError:
print('Voer een geldig getal in')
except Exception:
print('Voer een positief getal in')
except:
print('Andere fout')
uitkomst = hotelKosten / aantalPersonen
print('de kosten zijn {}'.format(uitkomst))
programma() |
bce81b89a51494eb8db90f856dc479f4916eeb9f | zqhhn/Python | /day02/code/variable.py | 210 | 3.953125 | 4 | """
使用input()输入
"""
name = input("请输入您的姓名:")
print("Hello,",name)
year = int(input("请输入年份:"))
is_leap = (year % 4 == 0 and year % 100 !=0 or year % 400 == 0)
print(is_leap)
|
a52a3394c353f0aa07726247a154c40972d52766 | Ichbini-bot/python-labs | /03_more_datatypes/2_lists/03_06_product_largest.py | 631 | 4.40625 | 4 | '''
Take in 10 numbers from the user. Place the numbers in a list.
Find the largest number in the list.
Print the results.
CHALLENGE: Calculate the product of all of the numbers in the list.
(you will need to use "looping" - a concept common to list operations
that we haven't looked at yet. See if you can figure it out, otherwise
come back to this task after you have learned about loops)
'''
list = []
for i in range(1,5):
data = int(input("Enter number: "))
list.append(data)
print(list)
list.sort()
print("largest number is: ", list[-1])
total = 1
for i in list:
print(i)
total = total * i
print(total)
|
f029cff8ddb7e844b493dffdc0568fb9856953d8 | ydang5/Assignment-1 | /A1_T2.PY | 119 | 3.578125 | 4 | humidity = 20
if humidity < 30:
print("Dry")
elif humidity > 60:
print("High Humidity")
else:
print("Ok")
|
ee5fb6ef601321b670238b0c409ffd0916c07a8b | hugo-paiva/curso_Python_em_Video | /Exercícios Resolvidos/aula07a.py | 477 | 3.8125 | 4 | sair = False
while sair == False:
print('='*15+' DESAFIO 13 '+'='*15)
l = float(input('Qual é a largura da parede em metros? '))
h = float(input('Qual é a altura da parede em metros? '))
a = h*l
# Cada litro de tinta pinta um área de 2m²
t = a/2
print('Para pintar uma parede de {} metros quadrados são necessários {} litros de tinta.'.format(a,t))
conta =input('Deseja fazer outra conta?(s/n)')
if conta == 'n':
sair = True
|
13979bc36eda56037d981c8724576dc7b10b6db5 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Resolução de problemas II/ListasTuplasDeicionários.py | 3,982 | 4.21875 | 4 | '''
Arrays são chamados de sequências
Tipos
String
s = 'texto'
Lista
São elementos mútáveis
Podem ter elementos de diferentes tipos
l = ['asa', 1]
Tupla
t = (1, 2, 3)
Tuplas e strings não são mutáveis
Mapping (relacionam chave ao valor)
Acesso
Com números positivos e negativos
0 1 2 3
[] [] [] []
-1 -2 -3 -4
Úteis
aList = []
for number in range(1,11):
aList += [number] #Adiciona elementos na listas
#Os dois elementos são listas
print(aList)
==============================================================
#Via elemento
for item in aList:
print(item) #imprime todos os elementos da lista
#Via índice
for i in range(len(aList)):
print(aList[i]) #imprime todos os elementos da lista
===============================================================
Histograma
values = [0] * 10 # cria uma lista com 10 valores iguais a zero
print('10 inteiros')
for i in range(10):
newValue = int(input('Valor: '))
for i in range(len(values)):
print(values[i] * '*')
==============================================================
Tuplas - lista que não pode ser mudada
currentHour = hour, minute, second
print(currentTime[0])
===============================================================
Desempacotar sequências
aString = 'abc'
first, second, third = aString
===============================================================
Slicing
sequencia[inicio : ]
sequencia[inicio : fim]
sequencia[ : fim]
sequencia[inicio : incremento : fim]
até fim-1
===============================================================
Dicionários
Coleção de valores associativos
Chave -> valor
dictionart = {}
dictionary = {1 : 'one', 2 : 'two'}
> Manipulando
nums = {1 : 'one', 2 : 'two'}
nums[3] = 'three' #adiciona ao dicionárioo
del nums[3] #removendo 3
nums[1] = 'ones' #alterando valor
===============================================================
Métodos = lista, tupla, dicionário (built-in types)
append(item) Insere item no final da lista
count( elemento ) Retorna o número de ocorrencias de elemento na lista.
extend( newList ) Insere os elementos de newList no final da lista
index( elemento ) Returna o indice da primeira ocorrência de elemento na lista
insert( indice, item ) Insere item na posição indice
pop( [indice] ) Sem parametro – remove e retorna o último elemento da lista. Se indice é especificado, remove e retorna o elemento na posição indice.
remove( elemento ) Remove a primeira ocorrencia de elemento da lista.
reverse() Inverte o conteúdo da lista
sort( [function] ) Ordena o conteúdo da lista.
===============================================================
Mpetodos de dicionário
clear() Apaga todos os item do dicionário
copy() Cria uma cópia do dicionário. Cópia referencia o dicionário original
get( key [, returnValue] ) Retorna o valor associado à chave. Se chave não está no dicionário e returnValue é dado, retorna-o.
has_key( key ) Returna 1 se a chave está no dicionário; 0 se não está.
items() Retorna uma lista de tuplas no formato chave-valor.
keys() Retorna uma lista das chaves do dicionário.
popitem() Remove e retorna um par arbitrário como uma tupla de dois elementos.
setdefault( key [,value] ) Se key não está no dicionário e value é especificado, insere o par key-value. Se value não é especificado, value é None.
update( newDictionary ) Adiciona todos pares chave-valor de newDictionary ao dicionário corrente e sobrescreve os valores para as chaves ja existentes.
values() Retorna uma lista de valores no dicionário.
for key in dicionario.keys():
from copy import deepcopy
copiaDistinta = deepcopy(dictionary)
'''
list = ['a','b','c']
list.remove('a')
print(list) |
95ee2e1164e36d1db221e4ba1377b14fd28ba926 | pounders82/rock-paper-scissor | /rock-paper-scissors.py | 673 | 3.984375 | 4 |
import random
print('...rock....')
print('...paper...')
print('...scissors...')
e = True
while e == True:
a = ['rock', 'paper', 'scissors']
b = input("Please enter a choice: ").lower()
c = random.choice(a)
if b in a:
if (b == 'rock' and c == 'scissors') or (b == 'scissors' and c == 'paper') or (b == 'paper' and c == 'rock'):
print("The computers's choice is " + c)
print("You Win")
e = False
elif (b == 'scissors' and c == 'rock') or (b == 'paper' and c == 'scissors') or (b == 'rock' and c == 'paper'):
print(c)
print("You Lose")
e = False
else:
print(c)
print("Draw throw again!")
else:
print("That is not a choice! Try Again!") |
952a6382a34432f15eccc379acb8abab11023a4e | JohnnyYamanaka/Uri_challenge_python | /1924.py | 135 | 3.890625 | 4 | qty_course = int(input())
courses = []
for course in range(0, qty_course):
courses.append(input())
print("Ciencia da Computacao") |
eb474a5b9cea520da10b4ebc5f90675794ae9d44 | Emmalindal/MAT-IN1105 | /uke 2/f2c_table_while.py | 638 | 3.828125 | 4 | #Exercise 2.1: Make a Fahrenheit-Celsius conversion table
#F = []
#C = F - 32*(5/9)
F = 0
steps = 10
while F <= 100:
C = F-(32*(5/9))
#print with 6 digits in total, 2 decimals:
print('Fahrenheit %.2f Celsius %.2f' %(F,C))
F = F + steps
"""
Terminal> Python f2c_table_while.py
Fahrenheit 0.00 Celsius -17.78
Fahrenheit 10.00 Celsius -7.78
Fahrenheit 20.00 Celsius 2.22
Fahrenheit 30.00 Celsius 12.22
Fahrenheit 40.00 Celsius 22.22
Fahrenheit 50.00 Celsius 32.22
Fahrenheit 60.00 Celsius 42.22
Fahrenheit 70.00 Celsius 52.22
Fahrenheit 80.00 Celsius 62.22
Fahrenheit 90.00 Celsius 72.22
Fahrenheit 100.00 Celsius 82.22
"""
|
0829af3fd85597f382c87801781b14fa50302a5d | rafaelperazzo/programacao-web | /moodledata/vpl_data/87/usersdata/228/53539/submittedfiles/contido.py | 332 | 3.703125 | 4 | # -*- coding: utf-8 -*-
n=int(input('digite o numero de elementos de a:'))
m=int(input('digite o numero de elementos de b:'))
listaa=[]
listab=[]
for i in range (0,n,1):
elea=int(input('digite o elemento:'))
listaa.append(elea)
for i in range(0,m,1):
eleb=int(input('digite o elemento:'))
listab.append(eleb)
|
be9c9db9862b5a5dd6e5609f57d89a46a0268437 | mastja/pythonSockets_clientServerChat | /server.py | 2,369 | 3.53125 | 4 | # Project 4 - Server and Client Chat Program - server file
# Programmer - Jacob Mast
# Date 8/5/2020
# Description - Simple client-server program using python sockets. Program emulates a simple chat server.
# source. 1 - https://www.binarytides.com/python-socket-programming-tutorial/
# source. 2 - https://realpython.com/python-sockets/#running-the-echo-client-and-server
# source. 3 - https://www.biob.in/2018/04/simple-server-and-client-chat-using.html
# source. 4 - https://stackoverflow.com/questions/45936401/string-comparison-does-not-work-in-python
import socket #for sockets
import sys #for exit
#source for setting up the socket - https://www.binarytides.com/python-socket-programming-tutorial/
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 8888 # Port to listen on (non-privileged ports are > 1023)
name = "Server"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind(('', PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#source for code and loop below: https://www.biob.in/2018/04/simple-server-and-client-chat-using.html
s_name = conn.recv(1024)
s_name = s_name.decode()
print '\n' + s_name + ' has connected to the chat room\nEnter "/q" to quit\n'
conn.send(name.encode())
#quit message from client, for use in if statement below
client_quit = 'Left chat room!'
#send and receive messages with the client in loop until a quit message is either sent or received
while True:
message = raw_input(str('Me : '))
message = message.strip() #source: https://stackoverflow.com/questions/45936401/string-comparison-does-not-work-in-python
if message == '/q':
message = 'Left chat room!'
conn.send(message.encode())
print '\n'
break
conn.send(message.encode())
message = conn.recv(1024)
message = message.decode()
print s_name + ' : ' + message
if message == client_quit:
break
#close the connection
conn.close()
print 'client disconnected\n'
s.close()
print 'program closing' |
56d1fb239d0d371ebc47353ffbf6c38fe7dd5f99 | IfDougelseSa/cursoPython | /exercicios_secao5/2.py | 143 | 3.96875 | 4 | # raiz quadrada
import math
x = float(input("Digite o número: "))
if x >= 0:
print(math.sqrt(x))
else:
print("Número inválido!!")
|
a2f3ba6e7e83b66334b0b5d7e7bf0f8f8d90e1c4 | bhumilad/full-python- | /oops10.py | 911 | 4.1875 | 4 | # abstract method
#
# from abc import ABC , abstractmethod
#
# class Shape(ABC):
# @abstractmethod
# def area(self):
# return 0
#
# class Rect(Shape):
# type="rectangle"
# sides=4
#
# def __init__(self):
# self.length='5'
# self.breadth='10'
#
# def area(self):
# return self.length*self.breadth
#
# r= Rect()
# print(r.area())
print("___________________________________________________________________________________________")
#setter & property decoraters
#
# class Employee:
#
# def __init__(self,fname,lname):
# self.fname=fname
# self.lname=lname
# self.email=f"{fname}{lname}@gmail.com"
#
# def detalis(self):
# return f" the employee is {self.fname} {self.lname}"
#
# def email(self):
# pass
#
# emp=Employee("jerry","lad")
# print(emp.email)
# print(emp.detalis())
|
3d3bf7958416a414b4e141f8e2405a9f3466202f | mymorkkis/chess-python | /src/game_errors.py | 1,460 | 4.125 | 4 | """User defined exceptions for chess game.
Exceptions:
NotOnBoardError: Passed coordinates not on game board
PieceNotFoundError: No piece located at from coordinates
InvalidMoveError: Invalid move attempted
"""
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class NotOnBoardError(Error):
"""Exception raised for passed coordinates are not on game board.
Attributes:
coords: Coordinates that caused the exception
message: Explanation of the error
"""
def __init__(self, coords, message):
self.coords = coords
self.message = message
class PieceNotFoundError(Error):
"""Exception raised when no piece is located at passed from coordinates.
Attributes:
coords: Coordinates that caused the exception
message: Explanation of the error
"""
def __init__(self, coords, message):
self.coords = coords
self.message = message
class InvalidMoveError(Error):
"""Exception raised when invalid move attempted on game board.
Attributes:
from_coords: Attempted to move piece from
to_coords: Attempted to move piece to
message: Explanation of the error
"""
def __init__(self, from_coords, to_coords, message):
self.from_coords = from_coords
self.to_coords = to_coords
self.message = message
|
0774dd1c0d17f4f43d9fedfe7774c607961bc63c | sandrabee/Udacity_CS101 | /Unit7/list_explosion.py | 604 | 3.96875 | 4 | #List Explosion
#Define a procedure, explode_list, that takes as inputs a list and a number, n.
#It should return a list which contains each of the elements of the input list,
#in the original order, but repeated n times.
def explode_list(p,n):
l = []
count = n
while count > 0:
for i in range(len(p)):
l.append(p[i])
count -=1
l.sort()
return l
#For example,
#print explode_list([1, 2, 3], 2)
#>>> [1, 1, 2, 2, 3, 3]
#print explode_list([1, 0, 1], 0)
#>>> []
print explode_list(["super"], 5)
#>>> ["super", "super", "super", "super", "super"]
|
288e5bff74c0533399d4ef4ae0b0929da21f2b83 | manikandanmass-007/manikandanmass | /Python Programs/program to covert celcius to fahrenheit.py | 169 | 4.25 | 4 | #program to covert celcius to fahrenheit
cel=(int(input("entetr the celcius value:")))
fahren=(1.8* cel)+32
print ("the fahrenheit value of",cel,"celcius is:",fahren) |
d6cb545d608c82a3d9dc3d7efbd296a54633daaa | chuyuanli/RR-mix-product-polarity-detection- | /RawData/json_txt.py | 3,745 | 3.5625 | 4 | import json
import os
def pre_processing(rawString):
"""pre-processing: delect strings like '\x92', normalize words"""
# 1.eliminate the space at the begining
if rawString.startswith(" "):
rawString = rawString[1:]
# change to lower-case
rawString = rawString.lower()
# 2.unicodes to be changed
changes = {(u"\x93", u"\x94", u"\x96", u"\r", u"<em>", u"</em>", "{", "}"):u"",
(u"\x92",u"''", u"\'", u"’"):u"'",
(u"\x97",u"\n"):u" "}
# use replace to clean the raw sentences
for oldS, replacemt in changes.items():
for old in oldS:
rawString = rawString.replace(old, replacemt)
# 3.promotion sentences to be delected
to_delect = "[this review was collected as part of a promotion.]".split()
possible_parts = []
for i in range(len(to_delect)):
part = ' '.join(to_delect[:len(to_delect)-i])
possible_parts.append(part)
for part in possible_parts:
if rawString.endswith(part):
rawString = rawString.replace(part, "")
# 4. negation spelling correction
negWords = "doesnt didnt wasnt dont havent cant couldnt wouldnt shouldnt".split()
for i in range(len(negWords)):
if negWords[i] in rawString:
rawString = rawString.replace(negWords[i], negWords[i][:-2]+"n't")
#return pre-processed sentence
# print(rawString)
return rawString
# pre_processing("It doesn\x92t help with hydration. If that''s the smell you''re going for, [This review was collected as part of a promotion.]")
#======================================================================
def extract_from_json(file):
"""
read a json file and transform into csv file
format: nb \t id \t sent \t tone
"""
# with urllib.request.urlopen(url) as url2:
# data = json.loads(url2.read().decode())
try:
f = open(file, 'r')
data = json.load(f)
with open ('fr_11k_neg.csv','w') as output:
i = 1
for nb, content in data["highlighting"].items():
# print(content)
for phrase in content.values():
# print(phrase)
phrase = pre_processing(str(phrase)[2:-2])
# print(phrase)
# input()
output.write(str(i)+'\t'+str(nb)+'\t'+str(phrase)+'\tnegatif')
i += 1
output.write('\n')
# input()
output.close()
f.close()
except FileNotFoundError:
print("ERROR: "+ str(file) + " doesn't exist.")
# file = 'fr_11k_neg.json'
# extract_from_json(file)
#======================================================================
def pure_text(file):
with open(file, 'r') as f:
data = f.readlines()
with open('MarkovGenerator/example_neg.txt','w') as output:
for line in data[101:200]:
phrase = line.split('\t')[2]
# print(phrase)
# input()
output.write(str(phrase)+'\n')
output.close()
f.close()
# file = '18k_neg_hl.csv'
# pure_text(file)
#======================================================================
def count_voc(csvFile):
""" check the nb of voc, sent and token in a csv file"""
voc = []
sent = 0
with open(csvFile) as f:
lines = f.readlines()
for line in lines:
phrase = line.split('\t')[2]
voc.extend(phrase.split())
# print(voc)
# input()
sent += 1
f.close()
print(sent)
print(len(voc))
print(len(set(voc)))
# count_voc('fr_25k_pos.csv')
|
633321378c874830b1801188878bfb27d524768f | nsinghai/FST-M1 | /python/Activity6.py | 168 | 4.125 | 4 | # Activity:6 - Pattern Generator
# Write a Python program to construct the following pattern, using a nested loop number.
for i in range(10):
print(str(i) * i) |
203d5e271c8a80d70cf5404716b0703c1a726ad7 | suleymankhrmn/python-assignment | /Assignment-1(if-Statements).py | 396 | 4.09375 | 4 | userInfo = {
"Suleyman" : "123",
"Joseph" : "ujk"
}
checkValue = False
entryUsername = input("Please enter your username: ")
for value in userInfo:
if(value == entryUsername):
checkValue = True
if(checkValue):
print("Hello " + entryUsername + " your password " + userInfo[entryUsername])
else:
print("Hello " + entryUsername + ", See you later.")
|
ef7bc6baebe9da661971f875426bd9c46b2b41b0 | Youbornforme/Python9.HW | /hw6.sizes.py | 879 | 3.640625 | 4 | sizes = {
'XXS': {'Russia': 42, 'Germany': 36, 'USA': 8, 'France': 38, 'UK': 24},
'XS': {'Russia': 44, 'Germany': 38, 'USA': 10, 'France': 40, 'UK': 26},
'S': {'Russia': 46, 'Germany': 40, 'USA': 12, 'France': 42, 'UK': 28},
'M': {'Russia': 48, 'Germany': 42, 'USA': 14, 'France': 44, 'UK': 30},
'L': {'Russia': 50, 'Germany': 44, 'USA': 16, 'France': 46, 'UK': 32},
'XL': {'Russia': 52, 'Germany': 46, 'USA': 18, 'France': 48, 'UK': 34},
'XXL': {'Russia': 54, 'Germany': 48, 'USA': 20, 'France': 50, 'UK': 36},
'XXXL': {'Russia': 56, 'Germany': 50, 'USA': 22, 'France': 52, 'UK': 38}}
input_size = input("Input international size: ")
get_size = input("Convert to size: ")
def convert():
if get_size in sizes[input_size]:
print(get_size, "size: ", sizes[input_size][get_size])
else:
print("size is not found")
convert() |
0aa1ad385f6a99ccfe1a55073e1350a6863493d6 | urmilasalke/python-Program | /basic/ifel.py | 80 | 3.578125 | 4 | a=10
b=20
if a>b:
print("a largest")
elif a<b:
print("b largest")
|
f8d7edb02e9ad2cd011822964fb05a42fe1c53c7 | betty29/code-1 | /recipes/Python/580613_Generate_set_random/recipe-580613.py | 315 | 4 | 4 | """Generate a set of random numbers based on the number requested."""
import random
try:
numbers = input("How many numbers do you want generated? ")
for num in range(int(random.random() + 1), int(numbers) + 1):
print(random.randint(num, num * 10))
except ValueError:
print("Input is invalid!")
|
70d6035e7a673046255dc03d1b1ca37366940a55 | dusgn/sparta_algorithm | /week_1/homework/01_find_prime_list_number.py | 1,876 | 4 | 4 | # input = 4
#
#
# def find_prime_list_under_number(number):
# prime_num = list()
# if number < 2:
# return [number]
# for num in range(2, number+1):
# if num == 2 or num == 3 or num == 5:
# prime_num.append(num)
# continue
# elif num % 2 == 0 or num % 3 == 0 or num % 5 == 0:
# continue
# elif number % num == 0:
# continue
# else:
# prime_num.append(num)
#
# return prime_num
#
#
# result = find_prime_list_under_number(input)
# print(result)
# input = 20
#
# def find_prime_list_under_number(number):
# prime_list = []
#
# for n in range(2, number+1):
# for i in range(2, n):
# if n % i == 0:
# break
# else:
# prime_list.append(n)
#
# return prime_list
#
#
# result = find_prime_list_under_number(input)
# print(result)
# input = 20
#
#
# def find_prime_list_under_number(number):
# prime_list = []
#
# for n in range(2, number + 1): # n = 2 ~ n
# for i in prime_list: # i = 2 ~ n-1
# if n % i == 0:
# break
# else:
# prime_list.append(n)
#
# return prime_list
#
#
# result = find_prime_list_under_number(input)
# print(result)
input = 20
# 소수는 자기자신과 1외에는 아무것도 나눌 수 없다.
# 주어진 자연수 N이 소수이기 위한 필요 충분 조건
# N이 N의 제곱근보다 크지 않은 어떤 소수로도 나눠지지 않는다.
def find_prime_list_under_number(number):
prime_list = []
for n in range(2, number + 1): # n = 2 ~ n
for i in prime_list: # i = 2 ~ n-1
if n % i == 0 and i * i <= n:
break
else:
prime_list.append(n)
return prime_list
result = find_prime_list_under_number(input)
print(result) |
6fa5bc72d4af8243be44a19cae1af9843f0c199d | enricodangelo/exercises-in-style | /python/coursera_python_spec/4.6-assignement.py | 1,172 | 4.4375 | 4 | # 4.6 Write a program to prompt the user for hours and rate per hour using
# raw_input to compute gross pay. Award time-and-a-half for the hourly rate for
# all hours worked above 40 hours. Put the logic to do the computation of
# time-and-a-half in a function called computepay() and use the function to do the
# computation. The function should return a value. Use 45 hours and a rate of
# 10.50 per hour to test the program (the pay should be 498.75). You should use
# raw_input to read a string and float() to convert the string to a number. Do not
# worry about error checking the user input unless you want to - you can assume
# the user types numbers properly. Do not name your variable sum or use the sum()
# function.
def computepay(hours,rate):
total = 0.0
exceedHours = hours - 40.0
exceedRate = rate * 1.5
if (exceedHours > 0):
exceed = exceedHours * exceedRate
hours = hours - exceedHours
base = hours * rate
total = base + exceed
return total
raw_hours = raw_input("Enter Hours: ")
hours = float(raw_hours)
raw_rate = raw_input("Enter Rate: ")
rate = float(raw_rate)
total = computepay(hours, rate)
print total
|
b92b9e302493bb68a4d3f2a10651add0330074bd | 0x0400/LeetCode | /p234.py | 768 | 3.90625 | 4 | # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
from common.tree import TreeNode
# # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
minVal = min(p.val, q.val)
maxVal = max(p.val, q.val)
curNode = root
while True:
if minVal <= curNode.val <= maxVal:
return curNode
if curNode.val > maxVal:
curNode = curNode.left
continue
if curNode.val < minVal:
curNode = curNode.right
|
888e28eceee3f05bc97fa5ec671050c57ac60ffa | oliveirajonathas/python_estudos | /pacote-download/pythonProject/cursoguanabara/aula19.1.py | 309 | 4 | 4 | brasil = []
estado1 = {'uf': 'Rio de Janeiro', 'sigla':'RJ'}
estado2 = {'uf':'São Paulo', 'sigla': 'SP'}
brasil.append(estado1)
brasil.append(estado2)
print(f'Dicionário estado1: {estado1}')
print(f'Dicionário estado2: {estado2}')
print(f'Lista: {brasil}')
print(brasil[0]['uf'])
print(brasil[1]['sigla'])
|
da31fc1b47505f00e2a4cce99baa37b2d50c91d6 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습12-2]120210198_윤동성_3.py | 227 | 4.21875 | 4 |
def trans():
global s
for i in range(3):
print("***original string: %s ***##" %s, end="")
s = "The string printed out!"
print(s)
return s
s = input("Enter the string: ")
trans()
print(s)
|
bb1e866796e893b17e694efe7b956e2d216cdaba | groodt/project-euler | /1/problem1.py | 203 | 3.75 | 4 | #!/usr/bin/python
if __name__ == '__main__':
multiples_of_3_or_5 = [i for i in range(1,1000) if (i % 3 == 0 or i % 5 == 0)]
sum = 0
for i in multiples_of_3_or_5:
sum+=i
print sum |
5ee1ecbd0c7545ccc93b49c3312d271f7860330e | omatveyuk/interview | /CodeFights/matrix_elements_sum.py | 1,349 | 4.28125 | 4 | """ Find sum of matrix elements.
Input a rectangular matrix, each cell containing an integer. Some cells are 0.
That is why any cell that is 0 or is located anywhere below 0 in the same column
is not considered to sum.
Calculate the total price of all the cells that are suitable for condition.
Example: 0 1 1 2 Suitable for condition: x 1 1 2
0 5 0 0 x 5 x x
2 0 3 3 x x x x
>>> matrixElementsSum([[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]])
9
>>> matrixElementsSum([[1,1,1,0], [0,5,0,1], [2,1,3,10]])
9
"""
def matrixElementsSum(matrix):
total_sum = sum(matrix[0][j] for j in xrange(len(matrix[0])))
unsuitable_columns = set([j for j in xrange(len(matrix[0])) if matrix[0][j] == 0])
for row in xrange(1, len(matrix)):
for column in xrange(len(matrix[0])):
if column not in unsuitable_columns:
if matrix[row-1][column] != 0:
total_sum += matrix[row][column]
else:
unsuitable_columns.add(column)
return total_sum
if __name__ == "__main__":
debug = True
if debug:
from doctest import testmod
if testmod().failed == 0:
print "********** All Tests are passed. *************"
|
fbc5bf8120a051749d8b83f77ae39f58681bf0f0 | littlebluewhite/Backen-Engineer-Exercise | /Backen Engineer Exercise(python)/solution1.py | 968 | 4.125 | 4 | # 1. Please implement a string function in a numeric format in a language that you
# are good at. And mark every three digits with a comma. Please attach unit
# test.
# f(9527) => "9,527", f(3345678) => "3,345,678", f(-1234.45) => "-1,234.45"
def numeric_format(s):
s = str(s)
result = ""
int_list = []
if s[0:1] == "-":
result += "-"
is_decimal = s.find(".")
if is_decimal != -1:
n_decimal = s[is_decimal:]
positive_int = abs(int(float(s)))
while positive_int >= 1000:
int_list.append(str(positive_int % 1000).zfill(3))
positive_int = positive_int // 1000
result += str(positive_int)
if int_list:
result += ","
result += ",".join(int_list[::-1])
if is_decimal != -1:
result += n_decimal
return result
if __name__ == '__main__':
print(numeric_format(9527))
print(numeric_format(3345678))
print(numeric_format(-1234.45))
|
3bca70bdc292e39841b0f4f1ef0e1268cf919c56 | GuanzhouSong/Leetcode_Python | /Leetcode/81. Search in Rotated Sorted Array II.py | 760 | 3.59375 | 4 | class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
start = 0
end = len(nums) - 1
mid = -1
while start <= end:
mid = (start + end) // 2
if nums[mid] == target:
return True
if nums[mid] < nums[end] or nums[mid] < nums[start]:
if nums[mid] < target <= nums[end]:
start = mid + 1
else:
end = mid - 1
elif nums[mid] > nums[start] or nums[mid] > nums[end]:
if nums[mid] > target >= nums[start]:
end = mid - 1
else:
start = mid + 1
else:
end -= 1
return False
s = Solution()
nums = [7, 8, 9, 0, 1, 2, 2, 3, 4, 4, 5, 6, 7]
print(s.search(nums, 7))
|
1a08d6a97969400717246d6eb83eaaff027bd1bd | zhiyunl/lcSolution | /0938RangeSumofBST.py | 1,912 | 3.8125 | 4 | """
Given the root node of a binary search tree,
return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
Note:
The number of nodes in the tree is at most 10000.
The final answer is guaranteed to be less than 2^31.
Idea:
1. inorder traversal method, add when meet the criteria, O(n)
2. logn to find the first node, successor finding method takes O(1), O(logn +k)
3. DFS, find the first node in range, then traversal subtrees. only visit node in criteria.
"""
from helper import *
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
cnt = 0
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
# inorder traversal
def inorder(tree):
if tree is None:
return None
inorder(tree.left)
if L <= tree.val <= R:
self.cnt += tree.val
inorder(tree.right)
return None
inorder(root)
return self.cnt
def rangeSumBST2(self, root: TreeNode, L: int, R: int) -> int:
# DFS
def dfs(tree):
if tree is not None:
if L <= tree.val <= R:
self.cnt += tree.val
if L < tree.val:
dfs(tree.left)
if R > tree.val:
dfs(tree.right)
dfs(root)
return self.cnt
if __name__ == '__main__':
sl = Solution()
nums = "[10,5,15,3,7,13,18,1,null,6]"
root = stringToTreeNode(nums)
L = 6
R = 10
tmp = sl.rangeSumBST2(root, L, R)
print(tmp)
|
65ffd09d4d2d792f58d772e43a8253587a66813c | anupamnepal/Programming-for-Everybody--Python- | /3.3.py | 621 | 4.46875 | 4 | #Write a program to prompt the user for a score using raw_input. Print out a letter
#grade based on the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error message and exit.
#For the test, enter a score of 0.85.
score = raw_input("Enter you score")
try:
score = float(score)
except Exception, e:
print "Enter a valid float Value"
quit()
if score >= 0.9 :
letter = 'A';
elif score >= 0.8 :
letter = 'B';
elif score >= 0.7 :
letter = 'C';
elif score >= 0.6 :
letter = 'D';
elif score < 0.6 :
letter = 'E';
print letter |
ae32a925f8cfaca533ee5ebe642ae169010d3aa3 | FigNewton0/Python-Project-Portfolio | /Term 3/BlackJack/cards.py | 2,372 | 4.03125 | 4 | import random
class Card(object):
"""a playing card"""
RANKS = ["A","2","3","4","5","6","7",
"8","9","10","J","Q","K"]
SUITS = ["♣","♢","♡","♠"]
def __init__(self,rank,suit, face_up = True):
self.rank = rank
self.suit = suit
self.is_face_up = face_up
def __str__(self):
if self.is_face_up:
rep = self.rank + self.suit
else:
rep = "XX"
return rep
def flip(self):
self.is_face_up = not self.is_face_up
class Hand(object):
"""This class creates a players hand of cards and interact with that hand.
You can clear your hand which removes all the cards from that hand
You can add a card to your hand
You can also give a card from your hand to another player's hand"""
def __init__(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card)+" "
else:
rep = "<empty>"
return rep
def clear(self):
self.cards = []
def add(self,card):
self.cards.append(card)
def give(self,card,other_hand):
self.cards.remove(card)
other_hand.add(card)
class Deck(Hand):
"""This is your deck with your deck you can do all the methods of Hand and populate, shuffle, and deal
to populate do deck.populate()
to shuffle deck.shuffle()
to deal you do deck.deal(where you want to deal to,the ammount of cards you want to deal to these hands
"""
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank,suit))
def shuffle(self):
random.shuffle(self.cards)
def deal(self, hands, per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card,hand)
else:
print("Can't contuinue deal. We be out of cards up in this, homie")
if __name__ =="__main__":
print("Your ran this module directly (and did not 'import' it).")
input("\n\nPress the enter key to exit")
|
ce4c30f7e48e51d30dc29c094badfecfe05899ca | fekisa/python | /lesson_4/homework_4_6.py | 764 | 4.34375 | 4 | '''
6. Реализовать два небольших скрипта:
а) бесконечный итератор, генерирующий целые числа, начиная с указанного,
б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools.
'''
from itertools import count
from itertools import cycle
for el in count(int(input('Введите стартовое число '))):
print(el) # беконечный цикл
my_list = [1, 'abc', 123, 'hello']
for el in cycle(my_list):
print(el) # беконечный цикл |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.