blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
10a10c46843adf9ccc5c3c1437ae3ff7083c7cfe | hevalenc/-Python-Introduction-to-Data-Science-and-Machine-learning | /numpy_basic_calculations.py | 246 | 3.71875 | 4 | import numpy as np
var1 = np.array([2, 4, 6]) #array de 1 dimensรฃo
print(var1)
var1 = np.array([(2, 4, 6), (1, 3, 5)]) #array de 2 dimensรตes
var2 = np.array([(2, 4, 6), (1, 3, 5)])
print('var1: ',var1)
print('var2: ',var2)
print(var1 + var2) |
8464dda736161badc5d71c0a53e7c766e40629eb | click-here/practicing-python-classes | /home-inventory/inventory_1.py | 547 | 3.9375 | 4 | class Item:
item_location = "click-here's home"
def __init__(self, name, home_location):
self.name = name
self.home_location = home_location
def __str__(self):
return "Item " + self.name
class Food(Item):
def __init__(self, name, home_location='Kitchen'):
self.name = name
self.home_location = home_location
tv = Item('Sony TV','Living Room')
pizza = Food('Left over Dominos')
print(tv)
print(tv.name)
print(tv.home_location)
print(pizza)
print(pizza.name)
print(pizza.home_location)
|
3d06bb681b3256c79cd2108cc046cc707e3071d9 | wherculano/Curso-Selenium-com-Python | /Exercicios Introduรงรฃo ao Python/011 - Nome e vogais.py | 282 | 4.1875 | 4 | """
Faรงa um programa que itera em uma string e toda vez que uma vogal aparecer
na sua string, print o seu nome entre elas
"""
vogais = 'aeiou'
string = 'bananas'
nome = input('Nome: ')
for letra in string:
if letra in vogais:
print(nome)
else:
print(letra)
|
d79bcb8f3c2efd0c375c7eb1ada3d4ac1f1d1581 | wangbqian/python_work | /cainiao/cainiao_1.py | 318 | 3.6875 | 4 | """1.ๆฏๅฆ่ช็ถๆฐ10ไปฅไธ่ฝ่ขซ3ๆ่
5ๆด้ค็ๆ,3,5,6ๅ9๏ผ้ฃไน่ฟไบๆฐๅญ็ๅไธบ23.
ๆฑ่ฝ่ขซ3ๆ่
5ๆด้ค็1000ไปฅๅ
ๆฐๅญ็ๅ"""
# sum = 0
# for i in range(1000):
# if i % 3 == 0:
# sum+=i
# elif i%5 == 0:
# sum+=i
print(sum(i for i in range(1000)if i%3 == 0 or i%5 == 0)) |
e12382f36f55bc920681019a9967212628fca441 | Anasshukri/Lets-Learn-Python | /Calculate My Age.py | 688 | 4.0625 | 4 | from datetime import date
def ask_for_date(name):
data = input('Enter ' + name + ' (yyyy mm dd): ').split(' ')
try:
return date(int(data[0]), int(data[1]), int(data[2]))
except Exception as e:
print(e)
print('Invalid input. Follow the given format')
ask_for_date(name)
def calculate_age():
born = ask_for_date('your date of birth')
today = date.today()
extra_year = 1 if ((today.month, today.day) < (born.month, born.day)) else 0
extra_months = 12 if (today.month < born.month) else 0
return today.year - born.year - extra_year, "years and", extra_months + today.month - born.month, "months old"
print(calculate_age()) |
5aaac4f4e78a06f4625dcffb63d73bdc169a510e | Nidhi4-p/python | /python_practice/p6.py | 724 | 4.46875 | 4 | '''question:You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91')'''
code:
import operator
p=[]
st=""
while True:
line=input()
if (line==st):
break
p.append(tuple((line).split(",")))
p.sort(key = operator.itemgetter(0,1,2))
for k in p:
print(",".join(k))
|
12f8e890727dd995210daf79473c975530793444 | matheuskiser/pdx_code_guild | /python/dungeon_crawler/main.py | 3,475 | 3.890625 | 4 | from player import Player
from monster import *
import random
# Displays to player what they want to do
def display_menu():
option = 0
while option != 2:
print "1. Start a game"
print "2. Exit"
option = int(raw_input("Pick an item: "))
pick_option(option)
# Picks option from what user picked
def pick_option(option):
if option == 1:
# Start game
start_game()
elif option == 2:
# Exit program
print "Thanks for playing!\n"
# If random number comes to be even, then monster attacks
def random_monster_attack(player, monster):
rand_number = random.randint(0, 100)
if monster.get_health() > 0:
# Monster attacks player if rand_number is even
if rand_number % 2 == 0:
player.take_hit(monster.get_hit_points(), monster.get_name())
# Displays the player's status after the attack
player.get_status()
# Pick a different monster based on the player's level
def pick_monster(level, player):
if level == 1:
monster_obj = Fluffy(player.get_health(), player.get_hit_points())
elif level == 2:
monster_obj = Ghost(player.get_health(), player.get_hit_points())
elif level == 3:
monster_obj = Clown(player.get_health(), player.get_hit_points())
else:
monster_obj = Monster()
return monster_obj
# Check health of player, levels up player, and moves player to next level
def check_health(player, monster):
if player.get_health() <= 0:
print "You just died, retry!"
elif monster.get_health() <= 0:
print "You killed " + monster.get_name() + "!"
# If player kills monster, then player's level raises by 1
player.raise_level()
# If there are still levels to play, then start the next level
if player.get_level() <= 3:
player_choice(player.get_level(), player)
# Engine of game
def player_choice(level, player):
# Creates a monster based on the level of the player
monster = pick_monster(level, player)
# Displays user the Monster's information
print "You are now facing monster " + monster.get_name()
print "It has " + str(monster.get_health()) + " health and has " + str(monster.get_hit_points()) + " hit points."
# Keeps player attacking if player and monster are still alive
while player.get_health() > 0 and monster.get_health() > 0:
choice = raw_input("Would you like to attack? ")
if choice.lower() == "yes" or choice.lower() == "y":
# Attacks the monster with player's hit points
monster.take_hit(player.get_hit_points())
# Displays monster's health status
monster.get_status()
# Monster's random attach
random_monster_attack(player, monster)
else:
# If player does not attack, then monster attacks
player.take_hit(monster.get_hit_points(), monster.get_name())
# Displays player's health status
player.get_status()
# Checks user's and monster's health when player's or monster's health are 0 or less
check_health(player, monster)
# Starts game and lets player pick a name - Only called once per game
def start_game():
player_name = raw_input("Name of player: ")
# Creates player
player = Player(player_name)
player.display_player_config()
player_choice(1, player)
# Runs game
display_menu() |
d32dd8fdc7640533d95acb78f66181204947d004 | StefanDimitrovDimitrov/Python_Fundamentals | /Python_Fundamentals/Fundamentals level/01.List Basics- lab/13.Seize the Fire.py | 1,049 | 3.984375 | 4 | # 1. Validate input
# 2. Check Water to a fire Amount
# 3. Calculate Water
# 4. Calculate Effort
def IsItInRange(type, value):
if type == 'High' and value >= 81 and value <= 125:
return True
if type == 'Medium' and value >= 51 and value <= 80:
return True
if type == 'Low' and value >= 1 and value <= 50:
return True
return False
fire_list = input().split("#")
# print(fire_list)
water_amount = int(input())
effort = 0
list_cell_output = []
total_fire = 0
value_of_cell = 0
for pair in fire_list:
type_of_fire = pair.split(" = ")[0]
value_of_cell = int(pair.split(" = ")[1])
if IsItInRange(type_of_fire, value_of_cell):
if water_amount >= value_of_cell:
water_amount -= value_of_cell
total_fire += value_of_cell
effort += float((25 / 100) * value_of_cell)
list_cell_output.append(value_of_cell)
print("Cells:")
for cell in list_cell_output:
print(f" - {cell}")
print(f"Effort: {effort:.2f}")
print(f"Total Fire: {total_fire}")
|
0417fd64d0ae6afde3f50610475067934b5a4a61 | LzWaiting/00.pythonbase | /code/function/student_info_fun.py | 8,238 | 3.765625 | 4 | # ๅฐ่ฃ
ๅฝๅ
ฅ็ๅญฆ็ไฟกๆฏ๏ผ
def input_student(*args):
L = []
while True:
name = input("ๅงๅ:")
if not name:
break
d = {} # ๅ้ ๆฐๅญๅ
ธ๏ผ้ๅคๅฉ็จ
d['name'] = name
age = int(input("ๅนด้พ:"))
d['age']= age
score = int(input("ๆ็ปฉ:"))
d['score'] = score
L.append(d)
return L
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ็กฎๅฎ่กจๆ ผๅฎฝๅบฆ๏ผ
def excel_width(L):
n,a,s = len('name'),len('age'),len('score')
for d in L:
if n < len(d['name']):
n = len(d['name'])
if a < len(str(d['age'])):
a = len(str(d['age']))
if s < len(str(d['score'])):
s = len(str(d['score']))
width = [n,a,s]
return width
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๆๅฐๅญฆ็ไฟกๆฏ๏ผ
def output_student(L):
n,a,s = excel_width(L)
i = 1
for d in L:
t = (str(i).center(6),
d['name'].center(n + 2),
str(d['age']).center(a + 2),
str(d['score']).center(s + 2)
)
l = '|%s|%s|%s|%s|' % t
i +=1
print(l)
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๆๅฐไฟกๆฏ่กจๆ ผ๏ผ
def print_excel(L):
n,a,s = excel_width(L)
l0 = '+' + '-' * 6 + '+' + '-'*(n + 2) +'+' + '-'*(a + 2) + '+' + '-'*(s + 2) + '+'
l1 = '|' + ' sort ' + '|' + 'name'.center(n + 2) + '|' + 'age'.center(a + 2) + '|' + 'score'.center(s + 2) + '|'
print(l0,l1,l0,sep = "\n")
output_student(L)
print(l0)
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ไฟฎๆนๅญฆ็ไฟกๆฏ๏ผ
def revise_info(L):
name = input('่ฏท่พๅ
ฅ่ฆไฟฎๆนๅญฆ็็ๅงๅ๏ผ')
for d in L:
if name == d['name']:
opt_age = input("ๆฏๅฆ่ฆไฟฎๆนๅนด้พ๏ผyes/no๏ผ:")
if opt_age == 'yes':
d['age'] = int(input('่ฏท่พๅ
ฅๆฐ็ๅนด้พ๏ผ'))
opt_score = input("ๆฏๅฆ่ฆไฟฎๆนๅๆฐ๏ผyes/no๏ผ:")
if opt_score == 'yes':
d['score'] = int(input("่ฏท่พๅ
ฅๆฐ็ๆ็ปฉ๏ผ"))
L[L.index(d)] = d
return L
else:
print('ๆจ่พๅ
ฅ็ๅญฆ็ไฟกๆฏไธๅญๅจ๏ผ')
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๅ ้คๅญฆ็ไฟกๆฏ๏ผ
def delete_info(L):
name = input('่ฏท่พๅ
ฅ่ฆๅ ้ค็ๅญฆ็ๅงๅ๏ผ')
for d in L:
if name == d['name']:
L.remove(d)
break
else:
print('ๆจ่พๅ
ฅ็ๅญฆ็ไฟกๆฏไธๅญๅจ๏ผ')
return L
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๆทปๅ ่ๅ๏ผ
def add_menu():
d = {}
k = 1
while True:
v = ''
sr = input('่ฏท่พๅ
ฅ่ฆๆทปๅ ็่ๅ๏ผ')
if sr == '้ๅบ':
v = '| '+ 'q' + ') ' + sr + ' '*(35-2*len(sr)) + '|'
d['q'] = v
break
else:
v = '| '+ str(k) + ') ' + sr + ' '*(35-2*len(sr)) + '|'
d[k] = v
k += 1
t = (k,d)
return t
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ่ๅ๏ผ
def menu(t):
k = t[0]
d = t[1]
l0 = '+'+'-'*40+'+'
print(l0)
for i in range(1,k):
print(d[i])
print(d['q'])
print(l0)
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๅบๅฎ่ๅ๏ผ
def main_menu():
print('+----------------------------------------+')
print('| 1) ๆทปๅ ๅญฆ็ไฟกๆฏ |')
print('| 2) ๆฅ็ๅญฆ็ไฟกๆฏ |')
print('| 3) ไฟฎๆนๅญฆ็ไฟกๆฏ |')
print('| 4) ๅ ้คๅญฆ็ไฟกๆฏ |')
print('| 5) ๆๆ็ปฉไป้ซๅฐไฝๆๅฐๅญฆ็ไฟกๆฏ |')
print('| 6) ๆๆ็ปฉไปไฝๅฐ้ซๆๅฐๅญฆ็ไฟกๆฏ |')
print('| 7) ๆๅนด้พไปๅคงๅฐๅฐๆๅฐๅญฆ็ไฟกๆฏ |')
print('| 8) ๆๅนด้พไปๅฐๅฐๅคงๆๅฐๅญฆ็ไฟกๆฏ |')
print('| q) ้ๅบ |')
print('+----------------------------------------+')
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๆๆ็ปฉไป้ซๅฐๅบๆๅบ(desc้ๅบ)๏ผ
def sort_score1(L):
print('ๆๆ็ปฉไป้ซๅฐไฝๆๅบๅ๏ผ')
L1 = sorted(L,key=lambda x : x['score'],reverse=True)
print_excel(L1)
# return L1
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๆๆ็ปฉไปไฝๅฐ้ซๆๅบ(ascๅๅบ)๏ผ
def sort_score2(L):
print('ๆๆ็ปฉไปไฝๅฐ้ซๆๅบๅ๏ผ')
L2 = sorted(L,key=lambda x : x['score'])
print_excel(L2)
# return L2
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๆๅนด้พไปๅคงๅฐๅฐๆๅบ๏ผ
def sort_age1(L):
print('ๆๅนด้พไปๅคงๅฐๅฐๆๅบๅ๏ผ')
L3 = sorted(L,key=lambda x : x['age'],reverse=True)
print_excel(L3)
# return L3
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๆๅนด้พไปๅฐๅฐๅคงๆๅบ๏ผ
def sort_age2(L):
print('ๆๅนด้พไปๅฐๅฐๅคงๆๅบๅ๏ผ')
L4 = sorted(L,key=lambda x : x['age'])
print_excel(L4)
# return L4
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
def main():
L = [] # ่พๅ
ฅๅญฆ็ไฟกๆฏ
# t = add_menu() # ๆทปๅ ่ๅไฟกๆฏ
while True:
# menu(t) # ๆพ็คบ่ๅ
# opt_menu(L) # ้ๆฉ่ๅๆไฝ(ๅฏ้ๆฉๅฝๆฐ)
main_menu()
num = input('่ฏท้ๆฉ่ๅๆไฝ๏ผ')
if num == '1':
L += input_student() # ๆทปๅ ๅญฆ็ไฟกๆฏ
elif num == '2':
print_excel(L) # ๆฅ็ๆๆๅญฆ็ไฟกๆฏ
elif num == '3':
revise_info(L) # ไฟฎๆนๅญฆ็ไฟกๆฏ
elif num == '4':
delete_info(L) # ๅ ้คๅญฆ็ไฟกๆฏ
elif num == '5':
sort_score1(L)
elif num == '6':
sort_score2(L)
elif num == '7':
sort_age1(L)
elif num == '8':
sort_age2(L)
elif num == 'q':
return # ้ๅบ
else:
print('่พๅ
ฅๆ่ฏฏ๏ผ')
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
main()
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ้ๆฉ่ๅ๏ผ
def opt_menu(L):
num = input('่ฏท้ๆฉ่ๅๆไฝ๏ผ')
if num == '1':
L += input_student() # ๆทปๅ ๅญฆ็ไฟกๆฏ
elif num == '2':
print_excel(L) # ๆฅ็ๆๆๅญฆ็ไฟกๆฏ
elif num == '3':
revise_info(L) # ไฟฎๆนๅญฆ็ไฟกๆฏ
elif num == '4':
delete_info(L) # ๅ ้คๅญฆ็ไฟกๆฏ
elif num == '5':
print('ๆๅนด้พไปๅคงๅฐๅฐๆๅบๅ๏ผ')
L2 = sort_age(L)
print_excel(L2)
elif num == '6':
print('ๆๆ็ปฉไป้ซๅฐไฝๆๅบๅ๏ผ')
L3 = sort_score(L)
print_excel(L3)
elif num == 'q':
return # ้ๅบ
else:
print('่พๅ
ฅๆ่ฏฏ๏ผ')
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# ๆๅบ๏ผ
def main1():
L = input_student()
print_excel(L)
print('ๆๅนด้พไปๅคงๅฐๅฐๆๅบๅ๏ผ')
L2 = sort_age(L)
print_excel(L2)
print('ๆๆ็ปฉไป้ซๅฐไฝๆๅบๅ๏ผ')
L3 = sort_score(L)
print_excel(L3)
# <<<โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ>>>
# main1() |
cf664bd2789ccd4ed9076c50b758a78b7031931c | tbs1-bo/hardware-101 | /hd44780/lcd.py | 1,995 | 3.546875 | 4 | import RPi.GPIO as GPIO
import time
class LCD:
CLEAR_DISPLAY = 0x01
RETURN_HOME = 0x02
def __init__(self, e_pin, rs_pin, d4, d5, d6, d7, boardmode=GPIO.BCM):
GPIO.setmode(boardmode)
self.rs_pin = rs_pin
self.e_pin = e_pin
self.d4 = d4
self.d5 = d5
self.d6 = d6
self.d7 = d7
# all pins are output pins
GPIO.setup([rs_pin, e_pin, d4, d5, d6, d7],
GPIO.OUT)
def tick(self, time_wait=0.001):
"""Make one clock cycle on the E pin."""
GPIO.output(self.e_pin, GPIO.LOW)
time.sleep(time_wait)
GPIO.output(self.e_pin, GPIO.HIGH)
time.sleep(time_wait)
GPIO.output(self.e_pin, GPIO.LOW)
def set_rs(self, signal):
GPIO.output(self.rs_pin, signal)
def send_data(self, byte, data_mode):
"""Send one byte on the pin connected to d4-d7. data_mode determines
whether it should be send as instructions (=0) or data (=1)."""
self.set_rs(data_mode)
# creating array of truth values corresponding to set bits in
# the byte
hi = [(byte >> 4) & 1 > 0,
(byte >> 5) & 1 > 0,
(byte >> 6) & 1 > 0,
(byte >> 7) & 1 > 0]
lo = [(byte) & 1 > 0,
(byte >> 1) & 1 > 0,
(byte >> 2) & 1 > 0,
(byte >> 3) & 1 > 0]
# First: writing upper 4 bits
GPIO.output([self.d4, self.d5, self.d6, self.d7], hi)
self.tick()
# Second: writing lower 4 bits
GPIO.output([self.d4, self.d5, self.d6, self.d7], lo)
self.tick()
if __name__ == "__main__":
lcd = LCD(e_pin=10, rs_pin=25,
d4=24, d5=23, d6=18, d7=17)
# configure by "return home" instruction
lcd.send_data(LCD.RETURN_HOME, 0)
# clear display
lcd.send_data(LCD.CLEAR_DISPLAY, 0)
# send command
lcd.send_data(ord("H"), 1)
lcd.send_data(ord("i"), 1)
GPIO.cleanup()
|
65e0ac83c5d327b379ca39cd74cdf95498468490 | Rock1311/Python_Practise | /all_divisor_of_a_number.py | 207 | 4 | 4 | ##print(all divisor of a number)
num = int(input('Please enter any number: ' ))
list = []
for x in range (1,num):
remainder = num%x
if (remainder == 0):
list.append(x)
print (list) |
fec76bdbb8aec39a13e86d00eddba7d2c6b03e90 | mjoblin/neotiles | /examples/speckled_tiles.py | 4,047 | 3.6875 | 4 | # =============================================================================
# Draws three speckled tiles and updates each tile's base color once per
# second. A speckled tile is just a single block of color where each pixel's
# intensity is varied slightly to give it a somewhat speckled look. The top
# left tile is also constantly updating its speckliness at the frame rate of
# the tile manager.
# =============================================================================
import random
import time
try:
from neopixel import ws
STRIP_TYPE = ws.WS2811_STRIP_GRB
except ImportError:
STRIP_TYPE = None
from neotiles import MatrixSize, TileManager, PixelColor, Tile, TilePosition
from neotiles.matrixes import NTNeoPixelMatrix, NTRGBMatrix
# Matrix size. cols, rows.
MATRIX_SIZE = MatrixSize(8, 8)
# For a neopixel matrix.
LED_PIN = 18
# For an RGB matrix.
CHAIN = 2
class SpeckledTile(Tile):
"""
Defines a tile which receives a PixelColor as input data, and sets all its
pixels to that color multiplied by an intensity picked randomly between
0.4 and 1.0. This should produce a speckled look to the tile.
"""
def draw(self):
if not isinstance(self.data, PixelColor):
return
for row in range(self.size.rows):
for col in range(self.size.cols):
# Set each pixel to the tile's color multiplied by an intensity
# value between 0.4 and 1.0.
intensity = random.uniform(0.4, 1.0)
display_color = PixelColor(
self.data.red * intensity,
self.data.green * intensity,
self.data.blue * intensity
)
self.set_pixel(
TilePosition(col, row), display_color)
# -----------------------------------------------------------------------------
def main():
# Initialize our matrix, animating at 10 frames per second.
tiles = TileManager(
NTNeoPixelMatrix(MATRIX_SIZE, LED_PIN, strip_type=STRIP_TYPE),
draw_fps=10
)
#tiles = TileManager(NTRGBMatrix(chain_length=CHAIN), draw_fps=10)
# Create three tiles based on our SpeckledTile class. Tiles are told their
# dimensions later. We enable animation on the first tile only.
speckled_tile_1 = SpeckledTile(animate=True)
speckled_tile_2 = SpeckledTile(animate=False)
speckled_tile_3 = SpeckledTile(animate=False)
cols = MATRIX_SIZE.cols
rows = MATRIX_SIZE.rows
# Assign the 3 tiles to the tile manager.
tiles.register_tile(
speckled_tile_1, size=(cols//2, rows//2), root=(0, 0))
tiles.register_tile(
speckled_tile_2, size=(cols//2, rows//2), root=(cols//2, 0))
tiles.register_tile(
speckled_tile_3, size=(cols, rows//2), root=(0, rows//2))
# Kick off the matrix animation loop.
tiles.draw_hardware_matrix()
try:
while True:
# Update each tile's base color. Each tile is getting different
# data (a different random color) so we call the Tile.data()
# methods independently rather than calling the tile manager's
# send_data_to_tiles() method.
for tile in [speckled_tile_1, speckled_tile_2, speckled_tile_3]:
tile.data = PixelColor(
random.random(), random.random(), random.random())
# We also draw each tile manually. This is only needed for
# the 'animate=False' tiles but we do it for all of them.
tile.draw()
# We only want the base color to update once per second. The
# first tile will randomly animate its pixel intensities during
# this one-second interval (see "animate=True" on the tile).
time.sleep(1)
except KeyboardInterrupt:
tiles.draw_stop()
tiles.clear_hardware_matrix()
# =============================================================================
if __name__ == '__main__':
main()
|
63952ef79d87affb91e421d68b152321ca4e6140 | stunningspectacle/code_practice | /python/projecteuler/62.py | 432 | 3.671875 | 4 | #!/usr/bin/python
def sort_cube(num):
cube = list(str(num ** 3))
cube.sort()
return "".join(cube)
def prob62():
TOP = 10000
cube = {}
for i in xrange(11, TOP):
str_cube = sort_cube(i)
if str_cube in cube:
cube[str_cube] += [i]
if len(cube[str_cube]) == 5:
print cube[str_cube]
print [c ** 3 for c in cube[str_cube]]
else:
cube[str_cube] = [i]
prob62()
|
2489d3bb4927a0aab560aab694779ad62c8b500e | sivaprasadnsp/Python-OOP | /Inheritance/prog01.py | 385 | 3.59375 | 4 | class Person:
def method1(self, a, b, c):
self.var1 = a
self.var2 = b
self.var3 = c
class Employee(Person):
pass
def main():
obj1 = Person()
obj2 = Employee()
obj1.method1(1, 2, 3)
print(obj1.var1, obj1.var2, obj1.var3)
obj2.method1(3, 4, 5)
print(obj2.var1, obj2.var2, obj2.var3)
if __name__ == "__main__":
main()
|
37e9ec85ea551c5a0f77ba61a24f955da77d0426 | loc-dev/CursoEmVideo-Python-Exercicios | /Exercicio_022/desafio_022.py | 662 | 4.375 | 4 | # Desafio 022 - Referente aula Fase09
# Crie um programa que leia o nome completo de uma pessoa
# e mostre:
# - O nome com todas as letras maiรบsculas e minรบsculas.
# - Quantas letras no total (sem considerar espaรงos).
# - Quantas letras tem o primeiro nome.
nome = input("Digite o seu nome completo: ")
print('')
print("Analisando o seu nome...")
print("Seu nome em letras maiรบsculas รฉ: {}".format(nome.upper()))
print("Seu nome em letras minรบsculas รฉ: {}".format(nome.lower()))
print("Seu nome tem ao todo {} letras".format(len(nome.replace(" ", ""))))
print("Seu primeiro nome รฉ {} e ele tem {} letras".format(nome.split()[0], len(nome.split()[0])))
|
5e18f4eb9f8a8249fc69ceecf8fbd6b24dd4512f | impankaj91/Python | /Chepter-11-Inheritance/sample_inheritance_multilevel.py | 223 | 4 | 4 | class Animals:
type="Pet"
class Pet(Animals):
name="Dog"
class Sound(Pet):
sound="Bow Bow"
s=Sound()
print(f"Type of Animal is {s.type}\n Name is {s.name} and sound is {s.sound}\n***************")
|
bcbcefa63dbbebeeb835c35509fb6dc1bf39b3b3 | Highjune/Python | /BasicConcept/class/classdemo1.py | 752 | 4.25 | 4 | class Employee:
"""Employee ๊ฐ์ฒด์ ์ค๊ณ๋์
๋๋ค."""
def __init__(self, name): #์์ฑ์
self.name = name
def getName(self): #getter
return self.name
def setName(self, newName): #setter
self.name = newName
def toString(self): #toString
return 'name = {}'.format(self.name)
smith = Employee('์ค๋ฏธ์ค')
# print(help(smith))
# print(smith.getName())
# smith.setName('๋ง์ดํด')
# print(smith.toString())
smith.age = 27 #์ค๊ณ๋(class)์ ์์ด๋ ์๋ก ๋ง๋ค ์ ์๋ค.
smith.age = 28
print(smith.age)
if hasattr(smith, 'age') == True :
print(getattr(smith, 'age'))
setattr(smith, 'age', 28)
print(getattr(smith, 'age'))
delattr(smith, 'age')
print(smith.age)
|
d4ffdc5c52bb60246493ba3ade4d455c00c309f7 | usnistgov/Economic-Resilience-Guide | /GUI/InfoPage.py | 36,408 | 3.75 | 4 | """
File: InfoPage.py
Author: Shannon Grubb
Description: Interacts with EconGuide.py, builds the GUI for the InfoPage,
the first page the user will input data on.
"""
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk #for pretty buttons/labels
from GUI.Constants import SMALL_FONT, ENTRY_WIDTH
from GUI.Constants import BASE_PADDING, FRAME_PADDING, FIELDX_PADDING, FIELDY_PADDING
from GUI.PlotsAndImages import none_dist, gauss_dist, tri_dist, rect_dist, disc_dist
from Data.ClassSimulation import Plan
import matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg#, NavigationToolbar2TkAgg
#from matplotlib.figure import Figure
matplotlib.use("TkAgg")
#
#
###################################### Base Information Class ######################################
############################################# InfoPage #############################################
#
#
class InfoPage(tk.Frame):
""" Allows the user to input the basic information about their options."""
def __init__(self, parent, controller, data_cont_list):
[self.data_cont] = data_cont_list
self.controller = controller
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Input the project name, the list of alternatives, "
"the planning horizon,the calculated \n"
"real discount rate for discounting future costs to "
"present values, and hazard specifics.", font=SMALL_FONT)
label.grid(pady=BASE_PADDING, padx=BASE_PADDING)
self.traces = [tk.StringVar() for i in range(6)]
#self.p1_trace = tk.StringVar()
#self.p2_trace = tk.StringVar()
#self.p3_trace = tk.StringVar()
#self.p4_trace = tk.StringVar()
#self.p5_trace = tk.StringVar()
#self.p6_trace = tk.StringVar()
self.choice_var = tk.StringVar()
self.create_widgets(controller)
def create_widgets(self, controller):
"""Widgets include: buttons, text boxes, and labels"""
group0 = ttk.LabelFrame(self)
group0.grid(row=0, sticky="ew", padx=FRAME_PADDING, pady=FRAME_PADDING)
ttk.Label(group0, text="Input the project name, the list of alternatives, "
"the planning horizon,the calculated \n"
"real discount rate for discounting future costs to "
"present values, and hazard specifics.",
font=SMALL_FONT).grid(row=1, column=0, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
ttk.Button(group0, text="More Information",
command=self.show_info).grid(row=1, column=1, sticky="w",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
# ===== Project Description Specifics
group1 = ttk.LabelFrame(self, text="Project Description")
group1.grid(row=2, sticky="ew", padx=FRAME_PADDING, pady=FRAME_PADDING)
ttk.Label(group1, text="Name",
font=SMALL_FONT).grid(row=0, column=0, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.name_ent = tk.Entry(group1, width=ENTRY_WIDTH, font=SMALL_FONT)
self.name_ent.insert(tk.END, "<enter project name>")
self.name_ent.grid(row=0, column=1, sticky="e", padx=FIELDX_PADDING, pady=FIELDY_PADDING)
ttk.Label(group1, text="Planning Horizon",
font=SMALL_FONT).grid(row=1, column=0, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.hor_ent = tk.Entry(group1, width=ENTRY_WIDTH, font=SMALL_FONT)
self.hor_ent.insert(tk.END, "<enter number of years for analysis>")
self.hor_ent.grid(row=1, column=1, sticky="e", padx=FIELDX_PADDING, pady=FIELDY_PADDING)
# ===== Project Alternatives Names
group2 = ttk.LabelFrame(self, text="Project Alternatives")
group2.grid(row=3, sticky="ew", padx=FRAME_PADDING, pady=FRAME_PADDING)
self.choices = [1, 2, 3, 4, 5, 6]
ttk.Label(group2, text="Number of Alternative Plans",
font=SMALL_FONT).grid(row=0, column=0, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.num_plans_ent = ttk.Combobox(group2, textvariable=self.choice_var, font=SMALL_FONT,
width=ENTRY_WIDTH, values=self.choices)
self.num_plans_ent.insert(tk.END, 0)
self.num_plans_ent.grid(row=0, column=1, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.choice_var.trace("w", self.on_trace_choice)
# ^ Updates other widgets when this field is updated
ttk.Label(group2, text="Base scenario",
font=SMALL_FONT).grid(row=1, column=0, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
ttk.Label(group2, text="---------------------------------------------------",
font=SMALL_FONT).grid(row=1, column=1, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.name_lbls = [ttk.Label(group2, text="Alternative 1", font=SMALL_FONT),
ttk.Label(group2, text="Alternative 2", font=SMALL_FONT),
ttk.Label(group2, text="Alternative 3", font=SMALL_FONT),
ttk.Label(group2, text="Alternative 4", font=SMALL_FONT),
ttk.Label(group2, text="Alternative 5", font=SMALL_FONT),
ttk.Label(group2, text="Alternative 6", font=SMALL_FONT)]
for lbl in self.name_lbls:
my_row = self.name_lbls.index(lbl) + 2
lbl.grid(row=my_row, column=0, sticky="e", padx=FIELDX_PADDING, pady=FIELDY_PADDING)
lbl.configure(state="disabled")
self.name_ents = [tk.Entry(group2, textvariable=self.traces[i],
width=ENTRY_WIDTH, font=SMALL_FONT) for i in range(6)]
for ent in self.name_ents:
my_row = self.name_ents.index(ent) + 2
ent.insert(tk.END, "<enter plan name>")
ent.grid(row=my_row, column=1, sticky="e", padx=FIELDX_PADDING, pady=FIELDY_PADDING)
ent.configure(state="disabled")
# ===== Discount Rate and Hazard Specifics
group3 = ttk.LabelFrame(self, text="Discount Rate")
group3.grid(row=4, sticky="ew", padx=FRAME_PADDING, pady=FRAME_PADDING)
ttk.Label(group3, text="Real Discount Rate",
font=SMALL_FONT).grid(row=0, column=0, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.dis_ent = tk.Entry(group3, width=ENTRY_WIDTH, font=SMALL_FONT)
self.dis_ent.insert(tk.END, "5.00")
self.dis_ent.grid(row=0, column=1, sticky="e", padx=FIELDX_PADDING, pady=FIELDY_PADDING)
ttk.Label(group3, text="%", font=SMALL_FONT).grid(row=0, column=2, sticky='w',
pady=FIELDY_PADDING)
ttk.Button(group3, text="Restore Default",
command=self.restore).grid(row=2, column=0, sticky="w",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
group4 = ttk.LabelFrame(self, text="Hazard Recurrence")
group4.grid(row=5, sticky="ew", padx=FRAME_PADDING, pady=FRAME_PADDING)
self.recur_choice = tk.StringVar()
self.recur_choice.set("none")
recur_rads = [tk.Radiobutton(group4, variable=self.recur_choice, value="none"),
tk.Radiobutton(group4, variable=self.recur_choice, value="gauss"),
tk.Radiobutton(group4, variable=self.recur_choice, value="tri"),
tk.Radiobutton(group4, variable=self.recur_choice, value="rect"),
tk.Radiobutton(group4, variable=self.recur_choice, value="discrete")]
rad_labels = ["Exact", "Gaussian", "Triangular", "Rectangular", "Discrete"]
figs = [none_dist(), gauss_dist(), tri_dist(), rect_dist(), disc_dist()]
for col in range(len(recur_rads)):
fig_label = ttk.Label(group4)
fig_label.grid(row=1, column=col)
fig = figs[col]
canvas = FigureCanvasTkAgg(fig, master=fig_label)
canvas.get_tk_widget().grid(row=1, column=col+1)
canvas.show()
recur_rads[col].grid(row=3, column=col)
rad_label = ttk.Label(group4, text=rad_labels[col], font=SMALL_FONT)
rad_label.grid(row=2, column=col)
self.recur_choice.trace("w", self.on_trace_change_recur)
self.recur_label = [tk.Label(group4, text="Most Frequent (Years)"),
tk.Label(group4, text="Expected Recurrence (Years)"),
tk.Label(group4, text="Least Frequent (Years)")]
self.recur_one_label = tk.Label(group4, text="Recurrence (Years)")
self.recur_one_label.grid(row=4, column=0)
self.recur_gauss_label = [tk.Label(group4, text="Expected Recurrence (Years)"),
tk.Label(group4, text="Standard Deviation (Years)")]
self.recur_discrete_label = [tk.Label(group4, text="Most Frequent (Years)"),
tk.Label(group4, text="Middle Recurrence (Years)"),
tk.Label(group4, text="Least Frequence (Years)"),
tk.Label(group4, text="Likelihood of Most Frequent (%)"),
tk.Label(group4, text="Likelihood of Middle Recurrence (%)"),
tk.Label(group4, text="Likelihood of Least Frequent (%)")]
self.recur_range = [tk.Entry(group4, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group4, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group4, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group4, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group4, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group4, width=int(ENTRY_WIDTH/2), font=SMALL_FONT)]
self.recur_range[0].grid(row=4, column=1, padx=FIELDX_PADDING, pady=FIELDY_PADDING)
group5 = ttk.LabelFrame(self, text="Hazard Magnitude")
group5.grid(row=6, sticky="ew", padx=FRAME_PADDING, pady=FRAME_PADDING)
self.mag_choice = tk.StringVar()
self.mag_choice.set("none")
mag_rads = [tk.Radiobutton(group5, variable=self.mag_choice, value="none"),
tk.Radiobutton(group5, variable=self.mag_choice, value="gauss"),
tk.Radiobutton(group5, variable=self.mag_choice, value="tri"),
tk.Radiobutton(group5, variable=self.mag_choice, value="rect"),
tk.Radiobutton(group5, variable=self.mag_choice, value="discrete")]
rad_labels = ["Exact", "Gaussian", "Triangular", "Rectangular", "Discrete"]
figs = [none_dist(), gauss_dist(), tri_dist(), rect_dist(), disc_dist()]
for col in range(len(mag_rads)):
fig_label = ttk.Label(group5)
fig_label.grid(row=1, column=col)
fig = figs[col]
canvas = FigureCanvasTkAgg(fig, master=fig_label)
canvas.get_tk_widget().grid(row=1, column=col+1)
canvas.show()
mag_rads[col].grid(row=3, column=col)
rad_label = ttk.Label(group5, text=rad_labels[col], font=SMALL_FONT)
rad_label.grid(row=2, column=col)
self.mag_choice.trace("w", self.on_trace_change_mag)
self.mag_label = [tk.Label(group5, text="Least Severe (%)"),
tk.Label(group5, text="Expected Magnitude (%)"),
tk.Label(group5, text="Most Severe (%)")]
self.mag_one_label = tk.Label(group5, text="Magnitude (%)")
self.mag_one_label.grid(row=4, column=0)
self.mag_gauss_label = [tk.Label(group5, text="Expected Magnitude (%)"),
tk.Label(group5, text="Standard Deviation (%)")]
self.mag_discrete_label = [tk.Label(group5, text="Least Severe (%)"),
tk.Label(group5, text="Middle Severity (%)"),
tk.Label(group5, text="Most severe (%)"),
tk.Label(group5, text="Likelihood of Least Severe (%)"),
tk.Label(group5, text="Likelihood of Middle Severity (%)"),
tk.Label(group5, text="Likelihood of Most Severe (%)")]
self.mag_range = [tk.Entry(group5, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group5, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group5, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group5, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group5, width=int(ENTRY_WIDTH/2), font=SMALL_FONT),
tk.Entry(group5, width=int(ENTRY_WIDTH/2), font=SMALL_FONT)]
self.mag_range[0].grid(row=4, column=1, padx=FIELDX_PADDING, pady=FIELDY_PADDING)
group6 = ttk.LabelFrame(self, text="Risk Preference")
group6.grid(row=7, stick="ew", padx=FRAME_PADDING, pady=FRAME_PADDING)
self.preference = tk.StringVar()
self.preference.set("none")
ttk.Label(group6, text="Define Risk Preference",
font=SMALL_FONT).grid(row=14, column=0, sticky="e",
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.neutral = ttk.Radiobutton(group6, text="Risk Neutral",
variable=self.preference, value="neutral")
self.neutral.grid(row=15, column=0, sticky="w", padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.averse = ttk.Radiobutton(group6, text="Risk Averse",
variable=self.preference, value="averse")
self.averse.grid(row=16, column=0, sticky="w", padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.accepting = ttk.Radiobutton(group6, text="Risk Accepting",
variable=self.preference, value="accepting")
self.accepting.grid(row=17, column=0, sticky="w", padx=FIELDX_PADDING, pady=FIELDY_PADDING)
# ===== Manueverability Buttons
group7 = ttk.LabelFrame(self)
group7.grid(row=8, sticky="ew", padx=FRAME_PADDING, pady=FRAME_PADDING)
# === Places spacing so that buttons are on the bottom right
ttk.Label(group7, text=" " * 106).grid(row=0, column=1)
ttk.Button(group7, text="Next>>",
command=lambda: self.check_page(controller,
'CostPage')).grid(row=0, column=7, sticky="se",
padx=FIELDX_PADDING,
pady=FIELDY_PADDING)
ttk.Button(group7, text="Menu",
command=lambda: self.check_page(controller,
'DirectoryPage')).grid(row=0, column=3,
sticky="se",
padx=FIELDX_PADDING,
pady=FIELDY_PADDING)
def restore(self):
"""restores default discount value"""
self.dis_ent.delete(0, tk.END)
self.dis_ent.insert(tk.END, "5.00")
def check_page(self, controller, frame):
"""Ensures that all required fields are properly filled out before continuing"""
err_messages = ""
valid = True
# ===== Mandatory fields cannot be left blank or left alone
if self.name_ent.get() == "" or self.name_ent.get() == "<enter project name>":
err_messages += "Project name field has been left empty!\n\n"
valid = False
if "," in self.name_ent.get():
err_messages += "Project name field cannot have a comma.\n\n"
valid = False
for i in range(int(self.num_plans_ent.get())):
if self.name_ents[i].get() == "" or self.name_ents[i].get() == "<enter plan name>":
err_messages += "Name for Alternative " + str(i) + " hasn't been given.\n\n"
valid = False
# ===== Number fields must be positive numbers
try:
float(self.hor_ent.get())
if float(self.hor_ent.get()) == 0:
err_messages += "Planning Horizon must be greater than zero.\n"
err_messages += "Please enter a positive amount. \n\n"
valid = False
except ValueError:
err_messages += "Planning Horizon must be a number. Please enter an amount.\n\n"
valid = False
if "-" in self.hor_ent.get():
err_messages += "Planning Horizon must be a positive number.\n"
err_messages += " Please enter a positive amount.\n\n"
valid = False
try:
float(self.dis_ent.get())
except ValueError:
err_messages += "Discount Rate must be a number. Please enter an amount.\n\n"
valid = False
if "-" in self.dis_ent.get():
err_messages += "Discount Rate must be a positive number.\n"
err_messages += "Please enter a positive amount.\n\n"
valid = False
if self.recur_choice.get() == 'none':
try:
if float(self.recur_range[0].get()) <= 0:
valid = False
err_messages += "Hazard Recurrence must be greater than zero.\n\n"
except ValueError:
valid = False
err_messages += "Hazard Recurrence must be a number.\n\n"
elif self.recur_choice.get() == 'gauss':
try:
if float(self.recur_range[0].get()) <= 0:
valid = False
err_messages += "Hazard Recurrence must be greater than zero.\n\n"
if float(self.recur_range[1].get()) <= 0:
valid = False
err_messages += "Hazard Recurrence standard deviation must be "
err_messages += "greater than zero.\n\n"
except ValueError:
valid = False
err_messages += "All Hazard Recurrence values must be numbers.\n\n"
elif self.recur_choice.get() == 'discrete':
for entry in self.recur_range:
try:
float(entry.get())
except ValueError:
valid = False
err_messages += "All Hazard Recurrence inputs must be numbers.\n\n"
try:
assert float(self.recur_range[0].get()) <= float(self.recur_range[1].get()) <= float(self.recur_range[2].get())
disc_sum = float(self.recur_range[3].get()) + float(self.recur_range[4].get()) + float(self.recur_range[5].get())
if disc_sum != 100:
valid = False
err_messages += "Hazard Recurrence discrete likelihoods must add to 100%.\n\n"
except AssertionError:
valid = False
err_messages += "Hazard Recurrence discrete options must be in order.\n\n"
except ValueError:
pass
else:
try:
bound = float(self.recur_range[0].get()) <= float(self.recur_range[1].get()) <= float(self.recur_range[2].get())
if not bound:
valid = False
err_messages += "Hazard Recurrence lower bound must be below upper bound.\n\n"
except ValueError:
valid = False
err_messages += "All Hazard Recurrence inputs must be numbers.\n\n"
if self.mag_choice.get() == 'none':
try:
if float(self.mag_range[0].get()) < 0:
valid = False
err_messages += "Hazard Magnitude must be greater than or equal to zero.\n\n"
except ValueError:
if self.mag_range[0].get() != "":
valid = False
err_messages += "Hazard Magnitude must be a number.\n\n"
elif self.mag_choice.get() == 'gauss':
try:
if float(self.mag_range[0].get()) <= 0:
valid = False
err_messages += "Hazard Magnitude must be greater than zero.\n\n"
if float(self.mag_range[1].get()) <= 0:
valid = False
err_messages += "Hazard Magnitude standard deviation must be "
err_messages += "greater than zero.\n\n"
except ValueError:
valid = False
err_messages += "All Hazard Magnitude values must be numbers.\n\n"
elif self.mag_choice.get() == 'discrete':
for entry in self.mag_range:
try:
float(entry.get())
except ValueError:
valid = False
err_messages += "All Hazard Magnitude inputs must be numbers.\n\n"
try:
assert float(self.mag_range[0].get()) >= float(self.mag_range[1].get()) >= float(self.mag_range[2].get())
disc_sum = float(self.mag_range[3].get()) + float(self.mag_range[4].get()) + float(self.mag_range[5].get())
if disc_sum != 100:
valid = False
err_messages += "Hazard Magnitude discrete likelihoods must add to 100%.\n\n"
except AssertionError:
valid = False
err_messages += "Hazard Magnitude discrete options must be in order.\n\n"
except ValueError:
pass
else:
try:
bound = float(self.mag_range[0].get()) <= float(self.mag_range[1].get()) <= float(self.mag_range[2].get())
if not bound:
valid = False
err_messages += "Hazard Magnitude lower bound must be below upper bound.\n\n"
except ValueError:
valid = False
err_messages += "All Hazard Magnitude inputs must be numbers.\n\n"
if self.preference.get() not in ['neutral', 'averse', 'accepting', 'none']:
err_messages += "A risk preference has not been selected! Please select one.\n\n"
valid = False
if not valid:
messagebox.showerror("ERROR", err_messages)
return valid
# Fills data_cont with the values entered
data = self.controller.data_cont
data.title = self.name_ent.get()
data.num_plans = int(self.num_plans_ent.get()) + 1
data.horizon = float(self.hor_ent.get())
data.discount_rate = float(self.dis_ent.get())
data.risk_preference = self.preference.get()
dis_recurr = [entry.get() for entry in self.recur_range]
dis_mag = [entry.get() for entry in self.mag_range]
if data.plan_list == []:
data.plan_list.append(Plan(0, "Base",
[self.recur_choice.get(), dis_recurr],
[self.mag_choice.get(), dis_mag],
data.discount_rate, data.horizon, data.stat_life,
self.data_cont.parties))
for i in range(1, data.num_plans):
data.plan_list.append(Plan(i, self.name_ents[i-1].get(),
[self.recur_choice.get(), dis_recurr],
[self.mag_choice.get(), dis_mag],
data.discount_rate, data.horizon, data.stat_life,
self.data_cont.parties))
else:
old_num_plans = len(data.plan_list)
new_num_plans = data.num_plans
if old_num_plans <= new_num_plans:
data.plan_list[0].update(0, 'Base', [self.recur_choice.get(), dis_recurr],
[self.mag_choice.get(), dis_mag],
data.discount_rate, data.horizon, data.stat_life)
for i in range(1, old_num_plans):
data.plan_list[i].update(i, self.name_ents[i-1].get(),
[self.recur_choice.get(), dis_recurr],
[self.mag_choice.get(), dis_mag],
data.discount_rate, data.horizon, data.stat_life)
for j in range(old_num_plans, new_num_plans):
data.plan_list.append(Plan(j, self.name_ents[j-1].get(),
[self.recur_choice.get(), dis_recurr],
[self.mag_choice.get(), dis_mag],
data.discount_rate, data.horizon, data.stat_life,
self.data_cont.parties))
elif old_num_plans > new_num_plans:
data.plan_list[0].update(0, 'Base', [self.recur_choice.get(), dis_recurr],
[self.mag_choice.get(), dis_mag],
data.discount_rate, data.horizon, data.stat_life)
for i in range(1, new_num_plans):
data.plan_list[i].update(i, self.name_ents[i-1].get(),
[self.recur_choice.get(), dis_recurr],
[self.mag_choice.get(), dis_mag],
data.discount_rate, data.horizon, data.stat_life)
for j in range(old_num_plans, new_num_plans, -1):
data.plan_list.remove(data.plan_list[j-1])
data.file_save()
controller.show_frame(frame)
def show_info(self):
"""Shows extra information for the user (for clarification)"""
messagebox.showinfo("More Information",
"In the EDGeS Tool, the terms are defined in the following manner:\n"
" Planning Horizon: The time span โ measured in years โ for which "
"the projectโs costs and benefits will be assessed in the analysis.\n"
" Base Scenario: Often referred to as the โbusiness as usualโ case."
" It refers to the option against which the other identified alterative"
" scenarios are compared.\n"
" Real Discount Rate: Often referred to as the โtime value of "
"money.โ Typically, a dollar is worth more today than it would be "
"worth tomorrow. This is the percent at which the value of money "
"decreases over time, allowing for the comparison of quantities as if "
"prices had not changed. 5.00% is the default value.\n"
" Hazard Recurrence: The number of years expected before a specific "
"hazard occurs after its last occurrence. In this version of EDGeS "
"only a single hazard will be considered. Future versions of the EDGeS"
" Tool may add functionality to deal with compound hazards directly.\n"
" Hazard Magnitude: The total damage the defined hazard is expected "
"tp inflict upon occurrence. The magnitude is measured as the fraction "
"of total replacement cost for a project.\n"
" Risk preference: The willingness of the user/community to take on "
"the risk(s) associated with the consequences of potential disruptive "
"events.\n\n"
"NOTE: The โhazard magnitudeโ and โrisk preferenceโ fields have no "
"impact on the calculations made within this Tool. The information "
"will only be stored for reference.")
def on_trace_change(self, _name, _index, _mode):
""" Triggers all on_trace_***"""
self.on_trace_change_mag(_name, _index, _mode)
self.on_trace_change_recur(_name, _index, _mode)
self.on_trace_choice(_name, _index, _mode)
def on_trace_choice(self, _name, _index, _mode):
"""Triggers refresh when combobox changes"""
try:
choice = int(self.num_plans_ent.get())
#print('try', choice)
if 0 <= choice <= 6:
for i in range(choice):
self.name_lbls[i].configure(state="active")
self.name_ents[i].configure(state="normal")
for i in range(choice, 6):
self.name_lbls[i].configure(state="disabled")
self.name_ents[i].configure(text="", state="disabled")
elif choice < 0:
self.num_plans_ent.set(0)
self.on_trace_choice("", "", "")
else:
#print('set 6', choice)
self.num_plans_ent.set(6)
self.on_trace_choice("", "", "")
except ValueError:
if self.num_plans_ent.get() == "":
pass
else:
self.num_plans_ent.set(0)
self.on_trace_choice("", "", "")
def on_trace_change_recur(self, _name, _index, _mode):
"""Triggers refresh when the uncertainty choices change."""
if self.recur_choice.get() == "none":
self.recur_one_label.grid(row=4, column=0)
for label in self.recur_label:
label.grid_remove()
for label in self.recur_gauss_label:
label.grid_remove()
for label in self.recur_discrete_label:
label.grid_remove()
self.recur_range[0].grid(row=4, column=1,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
for i in range(1, len(self.recur_range)):
self.recur_range[i].grid_remove()
elif self.recur_choice.get() == "gauss":
self.recur_one_label.grid_remove()
for label in self.recur_label:
label.grid_remove()
for label in self.recur_gauss_label:
label.grid(row=self.recur_gauss_label.index(label)+4, column=0)
for label in self.recur_discrete_label:
label.grid_remove()
self.recur_range[0].grid(row=4, column=1,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.recur_range[1].grid(row=5, column=1,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
for i in range(2, len(self.recur_range)):
self.recur_range[i].grid_remove()
elif self.recur_choice.get() == "discrete":
self.recur_one_label.grid_remove()
for label in self.recur_label:
label.grid_remove()
for label in self.recur_gauss_label:
label.grid_remove()
for label in self.recur_discrete_label[0:3]:
label.grid(row=self.recur_discrete_label.index(label)+4, column=0)
for label in self.recur_discrete_label[3:6]:
label.grid(row=self.recur_discrete_label.index(label)+1, column=2)
for entry in self.recur_range[0:3]:
entry.grid(row=self.recur_range.index(entry)+4, column=1,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
for entry in self.recur_range[3:6]:
entry.grid(row=self.recur_range.index(entry)+1, column=3,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
else:
self.recur_one_label.grid_remove()
for label in self.recur_label:
label.grid(row=self.recur_label.index(label)+4, column=0)
for label in self.recur_gauss_label:
label.grid_remove()
for label in self.recur_discrete_label:
label.grid_remove()
for i in range(3):
self.recur_range[i].grid(row=self.recur_range.index(self.recur_range[i])+4,
column=1, padx=FIELDX_PADDING, pady=FIELDY_PADDING)
for i in range(3, len(self.recur_range)):
self.recur_range[i].grid_remove()
def on_trace_change_mag(self, _name, _index, _mode):
"""Triggers refresh when the uncertainty choices change."""
if self.mag_choice.get() == "none":
self.mag_one_label.grid(row=4, column=0)
for label in self.mag_label:
label.grid_remove()
for label in self.mag_gauss_label:
label.grid_remove()
for label in self.mag_discrete_label:
label.grid_remove()
self.mag_range[0].grid(row=4, column=1,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
for i in range(1, len(self.mag_range)):
self.mag_range[i].grid_remove()
elif self.mag_choice.get() == "gauss":
self.mag_one_label.grid_remove()
for label in self.mag_label:
label.grid_remove()
for label in self.mag_gauss_label:
label.grid(row=self.mag_gauss_label.index(label)+4, column=0)
for label in self.mag_discrete_label:
label.grid_remove()
self.mag_range[0].grid(row=4, column=1,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
self.mag_range[1].grid(row=5, column=1,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
for i in range(2, len(self.mag_range)):
self.mag_range[i].grid_remove()
elif self.mag_choice.get() == "discrete":
self.mag_one_label.grid_remove()
for label in self.mag_label:
label.grid_remove()
for label in self.mag_gauss_label:
label.grid_remove()
for label in self.mag_discrete_label[0:3]:
label.grid(row=self.mag_discrete_label.index(label)+4, column=0)
for label in self.mag_discrete_label[3:6]:
label.grid(row=self.mag_discrete_label.index(label)+1, column=2)
for entry in self.mag_range[0:3]:
entry.grid(row=self.mag_range.index(entry)+4, column=1,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
for entry in self.mag_range[3:6]:
entry.grid(row=self.mag_range.index(entry)+1, column=3,
padx=FIELDX_PADDING, pady=FIELDY_PADDING)
else:
self.mag_one_label.grid_remove()
for label in self.mag_label:
label.grid(row=self.mag_label.index(label)+4, column=0)
for label in self.mag_gauss_label:
label.grid_remove()
for label in self.mag_discrete_label:
label.grid_remove()
for i in range(3):
self.mag_range[i].grid(row=self.mag_range.index(self.mag_range[i])+4,
column=1, padx=FIELDX_PADDING, pady=FIELDY_PADDING)
for i in range(3, len(self.mag_range)):
self.mag_range[i].grid_remove()
|
59c30aacd02becff8ed1935b685db4e151a3047f | cristinamais/exercicios_python | /Exercicios Estruturas Logicas e Condicionais/exercicio 41 - secao 05.py | 1,247 | 3.984375 | 4 | """
41 - Faรงa um algorรญtmo que calcule o IMC de uma pessoa e mostre sua classificaรงรฃo
de acordo com a tabela abaixo:
IMC | Classificaรงรฃo
------------------------------------------------------------
< 18,5 ----------------> Abaixo do peso
18,5 - 24,9 -------------> Saudรกvel
25,0 - 29,9 -------------> Peso em excesso
30,0 - 34,9 -------------> Obsidade Grau I
35,0 - 39,9 -------------> Obesidade Grau II(severa)
>= 40,0 ---------------> Obesidade Grau III(mรณrbida)
-------------------------------------------------------------
"""
imc = float(input("Digite o seu imc: "))
if imc < 18.5:
print(f'O seu imc รฉ {imc} vocรช estรก: Abaixo do peso')
elif imc >= 18.5 and imc <= 24.9:
print(f'O seu imc รฉ {imc} vocรช estรก: Saudรกvel')
elif imc > 24.9 and imc <= 29.9:
print(f'O seu imc รฉ {imc} vocรช estรก com Peso em excesso')
elif imc > 29.9 and imc <= 34.9:
print(f'O seu imc รฉ {imc} vocรช estรก com Obsidade Grau I')
elif imc > 34.9 and imc <= 39.9:
print(f'O seu imc รฉ {imc} vocรช estรก com Obesidade Grau II (severa)')
else:
imc >= 40.0
print(f'O seu imc รฉ {imc} vocรช estรก com Obsidade Grau III (mรณbida)')
|
2d973f92a733cbec8cd7aef8d0adc5a3e3e555e7 | jithendarreddy/guvi-set1 | /13.py | 171 | 3.5 | 4 | n=int(input())
i=2
k=0
while i<n:
if n%i==0:
k=1
print("no")
i=i+1
if k==0:
print("yes")
|
f67fc8fb3f5a3de50883b84feae91e29b6ddaa2b | danieldfc/curso-em-video-python | /ex006.py | 348 | 3.984375 | 4 | numeric_value = int(input('Digite um nรบmero: '))
dobro = numeric_value * 2
triplo = numeric_value * 3
raiz_quadrada = numeric_value ** (1/2)
print('O dobro de {} vale {}.'.format(numeric_value, dobro))
print('O triplo de {} vale {}.'.format(numeric_value, triplo))
print('A raiz quadrada de {} vale {:.2f}.'.format(numeric_value, raiz_quadrada)) |
57593a9f14112271934e413b077691ad3ea6eb43 | lookatjith/path_planning | /random_approach/random_planner.py | 3,091 | 4.28125 | 4 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from utils.plot_simulator import plot_movement
class RandomPlanner(object):
"""
Robot tries to achieve the goal point with in a max_step_number.
The robot finds the new pose by randomly incrementing/decrementing
the current pose at only one direction at a time
Complexity:
----------
1) Robot can visit already covered pose multiple times
2) Robot can get stuck at one point or between obstacles
3) Robot can get diverged even after nearing the goal point
3) Robot search is completely random. The robot may take long time
to reach the goal point. If the maximum number of step is small, the
robot may fail to achieve the goal point
4) If the complexity of the robot environment increase, the robot
may fail to reach the goal point.
Parameters
----------
world_state: 2D environment
obstacles: 2D obstacles in the environment
goal_point: 2D point for the robot to reach
robot_init: robot initial world_state
max_step_number: max number of steps within which the robot must reach
goal. If the robot is not able to reach the goal, the algorithm fails
pause_sec: used for simulating the environment, robot and the movement
"""
def __init__(self, max_step_number, world_state, obstacles, goal_point, robot_init, pause_sec):
self._max_step_number = max_step_number
self._world_state = world_state
self._obstacles = obstacles
self._goal_point = goal_point
self._robot_init = robot_init
self._pause_sec = pause_sec
plot_movement(self._world_state, self._obstacles, self._goal_point, self._robot_init)
def random_planner(self, x, y):
new_x = x
new_y = y
def do_increment(val):
new_val = val + np.random.randint(-1, 2)
if new_val != val:
return True, new_val
else:
return False, new_val
for i in range(self._max_step_number):
x = new_x
y = new_y
incremented, new_x = do_increment(x)
if not incremented:
incremented, new_y = do_increment(y)
# new estimated pose lies with the world
if (new_x, new_y) not in self._world_state:
new_x = x
new_y = y
# obstacle avoidance
elif (new_x, new_y) in self._obstacles:
new_x = x
new_y = y
# goal point reached
elif new_x == self._goal_point[0] and new_y == self._goal_point[1]:
print("goal point reached in {} iterations".format(i))
# return if goal point reached
return
new_pos = (new_x, new_y)
plot_movement(self._world_state, self._obstacles, self._goal_point, new_pos)
plt.pause(self._pause_sec)
print("total iterations: {} reached. Robot not able to reach the goal point".format(
self._max_step_number))
|
1d07a257f904aaf4487a31af6a7f6b12e430db48 | Vijay1234-coder/data_structure_plmsolving | /Mix Questions/combination.py | 418 | 3.9375 | 4 | from itertools import combinations
# A Python program to print all combinations
# of given length with unsorted input.
from itertools import combinations
s=[]
# Get all combinations of [2, 1, 3]
# and length 2
a=[1,2,3,4,5,6]
for i in range(len(a)+1):
comb =list(combinations(a,i))
s.extend(comb)
for i in range(0,len(a)):
for j in range(i+1,len(a)):
# Print the obtained combinations
|
06f4cedce03dfd7641424812899a3a9d3bb682e2 | Jerrytd579/CS-with-Data-Analysis | /Highschool CS/Machine Learning.py | 6,653 | 3.5625 | 4 | # Improved example. Uses training and test set.
__author__ = 'bixlermike'
# Based on tutorial at http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/
# This version uses different data set, incorporates optional neutral tweet category,
# removes hashtags from tweet, and stems words
import csv
import matplotlib.pyplot as plt
import nltk
import time
def get_words_in_tweets(tweets):
all_words = []
for (words, sentiment) in tweets:
all_words.extend(words)
return all_words
def get_word_features(wordlist):
wordlist = nltk.FreqDist(wordlist)
word_features = wordlist.keys()
return word_features
def extract_features(document):
document_words = set(document)
features = {}
for word in word_features:
features['contains(%s)' % word] = (word in document_words)
return features
# Stemming a word means grabbing just the root of the word, so "stopping" becomes "stop", etc.
# This object will help us stem the tweets.
s = nltk.stem.SnowballStemmer('english')
pos_tweets = []
neg_tweets = []
neutral_tweets = []
# If we define this here, we can avoid having to manually change this number in each place that it's used in the code
TRAINING_LINES = 1000
start_time = time.clock()
print ('Reading in tweets!')
with open('airline_tweets.csv','r', encoding='utf-8',errors='ignore') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
# Skip first line of file (headers)
next(plots)
for i, row in enumerate(plots):
# i contains the line number of the file, row contains the actual data
# Kick us out of the loop if we get to this line of the input file.
# We might want to leave the loop early, as the program runtime gets large very quickly!
if i == TRAINING_LINES:
break
# Break the tweet down into the individual stemmed words
# Append the stemmed tweet as well as the sentiment to the list
if row[1] == 'positive':
temp = s.stem(row[10]), 'positive'
pos_tweets.append(temp)
elif row[1] == 'negative':
temp = s.stem(row[10]), 'negative'
neg_tweets.append(temp)
# elif row[1] == 'neutral':
# temp = s.stem(row[10]), 'neutral'
# neutral_tweets.append(temp)
print ('Finished reading tweets!')
tweets = []
# Take all of the strings stored in both the positive and negative tweet lists, along with the sentiment labels
for (words, sentiment) in pos_tweets + neg_tweets:
#for (words, sentiment) in pos_tweets + neg_tweets + neutral_tweets:
# Filter the set of words to include only those that have at least 4 characters and don't start with a hashtag
words_filtered = [e.lower() for e in words.split() if len(e) >= 4 and not e.startswith('@')]
tweets.append((words_filtered, sentiment))
print ('Wrote all training data into a giant list!')
# Calculate how often we see each word in a positive or negative tweet
word_features = get_word_features(get_words_in_tweets(tweets))
# Tell the machine learning algorithm that this is our training set of data
training_set = nltk.classify.apply_features(extract_features, tweets)
print ('Starting to train data using Naive Bayes classifier!')
# This is the time consuming step. The machine learning algorithm tries to learn from the training data given to it.
classifier = nltk.NaiveBayesClassifier.train(training_set)
print ('Done training the data!')
# Lists the words that are the most informative as to whether we are looking at a positive or negative tweet
classifier.show_most_informative_features(50)
#tweet = ["You guys are terrible","Thank you for the great bday experience", "My plane was delayed 3 hours. You suck!"]
# Cycle through list of tweets that we want to test. Classify them one by one and print result
#for i in tweet:
# print("The sentiment of '" + str(i) + "' is " + classifier.classify(extract_features(i.split())))
# Create a list to store all of the tweets that we're trying to predict
test_set_tweets = []
correct_guesses = 0
incorrect_guesses = 0
attempts = 0
print ('Reading in tweets again!')
with open('airline_tweets.csv','r', encoding='utf-8',errors='ignore') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
# Skip first line of file (headers)
next(plots)
for i, row in enumerate(plots):
# Start guessing at the sentiment after we get past the data used to train the model
# It's not fair to test the same tweets that we used to train the model
# Let's skip the neutral tweets, as we didn't train the model to understand what neutral means
if i > TRAINING_LINES and str(row[1]) != 'neutral':
actual_sentiment = str(row[1])
# Don't forget to stem the tweet, since the model was trained with stemmed words!
current_tweet = s.stem(row[10])
test_set_tweets.append(current_tweet)
# Predict the sentiment of this tweet
predicted_sentiment = classifier.classify(extract_features(current_tweet.split()))
# Print line statements to make sure code is working correctly
#print("The predicted sentiment of '" + str(row[10]) + "' is " + predicted_sentiment + ".")
#print("The actual sentiment was " + actual_sentiment + ".")
#print()
if (predicted_sentiment == actual_sentiment):
correct_guesses+=1
attempts+=1
else:
incorrect_guesses+=1
attempts+=1
# Since code like this can take a long time to run, it's sometimes difficult to know if it's stuck in a loop,
# barely running, almost done, etc.
# Put in statements like the one below to give you occasional status updates
if (i % 1000 == 0):
print ("We're " + str(i) + " lines into the file!")
accuracy = correct_guesses / (correct_guesses + incorrect_guesses)
end_time = time.clock()
print ("For a training set of " + str(TRAINING_LINES) + " samples, the accuracy across " + str(attempts) + " predictions was " + str(round(accuracy*100,2)) + "%")
print ("The code took " + str(round(end_time-start_time,2)) + " seconds to run.")
accuracy *= 100
accuracy = [accuracy]
with open('C:/Users/jerry/Desktop/School Stuff/MachineLearning.csv', 'w') as csvfile:
fieldnames = ['accuracy']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'accuracy':accuracy})
|
34aaff8097e933c8e9013b4c32ee489036f04bfb | meredithtutrone/homework | /Higher Order Function on GitHub.py | 662 | 3.515625 | 4 | #4 different examples higher order functions
#1
def add(a):
def func(b):
return a + b
return func
twoMore = add(2)
x = 10
xPlusTwo = twoMore(x)
print(xPlusTwo)
#2
def mult(a):
def func(b):
return a * b
return func
timesTheOther = mult(4)
x = 2
xTimesA = timesTheOther(x)
print(xTimesA)
#3
def func(a, b):
return a + b
x = map(func, ('dog', 'cat', 'fish'), ('kangaroo', 'koala', 'anteater'))
print(x)
print(list(x))
jersey_number = [2, 3, 19, 22, 38, 89]
#4
def func(x):
if x >= 38:
return True
else:
return False
players = filter(func, jersey_number)
for x in players:
print(x)
|
e54dba462df62e7d002c8ed960abae968dbf2429 | Rielch/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 213 | 3.796875 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
new_list = my_list.copy()
new_list.sort()
res = 0
a = 0
for i in new_list:
if i != a:
res += i
a = i
return res
|
936c2961889ace76bdf1975d7390a83f25c9b242 | jax11000/movie_display | /media.py | 758 | 3.5 | 4 | """
Module to display movie object, attributes and instances
"""
import webbrowser
class Movie():
# defines what a movie object should be
"""
Class object stores movie info
"""
def __init__(self, title, storyline, image, youtube_url):
self.title = title
self.storyline = storyline
self.poster_image_url = image
self.youtube_url = youtube_url
"""
:param title: string
:param storyline: string
:param image: string
:param youtube_url: string
"""
def show_trailer(self):
"""
Initializing instance for opening youtube video
:return: webbrowser to play trailer
"""
webbrowser.open(self.youtube_url)
# end of file |
883ffcfab69077c57d009a4d45a2a0db90cb43bd | JDer-liuodngkai/LeetCode | /leetcode/945 ไฝฟๆฐ็ปๅฏไธ็ๆๅฐๅข้.py | 743 | 3.859375 | 4 | from typing import List
"""
่พๅ
ฅ๏ผ[1,2,2]
่พๅบ๏ผ1
่งฃ้๏ผ็ป่ฟไธๆฌก move ๆไฝ๏ผๆฐ็ปๅฐๅไธบ [1, 2, 3]ใ
move ๆไฝ: ้ๆฉไปปๆ1ไธชๆฐ๏ผ+1
ๆฏๆฌก้ไธญ1ไธชๆฐ๏ผๅขๅ 1๏ผไฝฟๅพๆฐ็ปๅฏไธ
้ฎ้่ฆๆง่ก็ move ๆฌกๆฐ
"""
class Solution:
def minIncrementForUnique(self, A: List[int]) -> int:
A.sort()
# ๆฐ็ปๅฏไธ๏ผๅคๆญไธฅๆ ผๅขๅบ็ๅผ ๆฏๅฆๆปก่ถณไธ็ญ
res = 0
n = len(A)
for i in range(n - 1):
d = A[i + 1] - A[i]
if d <= 0: # ้่ฆ move, ๅนถๆดๆฐ A[i+1]
res += (-d + 1)
A[i + 1] = A[i] + 1
return res
s = Solution()
# A = [1, 2, 2]
A = [3, 2, 1, 2, 1, 7]
print(s.minIncrementForUnique(A))
|
bc9f33aeef94819f7efb0ed41cbbf0e653a5dde6 | thedonflo/Flo-Python | /ModernPython3BootCamp/Loops/Screaming_Repeating.py | 126 | 3.9375 | 4 | user_input = input("How many times do I have to tell you? ")
for i in range(int(user_input)):
print("CLEAN UP YOUR ROOM!") |
79f0a6d026bd56e3b584a86e88ff36ccd3a316ae | yasar11732/stringutils | /stringutils.py | 2,616 | 3.640625 | 4 | from string import (letters, digits, punctuation,
whitespace, lowercase, uppercase,
hexdigits, octdigits, printable)
from itertools import groupby
from os import name as osname
if osname == "nt":
newline = "\r\n"
else:
newline = "\n"
isSomething = lambda thing: lambda x: x in thing
allSomething = lambda thing: lambda string : all(thing(x) for x in string)
anySomething = lambda thing: lambda string : any(thing(x) for x in string)
removeSomething = lambda thing: lambda string: "".join(x for x in string
if not thing(x))
onlySomething = lambda thing: lambda string: "".join(x for x in string
if thing(x))
func_dic = {
"Letter" : letters,
"Digit" : digits,
"Alphanum" : letters + digits,
"Punctuation" : punctuation,
"Whitespace" : whitespace,
"Lower" : lowercase,
"Upper" : uppercase,
"Hex" : hexdigits,
"Octal" : octdigits,
"Printable" : printable,
}
cat_order = ["Whitespace","Upper","Lower","Punctuation","Digit","Printable"]
for k, v in func_dic.iteritems():
predicate = isSomething(v)
globals()["is" + k] = predicate
globals()["all" + k] = allSomething(predicate)
globals()["any" + k] = anySomething(predicate)
globals()["remove" + k] = removeSomething(predicate)
globals()["only" + k] = onlySomething(predicate)
"""
def strtonum(string):
if not allDigits(string):
raise ValueError("Non-digit karakter in string")
return reduce(lambda x,y: 10 * x + y,
[x -48 for x in [ord(x) for x in string]])
"""
words = lambda string : removePunctuation(string).split(" ")
unwords = lambda lst : " ".join(lst)
lines = lambda string : string.split(newline)
unlines = lambda lst : newline.join(lst)
def category(char):
for cat in cat_order:
if char in func_dic[cat]:
return cat
raise ValueError("Couldn't determine the type of %s" % char)
def makestrfunctions(string,k):
predicate = isSomething(string)
globals()["is" + k] = predicate
globals()["all" + k] = allSomething(predicate)
globals()["any" + k] = anySomething(predicate)
globals()["remove" + k] = removeSomething(predicate)
globals()["only" + k] = onlySomething(predicate)
categories = lambda string : [category(x) for x in string]
groups = lambda string: ["".join(iterator) for (kate, iterator) in groupby(string,category)]
reversewords = lambda string: unwords("".join(reversed(x)) for x in words(string))
|
3b87f84f337826485a92564e9ec76e1bd7f537b7 | OSUrobotics/me499 | /types/others.py | 673 | 3.953125 | 4 | #!/usr/bin/env python3
from math import pi
import decimal
import fractions
if __name__ == '__main__':
# There are other types in Python, and we'll show you how to create your own types later in the class. Here are
# a couple of examples:
# Fixed and arbitrary precision floating point arithmetic: https://docs.python.org/3/library/decimal.html
print('Decimals:')
decimal.getcontext().prec = 3
d = decimal.Decimal(1 / 3)
print(1 / 3)
print(d)
# Fractions: https://docs.python.org/3/library/fractions.html
print('\nFractions:')
f = fractions.Fraction(1, 3)
g = fractions.Fraction(12, 17)
print(f)
print(f * g)
|
db391d6b0e7ecf265bc5c9aa66253f2c5dc32144 | HBharathi/Python-Programming | /constructor1.py | 221 | 3.625 | 4 | class Person:
def __init__(self,name): #constructor
self.name=name
def talk(self):
print(f" Hey {self.name}, please speak up!!!")
p1 = Person("Annu")
p1.talk()
p2 = Person("Bharathi")
p2.talk()
|
1cccb1bb568fbd8946b5062d196efa519a6c5841 | daniel-reich/ubiquitous-fiesta | /kmruefq3dhdqxtLeM_16.py | 192 | 3.71875 | 4 |
def sum_digits(m, n):
sum=0
for a in range(m,n+1):
string=str(a)
for b in string:
b=str(b)
sum+=int(b)
return sum
|
5ec1543c3d5c2e49bc13a3a8333e966f0b429be6 | jpvt/Reinforcement_Learning | /intro_projects/Intro to Gym Model-Free/qlearning_intro.py | 530 | 3.78125 | 4 | import gym #Inclui pacote Gym, essencial para RL
env = gym.make('MountainCar-v0') #Inicializa ambiente
env.reset() #Resets Env
done = False #sets finished state as False
random_act = 2 #For this problem there is 3 actions, for example we initially choose 2
while not done:
action = random_act # define action
nu_state, reward, done, _ = env.step(action) #New state for the next action, the reward of being in that state and the update of the done object
env.render() #Render the graphic env
env.close() #close env
|
06116f147b90a8c8372e763e601734de3242df9a | umunusb1/Python_for_interview_preparation | /all/patterns/01_square_pattern.py | 3,005 | 4.09375 | 4 | #!/usr/bin/python
def square_pattern(n):
"""
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
"""
for i in range(n):
print('* ' * n)
def square_number_pattern(n):
"""
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
"""
for i in range(1, n + 1):
print(f'{i} ' * n)
def square_number_pattern_2(n):
"""
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
"""
for _ in range(1, n + 1):
for i in range(1, n + 1):
print(i, end=' ')
print()
def square_alphabets_pattern(n):
"""
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
"""
for i in range(65, 65 + n):
print((chr(i) + ' ') * n)
def square_alphabets_pattern_2(n):
"""
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
"""
for _ in range(n):
for i in range(65, 65 + n):
print(chr(i), end=' ')
print()
def square_numbers_reverse(n):
"""
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
"""
for i in range(n, 0, -1):
print('%s ' % (i) * n)
def square_numbers_reverse_2(n):
"""
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
"""
for _ in range(n):
for i in range(n, 0, -1):
print(i, end=' ')
print()
def square_numbers_descending(n):
"""
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
"""
for i in range(n, 0, -1):
print(f'{i} ' * n)
def square_numbers_descending_2(n):
"""
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
"""
for _ in range(n):
for i in range(n, 0, -1):
print(i, end=' ')
print()
def square_alphabets_descending(n):
"""
E E E E E
D D D D D
C C C C C
B B B B B
A A A A A
"""
for i in range(n - 1, -1, -1):
print(f'{chr(i + 65)} ' * n)
def square_alphabets_descending_2(n):
"""
E D C B A
E D C B A
E D C B A
E D C B A
E D C B A
"""
for _ in range(n):
for i in range(n - 1, -1, -1):
print(chr(i + 65), end=' ')
print()
def custom_pattern_1(n):
"""
0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 1 1 1 1 1 0
0 0 0 0 0 0 0
"""
pass
if __name__ == '__main__':
print('-' * 10)
square_pattern(5)
print('-' * 10)
square_number_pattern(5)
print('-' * 10)
square_number_pattern_2(5)
print('-' * 10)
square_alphabets_pattern(5)
print('-' * 10)
square_alphabets_pattern_2(5)
print('-' * 10)
square_numbers_reverse(5)
print('-' * 10)
square_numbers_reverse_2(5)
print('-' * 10)
square_numbers_descending(5)
print('-' * 10)
square_numbers_descending_2(5)
print('-' * 10)
square_alphabets_descending(5)
print('-' * 10)
square_alphabets_descending_2(5)
print('-' * 10)
|
273e02b28d72d9c55ffd2e50db34a3497f1579f6 | cznccsjd/learnOpenpyxl | /workPandasNumpy.py | 1,928 | 3.75 | 4 | #coding:utf-8
"""
openpyxlๅญฆไน ๆๆกฃ๏ผWorking with Pandas and Numpy
url:http://openpyxl.readthedocs.io/en/latest/pandas.html#numpy-support
"""
### Working with Pandas Dataframes
# The openpyxl.utils.dataframe.dataframe_to_rows() function provides a simple way to work with Pandas Dataframes:
from openpyxl.utils.dataframe import dataframe_to_rows
from pandas import DataFrame
from openpyxl.workbook import Workbook
wb = Workbook()
ws = wb.active
file = "./pandas.xlsx"
data = {'name':{'one':'zhangsan','two':'lisi'},'sex':{'one':'man','two':'women'}}
df = DataFrame(data)
print('\n################################################')
# for r in dataframe_to_rows(df, index=True, header=True):
# ws.append(r)
#
# wb.save(filename=file)
# wb.close()
# ๅฐdataframe่ฝฌๆขไธบ็ชๅบๆพ็คบๆ ้ขๅ็ดขๅผ็ๅทฅไฝ่กจ
# To convert a dataframe into a worksheet highlighting the header and index:
'''
print('\n################################################')
for r in dataframe_to_rows(df, index=True, header=True):
ws.append(r)
# ไธ้ขไปฃ็ ๏ผๆฏexcel่กจๆ ผ็ฌฌAๅๅ็ฌฌ1่ก๏ผๅ ็ฒใๅ ้ปๆๆ
for cell in ws['A'] + ws['1']:
cell.style = 'Pandas'
wb.save(file)
'''
# ๅฆๆๅชๆณ่ฝฌๆขๆฐๆฎ๏ผๅฏไปฅไฝฟ็จๅชๅๆจกๅผ
# Alternatively, if you just want to convert the data you can use write-only mode:
# print('\n################################################')
# from openpyxl.cell.cell import WriteOnlyCell
# wb = Workbook(write_only=True)
# ws = wb.create_sheet()
#
# cell = WriteOnlyCell(ws)
# cell.style = 'Pandas'
#
# def format_first_row(row, cell):
# for c in row:
# cell.value = c
# yield cell
#
# rows = dataframe_to_rows(df)
# first_row = format_first_row(next(rows), cell)
# ws.append(first_row)
#
# for row in rows:
# row = list(row)
# cell.value = row[0]
# row[0] = cell
# ws.append(row)
#
# wb.save(file)
# ไธ้ข็ไปฃ็ ไธๆ ๅๅทฅไฝ็ฐฟๆๆไธๆ ท
|
f9a588b46fc5c688c977821f9b02b1b413f48154 | laricarlotti/python_exs | /ex_017.py | 151 | 4.125 | 4 | # Exercise 17
from math import sqrt
num = int(input("Type a number: "))
square = sqrt(num)
print(f"The square root of {num} is {square.__trunc__()}") |
8e1dfd7f11f9e5156372c741bb0b3dba0705868b | minhthe/practice-algorithms-and-data-structures | /Codility/06_Sorting/Triagle.py | 373 | 3.578125 | 4 | '''
https://app.codility.com/demo/results/training953UNF-5F3/
'''
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
pass
A.sort()
n = len(A)
if n < 3: return 0
for i in range(n-3, -1, -1 ):
if A[i] + A[i+1] > A[i+2]:
return 1
return 0 |
06ba10add53d11f111afb9f5654806ef56ade38b | Aasthaengg/IBMdataset | /Python_codes/p02995/s076785723.py | 367 | 3.671875 | 4 | # ่งฃ่ชฌๅ็ปใฟใ๏ผ https://www.youtube.com/watch?v=XI8exXVxZ-Q
# ๆๅฐๅ
ฌๅๆฐ
# ใฆใผใฐใชใใใฎไบ้คๆณ
import math
def lcm(x, y):
return (x * y) // math.gcd(x, y)
def f(x, c, d):
res = x
res -= x//c
res -= x//d
res += x//lcm(c, d)
return res
a, b, c, d = map(int, input().split())
ans = f(b, d, c) - f(a-1, c, d)
print(ans) |
11a87f2346699328b16f42916c853be1687d614a | Superfishintights/parseltongue | /ch2/2-4.py | 1,420 | 4.09375 | 4 | # Car Salesman Program
# Write a Car Salesman program where the user enters the base price of a car. The program should add on a bunch of extra fees such as tax, license, dealer prep, and destination charge. Make tax and license a percent of the base price. The other fees should be set values. Display the actual price of the car once all the extras are applied.
# Jay 2016-07-07 21:48:12
#Program Welcome
print("Welcome to the Snakes Autodealer, where all car salesman are Snakes!")
print("\nThis program allows you to quickly work out the total price of your new victim's (customer's) brand new (Cat D write-off) car")
# Setting the base price of the car (what the user sees on the price sticker)
base_price = int(input("\nWhat is the base price of the car? ยฃ"))
# Setting the 'addons'
tax = base_price * 0.15
license = base_price * 0.1
dealer_prep = 200
delivery = 100
# Setting final prices and bonus
price = float(base_price + license + tax + dealer_prep + delivery)
bonus = price * 0.05
total_price = bonus + price
# Viewing the breakdown in price
print("\n\tTax = ยฃ", tax)
print("\n\tLicense = ยฃ", license)
print("\n\tDealer Preparation Fees = ยฃ", dealer_prep)
print("\n\tDelivery charges (mandatory) = ยฃ", tax)
print("\nThe price is ยฃ ", price)
print("\nYour bonus is ยฃ", bonus)
print("\nThe total price for the customer to pay is ยฃ", total_price)
input("\nPress the enter key to exit")
|
4340fedd7414b94ff4191d5b2537b2b447958ca2 | daumie/dominic-motuka-bc17-week-1 | /day_4/missing_num.py | 662 | 4.03125 | 4 | """Module docstring"""
def find_missing(arr1, arr2):
"""compares 2 arrays and returns missing elements"""
new_list = []
for element in arr1:
if element not in arr2:
new_list.append(element)
for element in arr2:
if element not in arr1:
new_list.append(element)
length_new_list = len(new_list)
if length_new_list > 0:
if length_new_list == 1:
return new_list[0]
else:
return new_list
else:
return 0
# print(find_missing([2, 3, 3], [2]))
# print(find_missing([2, 3], [2, 3, 4, 5]))
# print(find_missing([2], [2]))
# print(find_missing([], []))
|
fbc72e29dd4e8e939f0c72fa3e0a3081870d6199 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/ashishdotme/programming-problems/python/30-days-of-code/02-operators.py | 700 | 4 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created by Ashish Patel
Copyright ยฉ 2017 ashish.me
ashishsushilpatel@gmail.com
"""
"""
Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip),
and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost.
"""
if __name__ == "__main__":
meal_cost = float(input().strip())
tip_percent = int(input().strip())
tax_percent = int(input().strip())
tip = meal_cost * (tip_percent / 100)
tax = meal_cost * (tax_percent / 100)
total_cost = meal_cost + tip + tax
print("The total meal cost is {0} dollars.".format(int(round(total_cost))))
|
aa9fa4ba2069fb1a745cff1081199353b9277e8c | elice-python-coding/MJY | /programmers/2.py | 143 | 3.546875 | 4 | def solution(numbers):
numbers.sort(key = lambda x:(x[0], x[1]))
answer=''.join(numbers)
return answer
print(solution([6, 10, 2])) |
4eaf040dac38ccbab9f5967cf06ede97d20b5c8a | FerValenzuela-ops/PyThings | /playing.py | 23,962 | 4.125 | 4 | '''
name = 'Jhonny'
age = 55
# The clean way to use variables
print(f'hi {name}. You are {age} years old')
# String indexes
selfish = '01234567'
# where to look at []
print(selfish[2])
# Where to start/ where to finish [start:over]
selfish = '01234567'
print(selfish[0:4])
# Stepover [start"stop:stepover]
print(selfish[0:8:2])
# go all the way to the end
print(selfish[1:])
# all before there
print(selfish[:-5])
# reverse the string
print(selfish[::-1])
# lenght of things
print(len(selfish[::-1]))
# built-in functions
quote = 'to be or not to be'
print(quote.find('be'))
tula = (quote.replace('be', 'tula'))
print(tula)
print(quote)
# booleans
name = 'Fer'
is_cool = False
is_cool = True
# Exercise, Age guesser
name = 'Fer'
age = 50
relationship_status = 'Single'
relationship_status = 'It\'s complicated'
print(relationship_status)
birth_year = int(input('what year were yo born? \n'))
from datetime import datetime
sys_date = str(datetime.now())
actual_year = sys_date[0:4]
guessing_age = int(actual_year) - birth_year
age_message = (
f'Hello {name}. It\'s been passed {guessing_age} years from your birth day!')
print(age_message)
# Exercise Password checker
user_name = str(input('Hello,write your name here: \n') #Ask user name's
)
pswd = str(input(f'{user_name}, please write your password: \n'))
pswdlen = len(pswd)
pswdsec = ('*' * pswdlen)
print(f'{user_name}. Your password {pswdsec} is {pswdlen} letters long')
li = [1,2,3,4,5]
li2 = ['a', 'b', 'c']
li3 = [1,2,'a',True]
amazon_cart = ['notebooks', 'sunglasses']
print(amazon_cart[0])
# list slicing
amazon_cart = [
'notebooks',
'sunglasses',
'toys',
'grapes'
]
amazon_cart[0] = 'laptop'
new_cart = amazon_cart[:]
new_cart[0] = 'gum'
print(new_cart)
print(amazon_cart)
# Matrix
matrix = [
[1,9,3],
[2,4,5],
[7,8,9]
]
print(matrix[0][1])
basket = [1,2,3,4,5]
basket.append(100)
basket.extend([104])
basket.insert(2, 909)
new_list = basket[:]
# adding
print(basket)
# print(new_list)
# removing
basket.pop() # removes the last
basket.pop(0) #removes by index
basket.remove(4) #removes the objetc
print(basket)
print(basket.clear())
basket = ['a','j','z','b','c','d','e']
print(basket.index('a'))
print(basket.index('d', 0 ,6))
print('d' in basket)
print('x' in basket)
print('My' in 'My name\'s is ian')
print(basket.count('d'))
basket.sort()
print(basket)
| = or
& = and
is_friend = True
is_user = False
can_message = "Message allowed" if is_friend else "message not allowed"
relationship = "Best Friends" if (is_friend | is_user) else "No best friends"
print(relationship)
print(can_message)
is_magician = False
is_expert = True
if(is_magician and is_expert):
print("You are a master magician")
elif (is_magician and not is_expert):
print("At least you're getting here")
elif not is_magician:
print("You need magic powers")
else:
print("wow")
user = {
'name': 'Golem',
'age': 5600,
'can_swim': True
}
for item in user.items():
print(item)
for key, value in user.items():
print(key, value)
for item in user.keys():
print(item)
for item in user.values():
print(item)
_list = [1, 2, 3 ,4, 5, 6, 7, 8, 9, 10]
counter = 0
for item in _list:
counter = counter + item
print(counter)
for _ in range(10):
print(_)
for _ in range(2):
print(list(range(10)))
"this doesnt works"
for _ in range(10, 0):
print(_)
for _ in range(10, 0, -1):
print(_)
for i,char in enumerate('Helloooo'):
print(i,char)
for i,char in enumerate(list(range(101))):
print(i,char)
seeking_number = int(input("Type any number from 0 to 100: \n"))
for i,char in enumerate(list(range(100))):
if (char == seeking_number):
print(f'the index of your number {seeking_number} is: {i}')
my_list = [1,2,3]
for item in my_list:
print(item)
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
while True:
response = input('type something: ')
if response == 'bye':
break
# exercise
picture = [
[0,0,0,1,0,0,0],
[0,0,1,1,1,0,0],
[0,1,1,1,1,1,0],
[1,1,1,1,1,1,1],
[0,0,0,1,0,0,0],
[0,0,0,1,0,0,0]
]
def show_tree():
for row in picture:
for pixel in row:
if (pixel == 1):
print('*', end = '')
else:
print(' ', end = '')
print('')
# finding duplicates
my_list = ['a','b','c','d','d','e','f','g','h','m','m']
duplicates = []
for letter in my_list:
if my_list.count(letter) > 1:
if letter not in duplicates:
duplicates.append(letter)
print(duplicates)
def say_hello():
print("hello")
say_hello()
show_tree()
print('')
show_tree()
def sum(num1, num2):
def another_func(n1, n2):
return n1 + n2
return another_func(num1, num2)
total = sum(10,20)
print(total)
def is_even(num):
if num % 2 == 0:
return True
return False
print(is_even(51))
def is_even_btt(num):
return num % 2 == 0
print(is_even_btt(51))
#
# *args **kwargs
def super_funct(name, *args, i='hi', **kwargs):
total = 0
for items in kwargs.values():
total += items
return sum(args) + total
print(super_funct('Andy', 1,2,3,4,5, num1=5, num2=10))
# Rule: params, *args, default parameter, **kwargs
def highest_even(li):
evens = []
for items in li:
if items % 2 == 0:
evens.append(items)
return max(evens)
print(highest_even([10,2,3,4,8,11,100,88]))
a = 'helloooooooo'
if (n := len(a)) > 10:
print(f"too long {n} elements")
while ((n := len(a)) > 1):
print(n)
a = a[:-1]
print(a)
'''
# Scope - what variables do i have access to?
# # class PlayerCharacter:
# # # Class object attribute
# # membership = True
# # def __init__(self, name, age):
# # if(PlayerCharacter.membership):
# # self.name = name
# # self.age = age
# # else:
# # print('No membership')
# # def shout(self):
# # print(f'my name is {self.name}')
# # def run(self, hello):
# # print(f'my name is {self.name}')
# # player1 = PlayerCharacter('Andre', 33)
# # player2 = PlayerCharacter('Fer', 54)
# # player2.attack = 50
# # print(player1.run('hello'))
# # print(player1.shout())
# # # print(player1.run())
# # # print(player2.age)
# # # help(list)
# # # print(player2)
# # # print(player2.attack)
# # # print(player2.membership)
# class PlayerCharacter:
# membership = True
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def shout(self):
# print(f'my name is {self.name}')
# @classmethod
# def adding_things(cls, num1, num2):
# return cls('Teddy', num1 + num2)
# @staticmethod
# def adding_things2(num1, num2):
# return (num1 + num2)
# player3 = PlayerCharacter.adding_things(2, 2)
# print(player3.name)
# print(player3.age)
# class PlayerCharacter:
# def __init__(self, name, age):
# self._name = name
# self._age = age
# def playerinfo(self):
# print(f'my name is {self._name} and I am {self._age} years old')
# # _variable --> _ means private
# player1 = PlayerCharacter('Fer', 23)
# print(player1.playerinfo())
# print(player1.speak())
# users
# class User:
# def __init__(self, email):
# self.email = email
# def sign_in(self):
# print('logged in')
# def attack(self):
# print('Do Nothing')
# class Wizzard(User):
# def __init__(self, name, power, email):
# super().__init__( email)
# self.name = name
# self.power = power
# def attack(self):
# User.attack(self)
# print(f'attacking with power of {self.power}')
# class Archer(User):
# def __init__(self, name, num_arrows):
# self.name = name
# self.num_arrows = num_arrows
# def attack(self):
# print(f'attacking with {self.num_arrows} arrows')
# wizard1 = Wizzard('Mage', 60, 'mage@gmail.com')
# archer1 = Archer('Bowy', 30)
# def player_attack(char):
# char.attack()
# print(isinstance(wizard1, object))
# player_attack(wizard1)
# player_attack(archer1)
# for char in [wizard1, archer1]:
# char.attack()
# print(wizard1.name)
# print(wizard1.email)
# print(dir(wizard1)) # dir makes possible the object introspection
# class Toy():
# def __init__(self, color, age):
# self.color = color
# self.age = age
# self.my_dict = {
# 'name': 'Yoyo',
# 'has_pets': False
# }
# def __str__(self): # Changes the value of the method
# return f'{self.color}'
# def __len__(self): # Changes the value of the method
# return 590
# def __del__(self): # Changes the value of the method
# print('deleted!')
# def __call__(self):
# return ('yeeeesss???')
# def __getitem__(self, i):
# return self.my_dict[i]
# action_figure = Toy('red', 0)
# print(action_figure.__str__())
# print(str(action_figure)) # Changes the value of the method
# print(len(action_figure)) # Changes the value of the method
# print(action_figure())
# print(action_figure['name'])
# del action_figure # Changes the value of the method
# class SuperList(list):
# def __len__(self):
# return 1000
# super_list1 = SuperList()
# print(len(super_list1))
# super_list1.append(5)
# print(super_list1[0])
# print(len(super_list1))
# print(issubclass(SuperList, list))
# print(issubclass(list, object))
# class User():
# def sign_in(self):
# print('You are logged in')
# class Wizard(User):
# def __init__(self, name, power):
# self.name = name
# self.power = power
# def attack(self):
# print(f'attacking with power of {self.power}')
# class Archer(User):
# def __init__(self, name, arrows):
# self.name = name
# self.arrows = arrows
# def check_arrows(self):
# print(f'{self.arrows} remaining')
# def run(self):
# print('ran really fast')
# class HybridBorg(Wizard, Archer):
# def __init__(self, name, power, arrows):
# Archer.__init__(self, name, arrows)
# Wizard.__init__(self, name, arrows)
# hb1 = HybridBorg('borgie', 50, 100)
# print(hb1.attack())
# print(hb1.check_arrows())
# print(hb1.sign_in())
# MRO - Method Resolution Order
# class A:
# num = 10
# class B(A):
# pass
# class C(A):
# num = 1
# class D(B, C):
# pass
# print(D.mro())
# class X:pass
# class Y:pass
# class Z:pass
# class A(X,Y):pass
# class B(Y,Z):pass
# class M(B,A,Z):pass
# print(M.__mro__)
# Functional programming
# map . filter , zip, and ,reduce
# def multiply_by2(li):
# new_list = []
# for item in li:
# new_list.append(item*2)
# return new_list
# new_list = ''
# # print(map(multiply_by2, ([1,2,3])))
# from functools import reduce
# # map()
# my_list = [1, 2, 3]
# your_list = [10, 20, 30]
# their_list = (5, 3, 2)
# def multiply_by2(item):
# return item*2
# print(list(map(multiply_by2, my_list)))
# print(my_list)
# # filter()
# def only_odd(item):
# return item % 2 != 0
# print(list(filter(only_odd, my_list)))
# # zip()
# print(list(zip(my_list, your_list, their_list)))
# print(my_list)
# # reduce()
# def accumulator(acc, item):
# print(acc, item)
# return acc + item
# print(reduce(accumulator, my_list, 0))
# # lambda expressions
# # lambda param: action(param)
# print(list(map(lambda item: item*2, my_list)))
# print(list(filter(lambda item: item % 2 !=0, my_list)))
# print(reduce(lambda acc, item: acc + item, my_list))
# my_list = [5, 4, 3]
# #Square
# new_list = print(list(map(lambda item: item**2, my_list)))
# print(new_list)
# #List sorting base in the second number
# li = [(0,2),(4,3),(9,9), (10,-1)]
# print(sorted(li, key = lambda x: x[1]))
# list, set, dictionary comprehension
# my_list = [char for char in 'hello']
# my_list2 = [num for num in range(0,100)]
# my_list3 = [num*2 for num in range(0,100)]
# my_list4 = [num**2 for num in range(0,100) if num % 2 == 0]
# print(my_list4)
# print(my_list3)
# print(my_list)
# print(my_list2)
# set comprehension
# my_list = {char for char in 'hello'}
# my_list2 = {num for num in range(0, 100)}
# my_list3 = {num*2 for num in range(0, 100)}
# my_list4 = {num**2 for num in range(0, 100) if num % 2 == 0}
# # print(my_list4)
# print(my_list3)
# print(my_list)
# print(my_list2)
# dict comprehension
# simple_dict = {
# 'a': 1,
# 'b': 2
# }
# my_dict = {k: v**2 for k, v in simple_dict.items() if v % 2 == 0}
# print(my_dict)
# my_dict2 = {num:num*2 for num in [1, 2, 3]}
# print(my_dict2)
# some_list = ['a','b','c','b','d','m','n','n']
# duplicate = list(set([letter for letter in some_list if some_list.count(letter) >1 ]))
# print(duplicate)
# High Order Function HOC
# def greet(func):
# func()
# def greet2():
# def func():
# return 5
# return func
# Decorator Pattern
# import main
# import unittest
# import re # re = regular expressions
# from time import time
# def my_decoratorPattern(func):
# def wrap_func(*args, **kwargs):
# func(*args, **kwargs)
# return wrap_func
# hello()
# @my_decorator
# def bye():
# print('see you later')
# bye()
# # Decorator example
# def my_decorator(func):
# def wrap_func(*args, **kwargs):
# print('*************')
# func(*args, **kwargs)
# print('*************')
# return wrap_func
# @my_decorator
# def hello(greeting, emoji=':('):
# print(greeting, emoji)
# hello('hiii')
# # Decorator
# def performance(fn):
# def wrapper(*args, **kwargs):
# t1 = time()
# result = fn(*args, **kwargs)
# t2 = time()
# print(f'took {t2-t1} ms')
# return result
# return wrapper
# @performance
# def long_time():
# for i in range(1000):
# i*5
# long_time()
# # Create an @authenticated decorator that only allows the function to run is user1 has 'valid' set to True:
# user1 = {
# 'name': 'Sorna',
# # changing this will either run or not run the message_friends function.
# 'valid': True
# }
# def authenticated(fn):
# def wrapper(*args, **kwargs):
# # Here valid equals True , *args[0] = (('name': 'Sorna'), ('valid': True)), ['valid'] = True or False
# if args[0]['valid']:
# return fn(*args, **kwargs)
# else:
# print('Ups, You are not logged in') # Here valid equals to False
# return wrapper
# @authenticated
# def message_friends(user):
# print('message has been sent')
# message_friends(user1)
# Error handling in Python
# while True:
# try:
# age = int(input('how old are you?'))
# 10/age
# print(age)
# except ValueError:
# print('please enter a number')
# except ZeroDivisionError:
# print('please enter age higher than zero')
# else:
# print('thank you')
# break
# def sum(num, num2):
# try:
# return num/num2
# except (TypeError, ZeroDivisionError) as err:
# print(f'please enter numbers or letters! -> {err}')
# print(sum(1, 0))
# while True:
# try:
# age = int(input('how old are you?'))
# 10/age
# raise ValueError('hey cut it out')
# except ZeroDivisionError:
# print('please enter age higher than zero')
# break
# else:
# print('thank you')
# finally:
# print('ok, i am already done')
# print('can you hear me')
# Generators
# range(100)
# list(range(100))
# def make_list(num):
# result = []
# for i in range(num):
# result.append(i)
# return result
# my_list = make_list(1000)
# print(my_list)
# # print(list(range(1000)))
# def generator_function(num):
# for i in range(num):
# yield i
# g = generator_function(100)
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# # for item in generator_function(1000):
# # print(item)
# # Why generators
import random
import sys
from random import randint
import main
import unittest
def performance(fn): # This allows to take the time of the script
def wrapper(*args, **kwargs):
t1 = time()
result = fn(*args, **kwargs)
t2 = time()
print(f'took {t2-t1} ms')
return result
return wrapper
# @performance
# def long_time():
# print('1')
# for i in range(100000):
# i*5
# @performance
# def long_time2():
# print('2')
# for i in list(range(100000)):
# i*5
# long_time()
# long_time2()
# So generators
# def gen_fun(num):
# for i in range(num):
# yield i
# for item in gen_fun(100):
# pass
# This is a for loop
# def special_for(iterable):
# iterator = iter(iterable)
# while True:
# try:
# print(iterator)
# print(next(iterator)*2)
# except StopIteration:
# break
# special_for([1, 2, 3])
# # This is how a range() works
# class MyGen():
# current = 0
# def __init__(self, first, last):
# self.first = first
# self.last = last
# def __iter__(self):
# return self
# def __next__(self):
# if MyGen.current < self.last:
# num = MyGen.current
# MyGen.current += 1
# return num
# raise StopIteration
# gen = MyGen(0, 100)
# for i in gen:
# print(i)
# # Fibonacci generator
# @performance
# def fib_num(num):
# a = 0
# b = 1
# for i in range(num):
# yield a
# temp = a
# a = b
# b = temp + b
# for x in fib_num(2000):
# print(x)
# @performance
# def fib_num2(num):
# a = 0
# b = 1
# result = []
# for i in range(num):
# result.append(a)
# temp = a
# a = b
# b = temp + b
# return result
# print(fib_num2(2000))
# from utility import multiply, divide
# from shopping.more_shopping import shopping_cart
# # print(shopping_cart.buy('item'))
# # print(divide(2, 3))
# # print(multiply(4, 20))
# # print(max([1,2,3]))
# # # if __name__ == '__main__'':
# # # print(shopping_cart.buy('item'))
# # # print(divide(2, 3))
# # # print(multiply(4, 20))
# # # print(max([1,2,3]))
# # # print(__name__)
# import utility
# import shopping.shopping_cart
# print(utility.divide(1, 2))
# print(shopping.shopping_cart.buy('item'))
# # Useful modules
# from collections import Counter, defaultdict, OrderedDict
# li = [1,2,3,4,5,6,7,7,7]
# sentence = 'blah blah blah thinking about python'
# print(Counter(li))
# print(Counter(sentence))
# my_dict = defaultdict(int,{'a' : 1, 'b':2}) # lambda: x -> this will return anything its in the variable lambda
# print(my_dict['a']) # returns 0 because nothing is inside the dictionaryt
# d = OrderedDict()
# d['a']=1
# d['b']=2
# d2 = OrderedDict()
# d2['b'] = 2
# d2['a'] = 1
# print(d2 ==d)
# import datetime
# print(datetime.time(2,0,0))
# print(datetime.date.today())
# from array import array
# arr = array('i', [1,2,3])
# print(arr[0])
# debuggin' tips
# use a linting for type errors in code
# use an IDE or a code editor instead
# learn to read errors
# PDB Python Debugger https://docs.python.org/3/library/pdb.html
# import pdb
# def add(num1, num2):
# pdb.set_trace()
# return num1 + num2
# add(4, 'asdasdasd')
# #
# print(my_file)
# my_file = open('test.txt')
# # print(my_file.read())
# # my_file.seek(0)
# # print(my_file.read())
# # my_file.seek(0)
# # print(my_file.read())
# # my_file.seek(0)
# print(my_file.readline())
# print(my_file.readlines())
# my_file.close()
# with open('test.txt', mode ='r') as my_file: # With 'r' allows to read the file and let you open and close the file without typing that
# print(my_file.readlines())
# with open('test.txt', mode ='r+') as my_file: # With 'r+' let you write in the file and alsolet you open and close the file without typing that
# text = my_file.write(':)')
# print(text) # Careful this replace the start of the file with everything you put on my_file.write(':)')
# with open('test.txt', mode ='a') as my_file: # With 'a' allows to append the text at the end of the file and also let you write in the file and alsolet you open and close the file without typing that
# text = my_file.write(':)')
# print(text)
# with open('test.txt', mode ='w') as my_file: # With 'w' allows to overwrite the text at the end of the file and also let you write in the file and alsolet you open and close the file without typing that
# text = my_file.write(':)')
# print(text)
# with open('sad.txt', mode='w') as my_file: #'w' also creates a new file is this doesnt exits
# text = my_file.write(':(')
# print(text)
# file paths
# with open('app/sad.txt', mode='r') as my_file: this will open the file sad.text on the app folder, the script necessary needs to be in one back path directory, in this case desktop
# print(my_file.read())
# C:/users/Ferna/desktop full path
# app/sad.txt relative path
# ./app/sad.txt this is the last directory, so this means that you are searching the folder in the last path
# ../ this means two steps back in path directory
# pathlib makes code paths work as unix as windows
# File IO Errors
# try:
# with open('sad.txt', mode='r') as my_file:
# print(my_file.read())
# except FileNotFoundError as err:
# print('Ups, the file does not exist')
# raise err
# except IOError as erro:
# print('IO Error')
# raise err
# Exercise Translator DONE
# Regular expressions
# PAGE WITH REGULAR EXPRESSION regex101.com
# pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
# string = 'fernando@gmail.com'
# a = pattern.search(string)
# print(a)
# # a = pattern.search(string)
# # b = pattern.findall(string)
# # c = pattern.fullmatch(string)
# # d = pattern.match(string)
# # print(b)
# # print(c)
# # print(d)
# # print(a.span())
# # print(a.start())
# # print(a.end())
# # print(a.group())
# # PAGE WITH REGULAR EXPRESSION regex101.com
# # Excercise: Create password checker with the next requirements
# # At least 8 char long
# # Contain any sort of letter, numbers, $@#@
# # has to end with a number
# password_pattern = re.compile(r"[A-Za-z0-9%&#$]{8,}\d")
# password = 'asdasdssS%3'
# check = password_pattern.fullmatch(password)
# print(check)
# class TestMain(unittest.TestCase):
# def setUp(self):
# print('about to test a function')
# def test_do_stuff(self):
# '''HIIIIIIIIIIIII'''
# test_param = 10
# result = main.do_stuff(test_param)
# self.assertEqual(result, 15)
# def test_do_stuff2(self):
# test_param = ('@@@23112', 2)
# result = main.do_stuff(test_param)
# self.assertIsInstance(result, (ValueError, TypeError))
# def test_do_stuff3(self):
# test_param = None
# result = main.do_stuff(test_param)
# self.assertEqual(result, 'Please enter a number')
# def test_do_stuff4(self):
# test_param = ''
# result = main.do_stuff(test_param)
# self.assertEqual(result, 'Please enter a number')
# def tearDown(self):
# print('cleaning up')
# if __name__ == '__main__':
# unittest.main()
# The command: python3 -m unittest only works with files that start with the word : "test"
# The command: python3 -m unittest -v gives more information of the tests"
# Excersice_testing
# def run_guess(guess, answer):
# if 0 < guess < 11:
# if guess == answer:
# print('you are a genius!')
# return True
# else:
# print('hey bozo, I said 1~10')
# if __name__ == '__playing__':
# answer = random.randint(1, 10)
# while True:
# try:
# guess = int(input('guess a number 1~10: '))
# if run_guess(guess, answer):
# break
# except ValueError:
# print('please enter a number')
# continue
|
fb12667207c15934a2e903f45ef052c6b0aabdef | Mounika2010/20186099_CSPP-1 | /cspp1-practice/m8/p2/assignment2.py | 596 | 4.0625 | 4 | '''
@author : Mounika2010
# Exercise: Assignment-2
# Write a Python function, sumofdigits, that takes in one number
and returns the sum of digits of given number.
# This function takes in one number and returns one number.
'''
def sumofdigits(n_inp):
'''
n is positive Integer
returns: a positive integer, the sum of digits of n.
'''
if n_inp == 0:
return 0
return n_inp%10 + sumofdigits(n_inp//10)
# Your code here
def main():
'''
sum of digits
'''
n_inp = input()
print(sumofdigits(int(n_inp)))
if __name__ == "__main__":
main()
|
b57ddf3048393cbe6881958774cc9abd9fce8345 | fabianobasso/Python_Projects | /Contact book/schedule/validateData.py | 1,681 | 3.546875 | 4 | # Funรงรตes de validaรงรฃo de dados
from time import sleep
import os
from .drawMenu import *
# Validation lists
numbers = ['0','1','2','3','4','5','6','7','8','9']
specialCharacters = ['!','@','#','$','%','&','*','(',')','-','_','+','=',';','.','<','>',':','/','?','~','^',']','[','{','}','ยด','`','"','|','\\','\'','\"']
aroba = ['@','.']
# text formatting
spceOp = 20
def validateName(data):
opName = True
global numbers, specialCharacters, spceOp
while opName:
os.system('clear')
drawMenuRegister(data)
print('\033[1;32m'+spceOp * " ",end=" ")
name = input("Digite Nome Completo: ")
print('\033[0;0m')
num = 0
for i in range(len(name)):
letter = name[i]
if letter in numbers:
num+=1
if letter in specialCharacters:
num+=1
if num == 0 and name != "" and name != " ":
opName = False
else:
drawNameInvalid()
sleep(3)
return name
def validateEmail(data):
opEmail = True
global aroba, spceOp
while opEmail:
os.system('clear')
drawMenuRegister(data)
print('\033[1;32m'+spceOp * " ",end=" ")
email = input("Digite Email: ")
print('\033[0;0m')
num = 0
for i in range(len(email)):
letter = email[i]
if letter in aroba:
num+=1
if num >= 2 and email != "" and email != " ":
opEmail = False
else:
drawEmailInvalid()
sleep(3)
return email |
71102497deb51ccf40f92534aa56dfc396d06528 | muindetuva/alx-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 988 | 3.859375 | 4 | #!/usr/bin/python3
'''
Contains the function island_perimeter
'''
def island_perimeter(grid):
'''
Returns the perimeter of the island descriibed in a grid
Args:
grid (list): A list of lists of integers
'''
perimeter = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 1:
try:
if grid[i][j - 1] == 0:
perimeter += 1
except:
pass
try:
if grid[i - 1][j] == 0:
perimeter += 1
except:
pass
try:
if grid[i][j + 1] == 0:
perimeter += 1
except:
pass
try:
if grid[i + 1][j] == 0:
perimeter += 1
except:
pass
return perimeter
|
1d5ca7eff89913816fc153e3667aa7c3bbde4cc8 | 28Lorena/dataproject | /week4-task10.py | 620 | 3.8125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
holiday = {"Destination": ["CountryA", "CountryB", "CountryC", "CountryD", "CountryE", "CountryF", "CountryG", "CountryH", "CountryI", "CountryJ", "CountryK", "CountryL", "CountryM", "CountryN", "CountryO"],
"Star Rating": [4.5, 3.0, 3.8, 4.4, 4.0, 4.7, 4.1, 4.0, 4.2, 3.3 , 4.0, 4.3, 4.6, 4.5, 3.9]}
df = pd.DataFrame (holiday, columns= ["Destination", "Star Rating"])
print (df [["Destination", "Star Rating"]])
df.plot (x="Destination", y="Star Rating", kind = "line")
plt.show()
|
eb2750a0b08596b9350b32b0c4b6b472a8fd08f0 | dbmarch/python-complete | /scope/scope.py | 764 | 3.9375 | 4 | def fact(n):
result = 1
if n > 1:
for f in range(2, n+1):
result *= f
return result
return result
def factorial(n):
if (n <= 1):
return 1
else:
return n * factorial(n-1)
def fib(n):
""" F(n) = F(n-1) + F(n-2) """
if n < 2:
return n
else:
return (fib(n-1) + fib(n-2))
def fibonacci(n):
if n == 0:
result = 0
elif n ==1:
result = 1
else:
n_minus1 = 1
n_minus2 = 0
for f in range(1,n):
result = n_minus2 + n_minus1
n_minus2 = n_minus1
n_minus1 = result
return result
for i in range (130):
# print (i , fact(i)-factorial(i))
print (i, fib(i))
print (i, fibonacci(i)) |
0d32a3a70178dc61ba190dd38efc565c09dbc7bb | moontree/leetcode | /version1/337_House_Robber_III.py | 1,525 | 3.953125 | 4 | """
The thief has found himself a new place for his thievery again.
There is only one entrance to this area, called the "root."
Besides the root, each house has one and only one parent house.
After a tour, the smart thief realized that "all houses in this place forms a binary tree".
It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
"""
from tree_helper import *
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.rob_helper(root)[1]
def rob_helper(self, root):
# return [without, max]
if root is None:
return [0, 0]
l = self.rob_helper(root.left)
r = self.rob_helper(root.right)
with_root = root.val + l[0] + r[0]
without_root = l[1] + r[1]
return [without_root, max(without_root, with_root)]
examples = [
{
"vals": [3, 2, 3, None, 3, None, 1],
"res": 7
}, {
"vals": [3, 4, 5, 1, 3, None, 1],
"res": 9
}
]
solution = Solution()
for example in examples:
tr = generate_tree_from_array(example["vals"])
print solution.rob(tr)
|
394131b909ae7fcf0673bc2064391437eb40eba2 | pineappledreams/python-algos | /edx/Week 1-3/reverse-string.py | 214 | 4.03125 | 4 | #Holy macaroni you can reverse strings so easily now!!
text = input("Enter thing you wanna get reversed: ")
print(text[::-1])
#Take THAT, programming interviews!
#No .split("").reverse().join(""); up this place! |
fabfa9d6f3ca75b88f8a26d5e9e7726c2a9194ae | GeorgyZhou/Leetcode-Problem | /lc414.py | 544 | 3.515625 | 4 | class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
import sys
return -sys.maxint - 1
import heapq
window = []
nums = list(set(nums))
heapq.heapify(window)
for n in nums:
if len(window) < 3:
heapq.heappush(window, n)
elif window[0] < n:
heapq.heappushpop(window, n)
return window[0] if len(window) == 3 else max(window) |
aee9313035b687eacd503867c93b31ab8b15ffbf | griswoldrx/hello-world | /remove_chars.py | 243 | 3.84375 | 4 | def remove_chars(x, y= "aeiou"):
z = ""
for i in x:
if i in y:
pass
else:
z = z + i
return z
print remove_chars("hello")
print remove_chars("abcdeiough")
print remove_chars('hallo', "l")
print remove_chars('hahahohohihi', 'aoi') |
60d3f0b1033ac976790f7c3b29b455d763a19b8c | jaramosperez/Pythonizando | /Ejercicios/Ejercicio 02.py | 341 | 4.25 | 4 | # EJERCICIO 02
# Determina mentalmente (sin programar) el resultado que aparecerรก
# por pantalla en las siguientes operaciones con variables:
a = 10
b = -5
c = "Hola "
d = [1, 2, 3]
print(a * 5) #50
print(a - b) #15
print(c + "Mundo") #"Hola Mundo"
print(c * 2) #"Hola" "Hola"
print(d[-1]) #3
print(d[1:]) #2,3
print(d + d) #[1,2,3,1,2,3] |
04f848faa94f5ec9c4c6ed7481eafd94d4061837 | anilbharadia/hacker-rank | /python/6.itertools/1.product/tut.py | 268 | 3.953125 | 4 | from itertools import product
print list(product([1, 2, 3], repeat = 2))
print list(product('ABC', repeat = 2))
print product('ABC', repeat = 2)
print list(product([1,2,3], [4,5,6]))
print list(product([1,2,3], 'ABC'))
print list(product([1,2,3], 'ABC', [4,5,6])) |
496e102bee64d2627f50d5c13f8049d7194004d7 | rodolphorosa/intcomp | /perceptron/plot.py | 752 | 3.65625 | 4 | import matplotlib.pyplot as plt
from numpy import array
"""
@brief Plots decision boundary.
"""
def plot_boundary(X, h, w, c='g'):
colormap = ['r' if i < 0 else 'b' for i in h]
slope = -(w[1]/w[2])
intercept = -(w[0]/w[2])
px = array([-1, 1])
py = slope*px + intercept
plt.ylim([-1, 1])
plt.xlim([-1, 1])
plt.scatter(X[:, 1], X[:, 2], c=colormap, marker='.')
plt.plot(px, py, c=c, linewidth=.5, linestyle='--', label="hipothesis")
"""
@brief Plots target function
"""
def plot_target(f, c='c'):
x = array([-1, 1])
y = f(x)
plt.plot(x, y, c='c', label="f(x)")
"""
@brief Exibits target function and decision boundary
"""
def plot_show():
plt.title("Perceptron Learning Algorithm - PLA")
plt.legend(loc="upper right")
plt.show()
|
bd2071ac6ad1efbad23148acb0d38e1bf6d317c6 | LuizC-Araujo/python | /EXERCICIOS PARTE 1/EXE 002 - MEDIA ARITMรTICA.py | 279 | 3.796875 | 4 | n4 = input("Digite a primeira nota: ")
n4 = int(n4)
n2 = input("Digite a segunda nota: ")
n2 = int(n2)
n3 = input("Digite a terceira nota: ")
n3 = int(n3)
n1 = input("Digite a quarta nota: ")
n1 = int(n1)
media = (n1 + n2 + n3 + n4) / 4
print("A mรฉdia aritmรฉtica รฉ", media)
|
62f51c63804b0a80326f429d7dcbb1f7796c37ef | emily1749/Leetcode | /103_binary_tree_zigzag_lvl_order_traversal.py | 2,776 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None: return None
result, temp, queue, flag = [], [], deque(), 1
queue.append(root)
while queue:
# length = len(queue)
for i in range(len(queue)):
current = queue.popleft()
temp.append(current.val)
if current.left: queue.append(current.left)
if current.right: queue.append(current.right)
result.append(temp[::flag])
temp = []
flag*=-1
return result
# if root == None:
# return None
# idx = 0
# queue = []
# result = []
# queue.append(root)
# while len(queue)>0:
# level_queue = queue
# queue = []
# level_result = []
# while len(level_queue)>0:
# current = level_queue.pop(0)
# level_result.append(current.val)
# if current.left:
# queue.append(current.left)
# if current.right:
# queue.append(current.right)
# result.append(level_result)
# if idx % 2 == 1:
# idx +=1
# return result
# if root == None:
# return None
# idx = 0
# queue = []
# result = []
# queue.append(root)
# while len(queue)>0:
# level_queue = queue
# queue = []
# level_result = []
# while len(level_queue)>0:
# current = level_queue.pop(0)
# level_result.append(current.val)
# if idx % 2 == 1:
# #left then right
# if current.left:
# queue.append(current.left)
# if current.right:
# queue.append(current.right)
# else:
# #right then left
# if current.right:
# queue.append(current.right)
# if current.left:
# queue.append(current.left)
# idx+=1
# result.append(level_result)
# return result |
d067b7ab2da2cac265780cb83e4f536fb0263dd9 | dpattison/cdassignments | /Python/animal.py | 1,175 | 3.9375 | 4 | class animal(object):
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
print self.health
return self
animal1 = animal("Tiger", 20)
animal1.display_health().walk().walk().walk().run().run().display_health()
class dog(animal):
def __init__(self, name):
super(dog, self).__init__(name, 150)
def pet(self):
self.health += 5
return self
dog1 = dog("Fido")
dog1.display_health().walk().walk().walk().run().run().pet().display_health()
class dragon(animal):
def __init__(self, name):
super(dragon, self).__init__(name, 170)
self.health = 170
def fly(self):
self.health -= 10
return self
def display_health(self):
super(dragon, self).display_health()
print "I am a Dragon"
return self
dragon1 = dragon("Slick")
dragon1.fly().display_health()
animal2 = animal("willy", 50)
# animal2.fly()
# animal2.pet()
animal2.display_health()
# dog1.fly() |
8edd1ca8676c4b25c163eb35b32f219580584a47 | v-tsepelev/Programming_HSE | /polynomial.py | 13,569 | 3.671875 | 4 | # Module for work with polynomials.
# Author: Vladimir Tsepelev, tsepelev at openmailbox.org
import math
class Polynomial:
def __init__(self, coefficients):
if isinstance(coefficients, list):
self.coefficients = coefficients
elif isinstance(coefficients, int):
self.coefficients = []
self.coefficients.append(coefficients)
elif isinstance(coefficients, Polynomial):
self.coefficients = coefficients.coefficients
elif isinstance(coefficients, dict):
self.coefficients = []
powers = sorted(coefficients.keys())
for i in powers:
self.coefficients.append(coefficients[i])
self.n = len(self.coefficients)
self.count = 0
self.visual = ""
def degree(self):
return int(self.n-1)
def __add__(self, other):
if isinstance(other, Polynomial) or isinstance(other, QuadraticPolynomial):
new_coefficients = []
for i in range(min(self.degree() + 1, other.degree() + 1)):
new_coefficients.append(self.coefficients[i] + other.coefficients[i])
if self.degree() > other.degree():
for i in range(other.degree() + 1, self.degree() + 1):
new_coefficients.append(self.coefficients[i])
elif self.degree() < other.degree():
for i in range(self.degree() + 1, other.degree() + 1):
new_coefficients.append(other.coefficients[i])
if isinstance(other, QuadraticPolynomial) and len(new_coefficients) > 3:
raise DegreeIsTooBig(len(new_coefficients) - 1)
else:
return Polynomial(new_coefficients)
else:
new_coefficients = []
for i in range(self.degree() + 1):
new_coefficients.append(self.coefficients[i])
new_coefficients[0] = self.coefficients[0] + int(other)
return Polynomial(new_coefficients)
def __sub__(self, other):
if isinstance(other, Polynomial) or isinstance(other, QuadraticPolynomial):
new_coefficients = []
for i in range(min(self.degree() + 1, other.degree() + 1)):
new_coefficients.append(self.coefficients[i] - other.coefficients[i])
if self.degree() > other.degree():
for i in range(other.degree() + 1, self.degree() + 1):
new_coefficients.append(self.coefficients[i])
elif self.degree() < other.degree():
for i in range(self.degree() + 1, other.degree() + 1):
new_coefficients.append(-other.coefficients[i])
if isinstance(other, QuadraticPolynomial) and len(new_coefficients) > 3:
raise DegreeIsTooBig(len(new_coefficients) - 1)
else:
return Polynomial(new_coefficients)
else:
for i in range(self.degree() + 1):
new_coefficients.append(self.coefficients[i])
new_coefficients[0] = self.coefficients[0] - int(other)
return Polynomial(new_coefficients)
def __neg__(self):
new_coefficients = []
for i in range(self.degree() + 1):
new_coefficients.append(-self.coefficients[i])
return Polynomial(new_coefficients)
def __mul__(self, other):
if isinstance(other, Polynomial) or isinstance(other, QuadraticPolynomial):
new_coefficients = []
for k in range(self.degree() + other.degree() + 1):
x = []
for i in range(self.degree() + 1):
for j in range(other.degree() + 1):
if (i + j == k):
x.append(self.coefficients[i]*other.coefficients[j])
new_coefficients.append(sum(x))
if isinstance(other, QuadraticPolynomial) and len(new_coefficients) > 3:
raise DegreeIsTooBig(len(new_coefficients) - 1)
else:
return Polynomial(new_coefficients)
else:
new_coefficients = []
for i in range(self.degree() + 1):
new_coefficients.append(other*self.coefficients[i])
return Polynomial(new_coefficients)
def __mod__(self, number):
new_coefficients = []
for i in range(self.degree() + 1):
new_coefficients.append(self.coefficients[i] % int(number))
return Polynomial(new_coefficients)
def __eq__(self, other):
if isinstance(other, Polynomial):
return self.coefficients == other.coefficients
if isinstance(other, int):
if self.degree() == 0:
return self.coefficients[0] == other
else:
return False
def __str__(self):
if self.degree() == 0:
return str(self.coefficients[0])
elif self.degree() == 1:
if self.coefficients[1] < 0:
self.visual = str(self.coefficients[0]) + str(self.coefficients[1]) + "t"
else:
self.visual = str(self.coefficients[0]) + "+" + str(self.coefficients[1]) + "t"
return self.visual
else:
if self.coefficients[1] < 0:
self.visual = str(self.coefficients[0]) + str(self.coefficients[1]) + "t"
else:
self.visual = str(self.coefficients[0]) + "+" + str(self.coefficients[1]) + "t"
for i in range(2, self.degree()):
if self.coefficients[i] < 0:
self.visual = self.visual + str(self.coefficients[i]) + "t^" + str(i)
else:
self.visual = self.visual + "+" + str(self.coefficients[i]) + "t^" + str(i)
if self.coefficients[self.degree()] < 0:
self.visual = self.visual + str(self.coefficients[self.degree()]) + "t^" + str(self.degree())
else:
self.visual = self.visual + "+" + str(self.coefficients[self.degree()]) + "t^" + str(self.degree())
return self.visual
def subst(self, x):
result = 0
for i in range(0, self.degree() + 1):
result += self.coefficients[i]*(x**i)
return result
def der(self, d = 1):
if d == 1:
new_coefficients = []
for i in range(self.degree()):
new_coefficients.append(self.coefficients[i+1]*(i+1))
return Polynomial(new_coefficients)
elif d > self.degree():
return int(0)
elif d == self.degree():
x = self.coefficients[self.degree()]
for i in range(1, self.degree() + 1):
x *= i
return x
else:
new_coefficients = []
for i in range(self.degree()):
new_coefficients.append(self.coefficients[i+1]*(i+1))
return Polynomial(new_coefficients).der(d-1)
def dersubst(self, x, d = 1):
return self.der(d).subst(x)
def __iter__(self):
return self
def __next__(self):
if self.count == 0:
self.count += 1
return (0, self.coefficients[0])
else:
if self.count < self.degree() + 1:
self.count += 1
return (self.count - 1, self.coefficients[self.count - 1])
else:
raise StopIteration
class RealPolynomial(Polynomial):
def find_root(self, left_x = "none", right_x = "none", epsilon = 0.01):
if isinstance(left_x, int) and isinstance(right_x, int) and self.subst(left_x)*self.subst(right_x) < 0:
a = left_x
b = right_x
while abs(b - a) > epsilon:
c = (a + b) / 2
if self.subst(b)*self.subst(c) < 0:
a = c
elif self.subst(a)*self.subst(c) < 0:
b = c
root = (a + b) / 2
return root
else:
a = -1000
b = 1000
while self.subst(a)*self.subst(b) >= 0:
a *= 2
b *= 2
return self.find_root(a, b)
def locmin_value(self, left_x, right_x):
x = self.der().find_root(left_x, right_x, epsilon = 0.01)
if self.substder(x, 2) > 0:
return x
def locmax_value(self, left_x, right_x):
x = self.der().find_root(left_x, right_x, epsilon = 0.01)
if self.substder(x, 2) < 0:
return x
class QuadraticPolynomial(Polynomial):
def __init__(self, coefficients):
Polynomial.__init__(self, coefficients)
if self.degree() > 2:
raise Exception("ะั ะฟััะฐะตัะตัั ัะพะทะดะฐัั ะผะฝะพะณะพัะปะตะฝ ััะตะฟะตะฝะธ, ะฑะพะปััะตะน ัะตะผ 2")
def __add__(self, other):
if isinstance(other, Polynomial) or isinstance(other, QuadraticPolynomial):
new_coefficients = []
for i in range(min(self.degree() + 1, other.degree() + 1)):
new_coefficients.append(self.coefficients[i] + other.coefficients[i])
if self.degree() > other.degree():
for i in range(other.degree() + 1, self.degree() + 1):
new_coefficients.append(self.coefficients[i])
elif self.degree() < other.degree():
for i in range(self.degree() + 1, other.degree() + 1):
new_coefficients.append(other.coefficients[i])
if len(new_coefficients) > 3:
raise DegreeIsTooBig(len(new_coefficients) - 1)
else:
return QuadraticPolynomial(new_coefficients)
else:
new_coefficients = []
for i in range(self.degree() + 1):
new_coefficients.append(self.coefficients[i])
new_coefficients[0] = self.coefficients[0] + int(other)
return QuadraticPolynomial(new_coefficients)
def __sub__(self, other):
if isinstance(other, Polynomial) or isinstance(other, QuadraticPolynomial):
new_coefficients = []
for i in range(min(self.degree() + 1, other.degree() + 1)):
new_coefficients.append(self.coefficients[i] - other.coefficients[i])
if self.degree() > other.degree():
for i in range(other.degree() + 1, self.degree() + 1):
new_coefficients.append(self.coefficients[i])
elif self.degree() < other.degree():
for i in range(self.degree() + 1, other.degree() + 1):
new_coefficients.append(-other.coefficients[i])
if len(new_coefficients) > 3:
raise DegreeIsTooBig(len(new_coefficients) - 1)
else:
return QuadraticPolynomial(new_coefficients)
else:
for i in range(self.degree() + 1):
new_coefficients.append(self.coefficients[i])
new_coefficients[0] = self.coefficients[0] - int(other)
return QuadraticPolynomial(new_coefficients)
def __mul__(self, other):
if isinstance(other, Polynomial) or isinstance(other, QuadraticPolynomial):
new_coefficients = []
for k in range(self.degree() + other.degree() + 1):
x = []
for i in range(self.degree() + 1):
for j in range(other.degree() + 1):
if (i + j == k):
x.append(self.coefficients[i]*other.coefficients[j])
new_coefficients.append(sum(x))
if len(new_coefficients) > 3:
raise DegreeIsTooBig(len(new_coefficients) - 1)
else:
return QuadraticPolynomial(new_coefficients)
else:
new_coefficients = []
for i in range(self.degree() + 1):
new_coefficients.append(other*self.coefficients[i])
return QuadraticPolynomial(new_coefficients)
def solve(self):
if self.degree() == 0:
return []
elif self.degree() == 1:
return [-self.coefficients[0]/self.coefficients[1]]
else:
a = self.coefficients[2]
b = self.coefficients[1]
c = self.coefficients[0]
D = b**2-4*a*c
if abs(D) <= 1e-10:
x = -b/(2*a)
return [x]
elif D > 1e-10:
x1 = (-b+D**0.5)/(2*a)
x2 = (-b-D**0.5)(2*a)
return [x1, x2]
elif D < -1e-10:
return []
class DegreeIsTooBig(Exception):
def __init__(self, x, y = 2):
self.x = x
self.y = y
def __str__(self):
if isinstance(self.x, str):
return self.x
elif isinstance(self.x, int):
error = "ะ ัะตะทัะปััะฐัะต ะพะฟะตัะฐัะธะธ ะฟะพะปััะธะปัั ะผะฝะพะณะพัะปะตะฝ ััะตะฟะตะฝะธ {0}, ะผะฐะบัะธะผะฐะปัะฝะพ ะดะพะฟัััะธะผะฐั ััะตะฟะตะฝั {1}".format(self.x, self.y)
return error
|
384ec3d7aca7183d3612334cc4837e910bc6157a | Manash-git/CP-LeetCode-Solve | /1523. Count Odd Numbers in an Interval Range.py | 527 | 3.96875 | 4 | '''Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
'''
low = 3
high = 7
# 800445804
# 979430543
# low = 800445804
# high = 979430543
count=0
for i in range(low,high+1):
if i%2!=0:
count+=1
print(count)
def countOdd(low,high):
total_no= (high-low)+1
if total_no%2==0:
return total_no//2
elif high%2==0 and low%2==0:
return total_no//2
else:
return (total_no//2)+1
print(countOdd(3,7))
print(countOdd(800445804,979430543))
|
fa2d395a19cd082cdc5952cf80cb1b04a61ba83c | EnvGen/toolbox | /scripts/parse_augustus_basic.py | 1,563 | 3.6875 | 4 | #!/usr/bin/env python
"""
Reads an augustus output file and prints the amino_acid fasta file to stdout
@author: alneberg
"""
import sys
import os
import argparse
def to_fasta(s, gene_id, contig_id):
print('>{}_{}'.format(contig_id, gene_id))
print(s)
def main(args):
with open(args.augustus_output) as ifh:
protein_str = None
for line in ifh:
line = line.strip()
# Check contig_id
if not line.startswith('#'):
contig_id = line.split('\t')[0]
# Check if protein starts
elif line.startswith('# protein sequence'):
line = line.replace('# protein sequence = [', '')
protein_str = line.replace(']','')
protein_str = line
elif protein_str:
# If protein ends
# Parse lines and output to stdout
if line.startswith('# end gene'):
line = line.replace('# end gene ', '')
gene_id = line
to_fasta(protein_str, gene_id, contig_id)
protein_str = None
else:
# add to protein lines
line = line.replace('# ', '')
line = line.replace(']', '')
protein_str += line
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("augustus_output", help=("Standard output format of augustus."))
args = parser.parse_args()
main(args)
|
f170bc6d09ad6680d80975fb8e8d0daa99ab8b12 | yangdaotamu/niuke | /็ผ็จ็ปไน /ๆพ้ฃ็ฉ.py | 1,697 | 3.875 | 4 | # ้ข็ฎๆ่ฟฐ
# ๅฐๆๆปๆฏๆ่ง้ฅฅ้ฅฟ๏ผๆไปฅไฝไธบ็ซ ้ฑผ็ๅฐๆ็ปๅธธๅบๅปๅฏปๆพ่ดๅฃณๅใๆๅผๅงๅฐๆๅจไธไธชๅๅงไฝ็ฝฎx_0ใ
# ๅฏนไบๅฐๆๆๅค็ๅฝๅไฝ็ฝฎx๏ผไปๅช่ฝ้่ฟ็ฅ็ง็ๅ้็งปๅจๅฐ 4 * x + 3ๆ่
8 * x + 7ใๅ ไธบไฝฟ็จ
# ็ฅ็งๅ้่ฆ่่ดนๅคชๅคไฝๅ๏ผๆไปฅๅฎๅช่ฝไฝฟ็จ็ฅ็งๅ้ๆๅค100,000ๆฌกใ่ดๅฃณๆป็้ฟๅจ่ฝ่ขซ1,000,000,007
# ๆด้ค็ไฝ็ฝฎ(ๆฏๅฆ๏ผไฝ็ฝฎ0๏ผไฝ็ฝฎ1,000,000,007๏ผไฝ็ฝฎ2,000,000,014็ญ)ใๅฐๆ้่ฆไฝ ๅธฎๅฟ่ฎก็ฎๆ
# ๅฐ้่ฆไฝฟ็จๅคๅฐๆฌก็ฅ็งๅ้ๅฐฑ่ฝๅๅฐ่ดๅฃณใ
# ่พๅ
ฅๆ่ฟฐ:
# ่พๅ
ฅไธไธชๅๅงไฝ็ฝฎx_0,่ๅดๅจ1ๅฐ1,000,000,006
# ่พๅบๆ่ฟฐ:
# ่พๅบๅฐๆๆๅฐ้่ฆไฝฟ็จ็ฅ็งๅ้็ๆฌกๆฐ๏ผๅฆๆไฝฟ็จๆฌกๆฐไฝฟ็จๅฎ่ฟๆฒกๆพๅฐ่ดๅฃณ๏ผๅ่พๅบ-1
def Solution(a):
temp=[a,4*a+3,16*a+15]
for j,m in enumerate(temp):
for i in range(100000):
m=(m*8+7)%1000000007
if m==0:
return i+j+1
return -1
a=int(raw_input(""))
ans=Solution(a)
print ans
# ่ฎพf(x)=4x+3,g(x)=8x+7ใ
# ่ฎก็ฎๅฏไปฅๅพๅฐไปฅไธไธคไธช่งๅพ๏ผ
# ๏ผ1๏ผ g(f(x))=f(g(x)) ๅณfๅg็ๆง่ก้กบๅบๆฒกๆๅฝฑๅใ
# ๏ผ2๏ผ f(f(f(x)))=g(g(x)) ๅณๅ3ๆฌกfๅๆข็ญไปทไบๅ2ๆฌกgๅๆข
# ็ฑไบ่งๅพ๏ผ1๏ผ ๅฏนไบไธไธชๅฏ่กๆนๆก๏ผๆไปฌๅฏไปฅ่ฐๆดๅ
ถๅๆข็้กบๅบใๅฆffggfggff๏ผๆไปฌๅฏไปฅ่ฝฌๅๆ fffffggggใ
# ็ฑไบ่งๅพ๏ผ2๏ผ๏ผๅนถไธไธบไบไฝฟๆง่กๆฌกๆฐๆๅฐ๏ผๆฏ3ไธชfๆไปฌๅฏไปฅ่ฝฌๅๆ2ไธชg๏ผๅฆๆนๆกfffffgggg๏ผๅฏไปฅ่ฝฌๅๆffggggggใ
# ๅ ๆญคไธไธชๆไผ็็ญ็ฅ๏ผf็ๆง่กๆฌกๆฐๅช่ฝไธบ0,1,2ใๅฏนไบ่พๅ
ฅ็x๏ผๆไปฌๅช้่ฆๆฑx๏ผ4x+3,4๏ผ4x+3๏ผ+3็ๆๅฐgๆง่กๆฌกๆฐๅฐฑๅฏไปฅไบใ |
0fd7c11542e95bd3522dd6ffaf44f186991c4476 | navinkumar-choudhary/TestPythonProject | /mainDemo.py | 334 | 3.625 | 4 | name = "Navin"
def fun(x):
print("value from fun one: ",name)
print("X value before modification in Fun1: ", x)
x = 100
print("X value after modification in Fun1: ", x)
def main():
print("Hi")
print("Value from main: ",name)
x=20
fun(x)
print("Value of x in main method: ",x)
main() |
d1fd84de6aa84041a09bae457509caeb5c55bb04 | iceknc/python_study_note | /cn/iceknc/study/e_python_mult_task/b_thread_extend.py | 392 | 3.71875 | 4 | """
็ปงๆฟThread็ฑปๅฎๆๅๅปบ็บฟ็จ
"""
import threading
import time
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
self.name = "MyThread"
def run(self):
for i in range(10):
str = "My name is "+ self.name
print(str)
time.sleep(1)
if __name__ == '__main__':
t = MyThread()
t.start()
|
515fa7c5cb9d4ea91d60026568c1a750a9875a5a | Gav104/practice_code | /pastimes.py | 973 | 3.546875 | 4 | import os
import csv
path = "C:/Users/Gavin/PycharmProjects/Practice_code"
high_scores_dict = {}
in_file_path = os.path.join(path, "scores.csv")
out_file_path = os.path.join(path, "highest_scores.csv")
with open(in_file_path, "r") as myFile, open(out_file_path, "w", newline="") as out_file:
my_file_reader = csv.reader(myFile)
for name, score in my_file_reader: # get each name/score pair
score = int(score) # convert string score to integer
if name in high_scores_dict: # already had an entry for that name
if score > high_scores_dict[name]: # new score is higher
high_scores_dict[name] = score
else: # haven't seen this name yet; add it to dictionary
high_scores_dict[name] = score
for name in sorted(high_scores_dict):
guess = name, high_scores_dict[name]
print(name, high_scores_dict[name])
writer = csv.writer(out_file)
writer.writerows([guess])
|
365edf821332b7b73db7918ad7facd048bcdccbb | YeomanYe/show-me-the-code | /0020/parseExcel.py | 583 | 3.609375 | 4 | #! python3
# -*- coding:utf-8 -*-
import xlrd
book = xlrd.open_workbook("็งปๅจ่ฏ่ดน่ฏฆๅ.xls")
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("sheetName:{0} sheetRows:{1} sheetCols:{2}".format(
sh.name, sh.nrows, sh.ncols))
print("Cell D4 is {0}".format(sh.cell_value(rowx=3, colx=3)))
sum = 0
for rx in range(sh.nrows):
if rx != 0:
print(sh.row(rx)[3].value)
sum += float(sh.row(rx)[3].value)
if rx == 3:
print("ๅ่ฎก๏ผ" + str(sum))
|
4b1f98c248538718ea43cce9ecf7cd0c4daed3cb | AbelRapha/Python-Exercicios-CeV | /Mundo 1/ex007 Media Aritmetica.py | 239 | 3.921875 | 4 | nota1 = int(input("Digite aqui a sua primeira nota "))
nota2 = int(input("Digite aqui a sua segunda nota "))
def Media(n1,n2):
return (n1+n2) /2
print(f"Considerando as notas inseridas a sua media final foi {Media(nota1,nota2):.2f}") |
8c25d622ce61325db3b3d19cc09e67b8729861d1 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/64_splitting_objects_inside_a_list.py | 2,275 | 4.25 | 4 | """
Splitting Objects Inside a List
You bought a few bunches of fruit over the weekend. Create a function that splits a bunch into singular objects inside a list.
Examples
split_bunches([
{ name: "grapes", quantity: 2 }
]) โ [
{ name: "grapes", quantity: 1 },
{ name: "grapes", quantity: 1 }
]
split_bunches([
{ name: "currants", quantity: 1 },
{ name: "grapes", quantity: 2 },
{ name: "bananas", quantity: 2 }
]) โ [
{ name: "currants", quantity: 1},
{ name: "grapes", quantity: 1 },
{ name: "grapes", quantity: 1 },
{ name: "bananas", quantity: 1 },
{ name: "bananas", quantity: 1 }
]
Notes
The input list will never be empty.
Objects will always have a name and quantity over 0.
The returned object should have each fruit in the same order as the original.
"""
def split_bunches(bunches):
a, b = [], []
for i in bunches:
a.append(i["quantity"])
i["quantity"]=1
for i in range(len(bunches)):
for j in range(a[i]):
b.append(bunches[i])
return b
#split_bunches([{ "name": 'bananas', "quantity": 1 }]) #, [{ "name": 'bananas', "quantity": 1 }])
#split_bunches([{ "name": 'bananas', "quantity": 2 }, { "name": 'grapes', "quantity": 2 }]) #, [{ "name": 'bananas', "quantity": 1 }, { "name": 'bananas', "quantity": 1 }, { "name": 'grapes', "quantity": 1 }, { "name": 'grapes', "quantity": 1 }])
split_bunches([{ "name": 'cherry tomatoes', "quantity": 3}, { "name": 'bananas', "quantity": 1 }, { "name": 'grapes', "quantity": 2 }, { "name": 'cherry tomatoes', "quantity": 3}]) #, [{ "name": 'cherry tomatoes', "quantity": 1}, { "name": 'cherry tomatoes', "quantity": 1}, { "name": 'cherry tomatoes', "quantity": 1}, { "name": 'bananas', "quantity": 1 }, { "name": 'grapes', "quantity": 1 }, { "name": 'grapes', "quantity": 1 }, { "name": 'cherry tomatoes', "quantity": 1}, { "name": 'cherry tomatoes', "quantity": 1}, { "name": 'cherry tomatoes', "quantity": 1}])
#split_bunches([{ "name": "currants", "quantity": 1 }, {"name": "grapes", "quantity": 2 }, {"name": "bananas", "quantity": 2 }]) #, [{"name": "currants", "quantity": 1},{"name": "grapes", "quantity": 1 },{"name": "grapes", "quantity": 1 },{"name": "bananas", "quantity": 1 },{"name": "bananas", "quantity": 1 }]) |
4be48b5a83e72d51ff44b0378b9992ddf48e82c1 | ryanyuchen/Data-Structure-and-Algorithms | /4 Algorithms on Strings/Week 1 Suffix Trees/Programming-Assignment-1/suffix_tree/suffix_tree.py | 1,840 | 3.6875 | 4 | # python3
import sys
_END = '$'
def compress_recursive(tree, node):
for (key, child_node) in tree[node].items():
if key == "start":
return
if len(tree[child_node]) == 1:
path_char = next(iter(tree[child_node]))
if path_char != "start":
grand_child_node = tree[child_node][path_char]
tree[node][key + path_char] = grand_child_node
del tree[node][key]
del tree[child_node]
compress_recursive(tree, grand_child_node)
else:
compress_recursive(tree, child_node)
def build_suffix_tree(text):
"""
Build a suffix tree of the string text and return a list
with all of the labels of its edges (the corresponding
substrings of the text) in any order.
"""
result = []
# Implement this function yourself
tree = dict()
tree[0] = {}
index = 0
for start in range(len(text)):
word = text[start:]
current_node = 0
for char in word:
if char in tree[current_node].keys():
current_node = tree[current_node][char]
else:
index += 1
new_node = index
if char == _END:
tree[new_node] = {"start": start}
else:
tree[new_node] = {}
tree[current_node][char] = new_node
current_node = new_node
current_node = 0
compress_recursive(tree, current_node)
for node in tree:
for c in tree[node]:
if c != "start":
result.append(c)
return result
if __name__ == '__main__':
text = sys.stdin.readline().strip()
result = build_suffix_tree(text)
print("\n".join(result)) |
1575bc3c5c67c5de8d4b7a0e79a4492c70843dc5 | filipe1992/Teoria-da-computa-o | /hw04/05.py | 1,481 | 3.734375 | 4 | '''
Created on 30 de nov de 2018
@author: filiped
'''
'''
Implemente em linguagem de programaรงรฃo ร sua escolha o algoritmo
CYK. Seu programa deve receber como entrada uma gramรกtica livre de
contexto na Forma Normal de Chomsky e uma string de teste da
gramรกtica. Descreva como deverรก ser o formato dessa gramรกtica.
'''
g = {"AA": ["S"],
"AS": ["S","A"],
"b": ["S"],
"SA": ["A"],
"a": ["A"]
}
c = "abaab"
def produzido_por(val):
if val in g:
return g[val]
return []
def printmat(mat):
for i in mat[::-1]:
print(i)
def passo1(mat,cadeia):
mat[1]= [g[i] for i in cadeia]
def roldana(mat, n):
for s in range(2,n+1):
for r in range(n-s+1):
mat[s][r]=[]
for k in range(1,s):
for i in mat[k][r]:
for j in mat[s-k][r+k]:
aux = produzido_por(i+j)
for a in aux:
if not (a in mat[s][r]):
mat[s][r]+= a
def CYK(gramatica, cadeia):
mat = [list(cadeia)]+[[""]*len(cadeia) for _ in range(len(cadeia))]
passo1(mat,cadeia)
print("\n#------------------------------Primeiro Passo-------------------------------------\n\n")
printmat(mat)
roldana(mat, len(cadeia))
print("\n#------------------------------Completo-------------------------------------\n\n")
printmat(mat)
CYK(g, c)
|
5af383466d4791551082f4703bba000c696711f0 | mkurde/the-coding-interview | /problems/intersections/intersections.py | 144 | 3.625 | 4 | def intersections(lst1,lst2):
return [i for i in lst1 if i in lst2]
print(intersections(['dog', 'cat', 'egg'], ['cat', 'dog', 'chicken'])) |
258a30e249830765833e08f164b4954d86ca44e4 | h-yaroslav/pysnippets | /lections/fib.py | 276 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
import os, sys
def fib(n): # ะะธะฒัะด ัะธัะตะป ะคัะฑะพะฝะฐััั ะดะพ ะทะฐะดะฐะฝะพะณะพ n
result = [1]
a, b = 0, 1
while b < n:
# print b,
a, b = b, a+b
result.append(b)
return result
a = fib(1000)
print a |
a61ef321e7643814224d7f238ac29561cc5cfe75 | TakuroKato/AOJ | /ITP1_1_B.py | 70 | 3.5625 | 4 | # -*- coding:utf-8 -*-
x = int(input())
result = x**3
print(result)
|
36ed4e9edacac9ddcfabea0c5ecbd5925bb84934 | sayantann11/Automation-scripts | /password_manager/password_manager.py | 11,768 | 3.59375 | 4 | #!/usr/bin/python3
# Created by Sam Ebison ( https://github.com/ebsa491 )
# If you have found any important bug or vulnerability,
# contact me pls, I love learning ( email: ebsa491@gmail.com )
"""
This is a simple password manager CLI program
based on https://github.com/python-geeks/Automation-scripts/issues/111
"""
import argparse
import sys
import os
import sqlite3
import base64
import signal
from getpass import getpass
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
# The program data file.
FILENAME = ".pass.db"
# Cookie(canary) value
COOKIE = "===PASSWORDS==="
# For coloring the outputs
GREEN_COLOR = "\033[1;32m"
RED_COLOR = "\033[1;31m"
NO_COLOR = "\033[0m"
def main():
"""The main function of the program."""
status, is_first = check_database() # status{0|-1} is_first{True|False}
if status == -1:
# ERROR
print(f"[{RED_COLOR}-{NO_COLOR}] Error in database connection...")
sys.exit(1)
if args.password == '' or args.password is None:
# User didn't enter the password (argument)
if is_first:
# New user
user_password = getpass("Enter a new password for the program> ")
confirm = getpass("Confirm it> ")
if user_password != confirm:
# ERROR
print(f"[{RED_COLOR}-{NO_COLOR}] Didn't match...")
sys.exit(1)
if new(user_password, COOKIE, '-', 0) != 0:
# ERROR (Cookie didn't set)
print(f"[{RED_COLOR}-{NO_COLOR}] Error in saving...")
os.remove(FILENAME)
sys.exit(1)
else:
user_password = getpass("Enter your user password> ")
if check_password(user_password) != 0:
# ERROR
print(f"[{RED_COLOR}-{NO_COLOR}] Wrong password...")
sys.exit(1)
else:
# We have the password here
user_password = args.password
if check_password(user_password) != 0:
# ERROR
print(f"[{RED_COLOR}-{NO_COLOR}] Wrong password...")
sys.exit(1)
prompt(user_password)
def check_database():
"""
This function checks the database file.
If everything was going OK returns 0, is_first{True|False}
and if not returns -1, False.
If is_first was True that means the program has run for the first time.
"""
try:
# If it was True that means the program has run for the first time
is_first = False
if not os.path.isfile(FILENAME):
is_first = True
with sqlite3.connect(FILENAME) as conn:
cursor = conn.cursor()
cursor.execute(
"""CREATE TABLE IF NOT EXISTS passwords (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
password TEXT NOT NULL
);"""
)
return 0, is_first
except Exception:
return -1, False
def check_password(user_password):
"""
This function checks the user password and will return two values {0|-1},
0 means the password is correct,
-1 means it's wrong.
"""
try:
with sqlite3.connect(FILENAME) as conn:
cursor = conn.cursor()
# Fetches the cookie (canary) value
row = cursor.execute(
"SELECT * FROM passwords WHERE id=0;"
).fetchone()
bin_user_password = str(user_password).encode('utf-8')
if decrypt(bin_user_password, row[1]).decode('utf-8') == COOKIE:
# The password is correct
# because it can decrypt the encrypted cookie value
return 0
else:
# The password can't decrypt the cookie value (Wrong)
return -1
except Exception:
return -1
def prompt(user_password):
"""
This function will be called after checking the password and database.
It gives you a prompt for entering your commands.
Valid commands are 'new', 'delete', 'show', 'exit'.
"""
print("Commands: [new] [delete] [show] [exit]")
try:
cmd = input("Enter your command> ")
except EOFError:
print("\nBye...")
sys.exit(0)
if cmd.lower() == 'new':
name = input("Where did you use this password for> ")
password = input("Enter the new password to save> ")
if new(user_password, name, password) == 0:
# Row added
print(f"[{GREEN_COLOR}+{NO_COLOR}] Successfully added...")
prompt(user_password)
else:
# ERROR
print(
f"[{RED_COLOR}-{NO_COLOR}] Error while writing the password..."
)
prompt(user_password)
elif cmd.lower() == 'delete':
id_num = input("Which id? > ")
confirm = input("Are you sure [Y/n]> ")
if confirm.lower() == 'y':
if delete(id_num) == 0:
# Row deleted
print(f"[{GREEN_COLOR}+{NO_COLOR}] Successfully deleted...")
else:
# ERROR
print(f"[{RED_COLOR}-{NO_COLOR}] Error in deleting...")
prompt(user_password)
elif cmd.lower() == 'show':
result = select_data(user_password)
if result == -1:
# ERROR
print(f"[{RED_COLOR}-{NO_COLOR}] Error in selecting the data...")
else:
show_data(result)
prompt(user_password)
elif cmd.lower() == 'exit':
print("Bye...")
sys.exit(0)
else:
print("Command not found...")
prompt(user_password)
def new(user_password, name, password, id_num=-1):
"""
This function used for inserting new row to the database.
It will return two values {0|-1},
0 means the row has inserted successfully,
-1 means there was an error.
parameters are (in sort) =>
===================================
user_password: The program password,
name: The tag of the new password,
password: The new password,
OPTIONAL id_num: Will be used for specific id number.
"""
try:
with sqlite3.connect(FILENAME) as conn:
cursor = conn.cursor()
if id_num == -1:
# insert id auto-increment
cursor.execute(
"""INSERT INTO passwords(name, password) VALUES (
?,?
);""",
[
encrypt(
str(user_password).encode('utf-8'),
str(name).encode('utf-8')
),
encrypt(
str(user_password).encode('utf-8'),
str(password).encode('utf-8')
)
]
)
else:
# insert the given id number
cursor.execute(
"""INSERT INTO passwords(id, name, password) VALUES (
?,?,?
);""",
[
id_num,
encrypt(
str(user_password).encode('utf-8'),
str(name).encode('utf-8')
),
encrypt(
str(user_password).encode('utf-8'),
str(password).encode('utf-8')
)
]
)
return 0
except Exception:
return -1
def delete(id_num):
"""
It gets an id number and will delete it from the database.
It will return two values {0|-1}
0 means the row has deleted successfully,
-1 means there was an error.
"""
try:
with sqlite3.connect(FILENAME) as conn:
cursor = conn.cursor()
cursor.execute(
"DELETE FROM passwords WHERE id = ? AND name != ?;",
[id_num, COOKIE]
)
return 0
except Exception:
return -1
def select_data(user_password):
"""
This function gets the program password (user_password)
and returns the passwords list.
returning -1 means there was an error
"""
try:
with sqlite3.connect(FILENAME) as conn:
cursor = conn.cursor()
# password => id, encrypted name and encrypted password
passwords = cursor.execute("SELECT * FROM passwords;").fetchall()
# result => id, decrypted name and decrypted password
result = []
for (id_num, name, password) in passwords:
result.append(
(
id_num,
decrypt(
str(user_password).encode('utf-8'), name
).decode('utf-8'),
decrypt(
str(user_password).encode('utf-8'), password
).decode('utf-8')
)
)
return result
except Exception:
return -1
def show_data(result):
"""
A function for printing the passwords.
It gets the password list.
"""
# the length of result must be more than 1
# because of the cookie row (0, ===PASSWORDS===, -)
if len(result) <= 1:
# Empty
print("\n\n====== Nothing ======\n\n")
else:
print("\n==============================\n")
for (id_num, name, password) in result:
if name != COOKIE:
print(f"({id_num}) {name} {GREEN_COLOR}{password}{NO_COLOR}")
print("\n==============================\n")
def encrypt(key, source, encode=True):
"""A function for encryption."""
# use SHA-256 over our key to get a proper-sized AES key
key = SHA256.new(key).digest()
# generate iv
iv = Random.new().read(AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC, iv)
# calculate needed padding
padding = AES.block_size - len(source) % AES.block_size
# Python 2.x: source += chr(padding) * padding
source += bytes([padding]) * padding
# store the iv at the beginning and encrypt
data = iv + encryptor.encrypt(source)
return base64.b64encode(data).decode("utf-8") if encode else data
def decrypt(key, source, decode=True):
"""A function for decrypting the encrypted datum."""
if decode:
source = base64.b64decode(source.encode("utf-8"))
# use SHA-256 over our key to get a proper-sized AES key
key = SHA256.new(key).digest()
# extract the IV from the beginning
IV = source[:AES.block_size]
decryptor = AES.new(key, AES.MODE_CBC, IV)
# decrypt
data = decryptor.decrypt(source[AES.block_size:])
# pick the padding value from the end; Python 2.x: ord(data[-1])
padding = data[-1]
if data[-padding:] != bytes([padding]) * padding:
raise ValueError("Invalid padding...")
# remove the padding
return data[:-padding]
def exit_program(sig, frame):
"""For handling SIGINT signal."""
print("\nBye...")
sys.exit(0)
if __name__ == '__main__':
global args # The program arguments
parser = argparse.ArgumentParser(description="Password Manager CLI")
# -p | --password PASSWORD
parser.add_argument(
'-p',
'--password',
metavar='password',
type=str,
default='',
help='the program password'
)
args = parser.parse_args()
# Handle SIGINT (same as ^C) signal
signal.signal(signal.SIGINT, exit_program)
main()
|
5a2adee92cdca9a14b16a2313f78ebdc7f709f22 | HuichuanLI/alogritme-interview | /Chapter03_LinkedList/้ข่ฏ้ข.py | 783 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
p1 = l1
p2 = l2
ov = 0
while p1 and p2:
p1.val += p2.val + ov
ov = p1.val // 10
p1.val = p1.val % 10
if not p1.next or not p2.next: break
p1 = p1.next
p2 = p2.next
if not p1.next and p2:
p1.next = p2.next
while p1.next and ov:
p1.next.val += ov
ov = p1.next.val // 10
p1.next.val = p1.next.val % 10
p1 = p1.next
if ov:
p1.next = ListNode(ov)
return l1
|
581b5c03d34f708a2e8efa2c8febd653e8b4faa5 | milenabaiao/python-1 | /area.py | 260 | 3.78125 | 4 | # -*- coding: utf-8 -*-
LadodoQuadrado = input("Digite o valor correspondente ao lado de um quadrado: ")
x = (float( 4 * int(LadodoQuadrado) ))
y = (float( int(LadodoQuadrado) * int(LadodoQuadrado) ))
print("perรญmetro: " + str(x) + " - รกrea: " + str(y))
|
ea623c32ea494085da420c41ad6634b416fa74c6 | greendar/ics4_2021 | /example.py | 1,315 | 3.8125 | 4 | class Vehicle:
def __init__(self, driver, colour, wheels):
self.driver = driver
self.wheels = wheels
self.colour = colour
self.name = 'vehicle'
self.horn = 'honk'
def __str__(self):
return f"{self.driver} is driving the {self.colour} {self.wheels} wheeled {self.name}."
def setColour(self, colour):
self.colour = colour
def honkHorn(self):
print(self.horn)
class Bike(Vehicle):
def __init__(self, driver, colour, wheels = 2):
self.driver = driver
self.wheels = wheels
self.colour = colour
self.name = 'bike'
self.horn = 'ring'
class Car(Vehicle):
def __init__(self, driver, colour, wheels = 4):
self.driver = driver
self.wheels = wheels
self.colour = colour
self.name = 'car'
self.passengers = 0
self.horn = 'beep'
def addPassengers(self, new):
self.passengers += new
class Truck(Vehicle):
def __init__(self, driver, colour, wheels = 4):
self.driver = driver
self.wheels = wheels
self.colour = colour
self.name = 'truck'
self.cargo = []
self.horn = 'awooga'
def addCargo(self, newCargo):
self.cargo.append(newCargo)
if __name__ == '__main__':
pass
|
854523995c3999b38f7531c0cc47f1cd9dc12903 | danielkouba/insertion_sort | /insertion_sort.py | 1,229 | 3.921875 | 4 | import random
from datetime import datetime
def randomNumArrayGen(max, length):
arr = []
for count in range(length):
arr.append(int(round(random.random()*max)))
return arr
# def insertionSort(arr):
# for i in range(0,len(arr)):
# # print i
# swap = "false"
# for n in reversed(range(0, i)):
# insertAt = i
# print "is", arr[i], "less than", arr[n]
# if arr[i] < arr[n]:
# print "Swap!"
# insertAt = n
# swap = "true"
# if swap == "true":
# #DONT SWAP PUSH IT BACK
# ins = arr[i]
# for count in range(insertAt, i+1):
# temp = arr[count]
# arr[count] = ins
# ins = temp
# print arr
# return arr
def insertionSort(arr):
for i in range(len(arr)):
tracker = 0
for n in reversed(range(0, i)):
print arr[i], "<", arr[n]
if arr[i] < arr[n]:
print "swap!"
tracker += 1
print arr
startPos = i
for k in reversed(range(tracker)):
(arr[startPos-1], arr[startPos]) = (arr[startPos],arr[startPos-1])
startPos-=1
return arr
now1 = datetime.now().microsecond
# print insertionSort([2, 6, 9, 9, 7, 7, 7, 3, 2, 10])
print insertionSort(randomNumArrayGen(1000000, 100))
now2 = datetime.now().microsecond
print(str(now2 - now1) + " microseconds")
|
a5af0827cf75d9ef163ec338bac4184d0130bba4 | CharisseU/CodingDojo_Assignments | /Python_Stack/Fundamentals/insertionSort.py | 383 | 4.03125 | 4 | #Python Insertion Sort
import sys
list = [99, 88, 77, 66, 55, 44, 33, 22, 11]
def insertionSort(list):
for i in range(1, len(list)):
key = list[i]
j = i-1
while j>=0 and key < list[j]:
list[j+1] = list[j]
j-=1
list[j+1] = key
insertionSort(list)
print ("Sorted array is: ")
for i in range(len(list)):
print (list[i])
|
f4953322f6511c8329c0342473800489e42b9ccb | IronE-G-G/algorithm | /ๅๆoffer/65hasPath.py | 1,745 | 3.671875 | 4 | # -*- coding:utf-8 -*-
"""
็ฉ้ตไธญ็่ทฏๅพ๏ผ่ฏท่ฎพ่ฎกไธไธชๅฝๆฐ๏ผ็จๆฅๅคๆญๅจไธไธช็ฉ้ตไธญๆฏๅฆๅญๅจไธๆกๅ
ๅซๆๅญ็ฌฆไธฒๆๆๅญ็ฌฆ็่ทฏๅพใ
่ทฏๅพๅฏไปฅไป็ฉ้ตไธญ็ไปปๆไธไธชๆ ผๅญๅผๅง๏ผๆฏไธๆญฅๅฏไปฅๅจ็ฉ้ตไธญๅๅทฆ๏ผๅๅณ๏ผๅไธ๏ผๅไธ็งปๅจไธไธชๆ ผๅญใ
ๅฆๆไธๆก่ทฏๅพ็ป่ฟไบ็ฉ้ตไธญ็ๆไธไธชๆ ผๅญ๏ผๅ่ฏฅ่ทฏๅพไธ่ฝๅ่ฟๅ
ฅ่ฏฅๆ ผๅญใ
ไพๅฆ a b c e s f c s a d e e ็ฉ้ตไธญๅ
ๅซไธๆกๅญ็ฌฆไธฒ"bcced"็่ทฏๅพ๏ผไฝๆฏ็ฉ้ตไธญไธๅ
ๅซ"abcb"่ทฏๅพ๏ผ
ๅ ไธบๅญ็ฌฆไธฒ็็ฌฌไธไธชๅญ็ฌฆbๅ ๆฎไบ็ฉ้ตไธญ็็ฌฌไธ่ก็ฌฌไบไธชๆ ผๅญไนๅ๏ผ่ทฏๅพไธ่ฝๅๆฌก่ฟๅ
ฅ่ฏฅๆ ผๅญใ
ๆ่ทฏ๏ผ้ๅๆพๅฐpath็็ฌฌไธไธชๅ
็ด ๏ผ่ฟๅ
ฅๅคๆญๆจกๅผใ
"""
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
self.matrix = matrix
self.rows = rows
self.cols = cols
self.path = path
self.length = rows * cols
for ind, item in enumerate(matrix):
if item == path[0] and self.judge(ind, path[1:], [ind]):
return True
return False
def judge(self, ind, path, flagSet):
if not path:
return True
# left
left = ind - 1
right = ind + 1
up = ind - self.cols
down = ind + self.cols
# ๅฆๆไธไธๅทฆๅณไธญๆๅ
็ด ๆปก่ถณๆกไปถ๏ผ็ญไบpath็ๅคดไธชๅ
็ด ๅนถไธๅไฝๆฒก่ขซๅ ๏ผ๏ผ้ๅฝ่ฟๅ
ฅ่ฏฅๅ
็ด judgeไธไธไธช
for item in [left, right, up, down]:
if 0 <= item < self.length and item not in flagSet and self.matrix[item] == path[0]:
res = self.judge(item, path[1:], flagSet + [item])
if res:
return True
return False
|
41d38ae411820a57aa0d3813f87d5b5ceb4cbd08 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q11_numero.py | 627 | 3.953125 | 4 | def main():
num1 = int(input('Digite o primeiro nรบmero: '))
num2 = int(input('Digite o segundo nรบmero: '))
num3 = int(input('Digite o terceiro nรบmero: '))
opcao = int(input('Selecione a sua opรงรฃo (1, 2 ou 3): '))
verificar_opcao(opcao, num1, num2, num3)
def verificar_opcao(opcao, num1, num2, num3):
if opcao == 1:
print(f'O numero escolhido foi {num1}.')
elif opcao == 2:
print(f'O numero escolhido foi {num2}.')
elif opcao == 3:
print(f'O numero escolhido foi {num3}.')
else:
print('Vocรช nรฃo selecionou uma opรงรฃo vรกlida.')
main()
|
f0a6403cbe75047b544c3c239894b954e5f6e89c | bbansalaman0/ML | /Python Learning/ass/as 4.6.py | 238 | 3.84375 | 4 | def computepay(h,r):
if h>40:
pay=h*r+((h-40)*(r*0.5))
else:
pay=h*r
return pay
hours=input('enter hours:')
rate=input('enter rate:')
h=float(hours)
r=float(rate)
tp=computepay(h,r)
print('Pay',tp)
|
7029b058fc45a4613620c28eb22fcc1f038d5d66 | tacores/algo-box-py | /strings/suffix_tree.py | 3,887 | 3.71875 | 4 | # python3
import sys
# $ใง็ตใใๆๅญๅใฎ้จๅๆๅญๅใฎใใใฉใคใใชใผๆง็ฏ(Compressed)
class Node:
def __init__ (self, index, length, node_no):
# ้จๅๆๅญๅใไฟๆใใไปฃใใใซใtextๅ
ใฎไฝ็ฝฎใจ้ทใใไฟๆใใ
self.index = index
self.length = length
self.node_no = node_no
def build_suffix_tree(text):
"""
Build a suffix tree of the string text and return a list
with all of the labels of its edges (the corresponding
substrings of the text) in any order.
"""
tree = dict()
tree[0] = {}
head_node = 1
# ไพใใฐใABC$ ใจใใๆๅญๅใฎๅ ดๅใABC$, BC$, C$, $ ใฎ้ ใซๅฆ็
for p in range(len(text)):
suffix = text[p:]
current_node = 0
# ใตใๆๅญๅใฎๅ
้ ญใใไธๆๅญใใคๅฆ็
i = 0
while i < len(suffix):
c = suffix[i]
cur_str = suffix[i:]
idx_on_suffix = i
#print(suffix, cur_str)
# ็พๅจใฎใใผใใใใc ใงๅงใพใใจใใธใๅบใฆใใ
if c in tree[current_node]:
next_node = tree[current_node][c]
next_str = text[next_node.index : next_node.index + next_node.length]
next_len = len(next_str)
cur_len = len(cur_str)
compare_len = min(next_len, cur_len)
for u in range(compare_len):
# ๆขๅญใฎใจใใธใจ๏ผๆๅญใไธ่ด
if next_str[u] == cur_str[u]:
if u != 0: # 0ใฎๅใฏ for ใงใคใณใฏใชใกใณใใใใใฎใง
# ๏ผๆๅญ้ฒใ
i = i + 1
if u == next_len - 1:
# ๆฌกใฎใใผใใจใฎๆฏ่ผใซ้ฒใ
current_node = next_node.node_no
else:
# โ ๆขๅญใฎใจใใธใๅๅฒใใใใผใใ่ฟฝๅ
new_node = Node(next_node.index, u, head_node)
cur_node = tree[current_node][c]
tree[current_node][c] = new_node
print_nodechange(current_node, c, new_node)
# โกใโ ใงไฝๆใใใใผใใจๆขๅญใฎใใผใใ้ฃ็ต
if head_node not in tree:
tree[head_node] = {}
next_node.index = next_node.index + u
next_node.length = next_node.length - u
tree[head_node][next_str[u]] = next_node
print_nodechange(head_node, next_str[u], next_node)
current_node = head_node
head_node = head_node + 1
# โขใโ ใใๅๅฒใใใใผใใ่ฟฝๅ
if cur_len > u:
if head_node not in tree:
tree[head_node] = {}
new_node = Node(p + idx_on_suffix + u, cur_len - u, head_node)
tree[current_node][text[p + idx_on_suffix + u]] = new_node
print_nodechange(current_node, text[p + idx_on_suffix + u], new_node)
current_node = head_node
head_node = head_node + 1
i = len(suffix) #whileใซใผใใใๅบใใใใซ
break
# ็พๅจใฎใใผใใใใc ใงๅงใพใใจใใธใๅบใฆใใชใ
else:
# ๅ็ดใซใใผใใ่ฟฝๅ
new_node = Node(p + i, len(suffix) - i, head_node)
tree[current_node][c] = new_node
print_nodechange(current_node, c, new_node)
current_node = head_node
head_node = head_node + 1
break
i = i + 1
result = []
#print("*******************")
for i in tree:
for j in tree[i]:
node = tree[i][j]
print_nodechange(i, j, node)
next_str = text[node.index : node.index + node.length]
result.append(next_str)
#print("*******************")
return result
def print_nodechange(i, j, node):
pass
#print(node.node_no, text[node.index : node.index + node.length], i, j)
if __name__ == '__main__':
text = sys.stdin.readline().strip()
result = build_suffix_tree(text)
print("\n".join(result)) |
b1a2365c9c26db6bc0702c5ecf7537c5fc9dfeae | ashleyabrooks/code-challenges | /polish_calculator.py | 1,144 | 4.25 | 4 | """Calculator
>>> calc("+ 1 2") # 1 + 2
3
>>> calc("* 2 + 1 2") # 2 * (1 + 2)
6
>>> calc("+ 9 * 2 3") # 9 + (2 * 3)
15
Let's make sure we have non-commutative operators working:
>>> calc("- 1 2") # 1 - 2
-1
>>> calc("- 9 * 2 3") # 9 - (2 * 3)
3
>>> calc("/ 6 - 4 2") # 6 / (4 - 2)
3
"""
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num21
def calc(s):
"""Evaluate expression."""
stack = s.split()
num2 = int(stack.pop())
while stack:
num1 = int(stack.pop())
operator = stack.pop()
if operator == '+':
num2 = num1 + num2
elif operator == '-':
num2 = num1 - num2
elif operator == '*':
num2 = num1 * num2
elif operator == '/':
num2 = num1 / num2
return num2
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. ***\n"
|
688863f73015eb6a245ea159de1a9a7842e44173 | SocratesGuerrero/ejemplo | /sentencias/sentencias_FOR.py | 333 | 3.90625 | 4 | """ Bucle FOR """
# Opera sobre una secuencia establecida
# Sin tipos de datos ni incrementos
#! /usr/bin
lista = ["uno", "dos", "tres", "cuatro", "cinco", "seis"]
for elemento in lista:
print elemento
if elemento=="tres":
print "soy un tres"
for var in range(2,13,1): #Valor inicial, final, incremento
print var
|
5d4b7567369c376ad733855a955d1b2ed80f0597 | Sona1414/luminarpython | /object oriented programming/concs and inheritance.py | 292 | 3.71875 | 4 | class Person:
def __init__(self,name,age):
self.name=name
self.age=age
class Student(Person):
def __init__(self,rollno,name,age):
super().__init__(name,age)
self.rollno=rollno
print(self.name,self.age,self.rollno)
stu=Student(101,"SONA",15)
|
1ebaf6f862173cf65c47fde5d434b97768ed2a60 | JamesP2/adventofcode-2020 | /day/2/day2-2.py | 994 | 3.796875 | 4 | import sys
import re
valid_passwords = 0
with open(sys.argv[1]) as file:
for line in file:
# Almost did line[:-2] but then the last line would be too short
line = line.replace('\n', '')
# Split line into [minimum, maximum, char, password]
first_index, second_index, char, password = re.split(
'-| |: ', line)
first_index = int(first_index) - 1
second_index = int(second_index) - 1
valid = True if (password[first_index] == char and password[second_index] != char) or (
password[first_index] != char and password[second_index] == char) else False
print('Looking for {} in password {}. Char {} = {}, Char {} = {}, {}'.format(
char, password, first_index, password[first_index], second_index, password[second_index], 'Valid' if valid else 'Not Valid!'))
if valid:
valid_passwords += 1
print('There are {} valid passwords in the data set.'.format(valid_passwords))
|
79aeb79b410fbe90bd1e427c4c4aaa3b53824573 | Esubalew24/Python | /Dictionary.py | 332 | 3.984375 | 4 | l = [1,"heh",2]
m = "Hello"
print l[1]
my_dict = {"key1": "value1", "key2" : "value2", "key3": 123}
my_dict2 = ["Value1", "Value2", 123]
print my_dict["key1"][::-1].upper()
print my_dict2[0][::-1].upper()
print m.upper()
print m.lower()
n = m.upper()
print n.capitalize()
print my_dict["key1"] + " hekk"
print my_dict["key3"] + 22 |
aff5efbfb08792b7db28d3ea384abead801922e5 | lszloz/Python_apps | /python_net/TCP/tcp_server.py | 904 | 3.796875 | 4 | """
TCPๅฅๆฅๅญๆๅก็ซฏ
"""
import socket
# ๅๅปบๆตๅผๅฅๆฅๅญ
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# ใ็ปๅฎๆฌๆบๅฐๅ
sockfd.bind(('127.0.0.1', 8888))
# sockfd.bind(('localhost', 8888))
# sockfd.bind(('0.0.0.0', 8888))
# ใ็ๅฌ๏ผ่ฎพ็ฝฎๆๅค่ฟๆฅๆฐ้
sockfd.listen(5)
# ใ็ญๅพ
ๅค็ๅฎขๆท็ซฏ้พๆฅ
while True:
print("Waiting for connect....")
try:
connfd, addr = sockfd.accept()
print("Connect from:", addr)
except KeyboardInterrupt:
print("้ๅบๆๅก")
break
# ๆถๅๆถๆฏ
while True:
data = connfd.recv(1024)
# ใๅพๅฐ็ฉบๅ้ๅบๅพช็ฏ
if not data:
break
print("ๆฅๆถๅฐ็ๆถๆฏ:", data.decode())
n = connfd.send(b'Receive your message')
print("ๅ้ไบ %d ไธชๅญ่ๆฐๆฎ" % n)
connfd.close()
# ๅ
ณ้ญๅฅๆฅๅญ
sockfd.close()
|
05f04f36611d827eb52aa114da9166f3f5f5bb61 | josepforadada/DA-prework | /Duel_of_sorcerers.py | 8,604 | 4.0625 | 4 | print("\nDUEL OF SORCERERS\n")
print("You are witnessing an epic battle between two powerful sorcerers.")
print("Gandalf and Saruman. Each sorcerer has 10 spells of variable power")
print("in their mind and they are going to throw them one after the other.")
print("The winner of the duel will be the one who wins more of those")
print("clashes between spells. Spells are represented as a list of 10")
print("integers whose equals the power of the spell.\n")
print("Gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]")
print("Saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]\n")
print("For example:\n")
print("You will create two variables, one for each sorcerer, where the")
print("sum of clashes won will be stored. Depending on which variable is")
print("greater at the end of the duel, you will show one of the following")
print("three results on the screen:\n")
print("\t - Gandalf wins")
print("\t - Saruman wins")
print("\t - Tie\n")
clash_list = []
Num_of_clashes = 0
Round_of_clashes = 0
Gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
Saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]
Name_of_round = {
0: "First",
1: "Second",
2: "Third",
3: "Fouth",
4: "Fifth",
5: "Sixth",
6: "Seventh",
7: "Eigth",
8: "Ninth",
9: "Tenth"
}
sorcerer = "Saruman"
gandalf_wins = 0
saruman_wins = 0
draws = 0
total_clashes = 10
print("The battle starts...\n")
import random
if len(Gandalf) != len(Saruman):
print("Any of the sorcerers has more attacks!!")
print("We are going to remove attacks randomly to match the number of attacks with the lesser.")
if len(Gandalf) <= len(Saruman):
times = len(Saruman) - len(Gandalf)
count = 0
while count < times:
new_length = (len(Saruman))
random_num = random.randint(1, len(Saruman)-1)
print(random_num)
Saruman.pop(random_num)
count += 1
else:
times = len(Gandalf) - len(Saruman)
count = 0
while count < times:
random_num = random.randint(0, len(Gandalf)-1)
print(random_num)
Gandalf.pop(random_num)
count += 1
number_round = 0
total_clashes = len(Saruman)
while number_round < total_clashes:
if Gandalf[number_round] == Saruman[number_round]:
draws = draws + 1
elif Gandalf[number_round] < Saruman[number_round]:
saruman_wins = saruman_wins + 1
else:
gandalf_wins = gandalf_wins + 1
number_round += 1
round_val = 0
while round_val < len(Saruman):
if Gandalf[round_val] == Saruman[round_val]:
print(" - The %s round was a draw!" % Name_of_round[round_val])
elif Gandalf[round_val] < Saruman[round_val]:
print(" - The winner of the %s round is Saruman" % Name_of_round[round_val].lower())
else:
print(" - The winner of the %s round is Gandalf" % Name_of_round[round_val].lower())
round_val = round_val + 1
print("\nThe final result is Gandalf %d of %d battles - Saruman %d of %d battles." % (gandalf_wins, total_clashes, saruman_wins, total_clashes))
if saruman_wins < gandalf_wins:
print("\nGandalf wins the battle!")
elif saruman_wins > gandalf_wins:
print("\nSaruman wins the battle!")
else:
print("\nThe battle ends with an epic draw!")
print("\n\nDUEL OF SORCERERS - BONUS\n")
print("1 - Spells now have a name and there is a dictionary that relates")
print(" that name to a power.")
print("2 - A sorcerer wins if he succeeds in winning 3 spell clashes in a row")
print("3 - Average of the spells lists.")
print("4 - Standard deviation of each of the spells lists.")
power = {
"Fireball": 50,
"Lighting bolt": 40,
"Magic arrow": 10,
"Black tentacles": 25,
"Contagion": 45
}
gandalf_spells = [
"Fireball",
"Lighting bolt",
"Lighting bolt",
"Magic arrow",
"Fireball",
"Magic arrow",
"Lighting bolt",
"Fireball",
"Magic arrow",
"Fireball"
]
saruman_spells = [
"Contagion",
"Contagion",
"Black tentacles",
"Fireball",
"Black tentacles",
"Lighting bolt",
"Magic arrow",
"Contagion",
"Magic arrow",
"Magic arrow"
]
who_attacks = 0
random_words_attack = ["attacks with a ", "uses a ", "utilizes a ", "charges with a ", "shoots a "]
random_words_defense = ["refuse it with a ", "stops it with a ", "uses a ", "attacks with a "]
random_interjections = [", ", " and ", " but ", " at the same time ", ". ", " while "]
print("\nThe battle starts...\n")
import random
Round_of_clashes = 0
Total_of__clashes = len(saruman_spells)
saruman_score = 0
gandalf_score = 0
saruman_total_score = 0
gandalf_total_score = 0
total_draws = 0
while saruman_score < 3 and gandalf_score < 3 and Round_of_clashes < Total_of__clashes:
who_attacks = random.randint(0, 1)
random_word1 = random.randint(0, len(random_words_attack)-1)
random_word2 = random.randint(0, len(random_words_defense)-1)
random_word3 = random.randint(0, len(random_interjections)-1)
if Round_of_clashes < 9:
spell_round = "0" + str(Round_of_clashes + 1)
else:
spell_round = str(Round_of_clashes + 1)
if who_attacks == 0:
attacker = ["Gandalf ", gandalf_spells]
defender = ["Saruman ", saruman_spells]
print(" %s - %s%s%s%s%s%s%s" % (spell_round, attacker[0], random_words_attack[random_word1], attacker[1][Round_of_clashes], random_interjections[random.randint(0, len(random_interjections)-1)], defender[0],random_words_defense[random_word2], defender[1][Round_of_clashes]))
if power[attacker[1][Round_of_clashes]] > power[defender[1][Round_of_clashes]]:
gandalf_score += 1
gandalf_total_score += 1
saruman_score = 0
elif power[attacker[1][Round_of_clashes]] < power[defender[1][Round_of_clashes]]:
gandalf_score = 0
saruman_score += 1
saruman_total_score +=1
else:
print("\t What a draw!")
gandalf_score = 0
saruman_score = 0
total_draws += 1
else:
attacker = ["Saruman ", saruman_spells]
defender = ["Gandalf ", gandalf_spells]
print(" %s - %s%s%s%s%s%s%s" % (spell_round, attacker[0], random_words_attack[random_word1], attacker[1][Round_of_clashes], random_interjections[random_word3], defender[0],random_words_defense[random_word2], defender[1][Round_of_clashes]))
if power[attacker[1][Round_of_clashes]] > power[defender[1][Round_of_clashes]]:
gandalf_score = 0
saruman_score += 1
saruman_total_score += 1
elif power[attacker[1][Round_of_clashes]] < power[defender[1][Round_of_clashes]]:
gandalf_score += 1
gandalf_total_score += 1
saruman_score = 0
else:
print("\t What a draw!")
gandalf_score = 0
saruman_score = 0
total_draws += 1
Round_of_clashes += 1
print("\n\nThe final result of the competition is:")
print("\n\t- Gandalf total wins: %d" % gandalf_total_score)
print("\t- Saruman total wins: %d" % saruman_total_score)
print("\t- Total draws: %d" % total_draws)
if gandalf_total_score > saruman_total_score:
print("\n\t THE WINNER OF THE BATTLE IS GANDALF")
elif gandalf_total_score < saruman_total_score:
print("THE WINNER OF THE BATTLE IS SARUMAN")
else:
print("THE FINAL RESULT IS A DRAW. WHAT A BATTLE, AMAZING DUEL!!")
print("\n\nAfter this apotheosic battle we have analyzed that:")
saruman_array = []
gandalf_array = []
saruman_array2 = []
gandalf_array2 = []
SD_saruman = 0
SD_gandalf = 0
for spell in saruman_spells:
name_spell = spell
saruman_array.append(power[name_spell])
for spell in gandalf_spells:
name_spell = spell
gandalf_array.append(power[name_spell])
average_saruman = sum(saruman_array)/len(saruman_spells)
average_gandalf = sum(gandalf_array)/len(gandalf_spells)
import math
for spells in range(len(saruman_spells)):
saruman_array[spells] = math.pow(saruman_array[spells] - average_saruman, 2)
SD_saruman = math.sqrt(sum(saruman_array) / len(saruman_spells))
for spells in range(len(gandalf_spells)):
gandalf_array[spells] = math.pow(gandalf_array[spells] - average_gandalf, 2)
SD_gandalf = math.sqrt(sum(gandalf_array)/len(gandalf_spells))
print("\nSrumnan's average spells is a %s power" % average_saruman)
print("Gandalf's average spells is a %s power" % average_gandalf)
print("Saruman's standard deviation is: %.2f" % SD_saruman)
print("Gandalf's standard deviation is: %.2f" % SD_gandalf)
|
cd37ec7f3c0b794e5dfde334e335b21934207ee4 | SJeliazkova/SoftUni | /Programming-Basic-Python/Exercises-and-Labs/Loops_Part_2_Lab/06. Max Number.py | 184 | 3.640625 | 4 | import sys
n = int(input())
counter = 0
max_num = - sys.maxsize
while counter < n:
num = int(input())
if num > max_num:
max_num = num
counter += 1
print(max_num) |
15ba9597f6fcf309c0270479473731d6805416ca | GANESH0080/Python-Practice-Again | /ElseInForLoop/ExampleOne.py | 61 | 3.65625 | 4 | for x in "banana":
print(x)
else :
print("Hi Ganesh") |
06ad43a4e1f10a849401235656ab1aa830f7634e | harikakosuri/Height-And-Weight-Prediction-With-ML-Algorithm | /org_wt_ht.py | 3,078 | 3.578125 | 4 | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
data = pd.read_csv('wt_ht-220.csv')
#Machine Learning
#Female Prediction
### Female Weight prediction
#replaceing the data from data variable to df
df = pd.DataFrame(data)
X1 = df.iloc[:,0:1] #feactuers
Y1 = df.iloc[:,1] #labels
#X_train.shape
#Y_train.shape
#X=Gender & height
#Y=weight
#Split the train and test data
from sklearn.model_selection import train_test_split
X1_train, X1_test, Y1_train, Y1_test = train_test_split(X1,Y1,test_size = 1/3, random_state=1)
#Training the with linear Regression
from sklearn.linear_model import LinearRegression
fe_wt=LinearRegression()
fe_wt.fit(X1_train,Y1_train)
##Prediciting results
fe_wt_pred=fe_wt.predict(X1_train)
fe_wt.predict([[167]])
#saving model with help pickle
import pickle
pickle.dump(fe_wt,open("female_wt_pred.pkl","wb"))
##Female Height Prediction
X2 = df.iloc[:,-2:-1] #feactuers
Y2 = df.iloc[:,0]
#X2
#Y2
#Female
#X= Female weight
#Y= Felmale height
#Split the train and test data
from sklearn.model_selection import train_test_split
X2_train, X2_test, Y2_train, Y2_test = train_test_split(X2,Y2,test_size = 1/3, random_state=1)
#Training the with linear Regression
from sklearn.linear_model import LinearRegression
fe_ht=LinearRegression()
fe_ht.fit(X2_train,Y2_train)
#Predict value in train set
fe_ht_pred=fe_ht.predict(X2_train)
fe_ht.predict([[59]])
#saving model with pickle
import pickle
pickle.dump(fe_ht,open("female_ht_pred.pkl","wb"))
#Male Prediction
## Male Weight Prediction
X3 = df.iloc[:,0:1] #feactuers
Y3 = df.iloc[:,2] #labels
#X=Gender & height
#Y=weight
#X3
#Y3
#Split the train and test data
from sklearn.model_selection import train_test_split
X3_train, X3_test, Y3_train, Y3_test = train_test_split(X3,Y3,test_size = 1/3, random_state=1)
#Training the with linear Regression
from sklearn.linear_model import LinearRegression
ma_wt=LinearRegression()
ma_wt.fit(X3_train,Y3_train)
#Split the train and test data
from sklearn.model_selection import train_test_split
X3_train, X3_test, Y3_train, Y3_test = train_test_split(X3,Y3,test_size = 1/3, random_state=1)
#Training the with linear Regression
from sklearn.linear_model import LinearRegression
ma_wt=LinearRegression()
ma_wt.fit(X3_train,Y3_train)
#saving model with help pickle
import pickle
pickle.dump(ma_wt,open("male_wt_pred.pkl","wb"))
##Male Height Prediction
X4 = df.iloc[:,2:3] #feactuers
Y4 = df.iloc[:,0] #labels
#X=Male weight
#Y=height
#X4
#Y4
#Male
#X= Male weight
#Y= Male height
#Split the train and test data
from sklearn.model_selection import train_test_split
X4_train, X4_test, Y4_train, Y4_test = train_test_split(X4,Y4,test_size = 1/3, random_state=1)
#Training the with linear Regression
from sklearn.linear_model import LinearRegression
ma_ht=LinearRegression()
ma_ht.fit(X4_train,Y4_train)
#Predicting the train set
ma_ht_pred=ma_ht.predict(X2_train)
ma_ht.predict([[59]])
#saving model with help pickle
import pickle
pickle.dump(ma_ht,open("male_ht_pred.pkl","wb")) |
e3d4584b27dbe9927f39385fc9c1f16ae49011d2 | FilipLangr/ub201617_delta | /euler_path_all_paths.py | 8,344 | 3.6875 | 4 | from collections import defaultdict
import copy
class Graph:
"""
Graph represented as a dict.
Keys: kmers (string).
Values: List of neighbouring kmers (string).
"""
def __init__(self):
"""
Construct a sensible empty graph. self.indeg is technically not needed, but is a useful syntactic sugar.
"""
self.graph = defaultdict(list)
self.indeg = defaultdict(lambda: 0)
self.outdeg = defaultdict(lambda: 0)
def add_arrow(self, src, dest):
"""
Adds an arrow from node src to node dest to the graph.
"""
self.graph[src].append(dest)
self.outdeg[src] += 1
self.indeg[dest] += 1
def find_beginning(self):
"""
Find the node to begin searching for Euler path with.
TODO Terrible complexity, would be nice to remember starting node when creating the graph
and just give it as an argument.
"""
return_node = None
for node in self.graph:
return_node = node
# If out > into, we should begin with that node.
if self.outdeg[node] > self.indeg[node]:
return return_node
# All nodes have even degree, the graph is Euler cycle, first node can be whatever node.
return return_node
def __str__(self):
return 30*"=" + "\nGraph:\n" + "\n".join(str(item) + " (>%d, %d>)" % (self.indeg[item], self.outdeg[item]) + ": " + " ".join(str(item) for item in euler_graph.graph[item]) for item in euler_graph.graph) + "\n" + 30*"="
def get_kmers(sequence, k, d=1):
for i in range(0, len(sequence) - (k - 1), d):
yield sequence[i:i+k]
def get_graph(sequence, k):
g = Graph()
kmers = get_kmers(sequence, k)
for kmer in kmers:
#we add nodes (k-1 mer) and edge in graph : n1 -> n2
n1 = kmer[:-1]
n2 = kmer[1:]
g.add_arrow(n1, n2)
return g
def get_paired_kmers(sequence, k, d):
for i in range(0, len(sequence) - 2 * k - d + 1):
yield (sequence[i:i+k], sequence[i+k+d:i+2*k+d])
def get_paired_graph(sequence, k, d):
g = Graph()
pairs = get_paired_kmers(sequence, k, d)
for pair in pairs:
n1 = (pair[0][:-1], pair[1][:-1])
n2 = (pair[0][1:], pair[1][1:])
g.add_arrow(n1, n2)
return g
def find_sequence(euler_graph):
# Init stack of visited nodes and reconstructed sequence.
stack = []
path = []
# Find the first node to start with.
node = euler_graph.find_beginning()
pths = euler_path(euler_graph, stack, path, node)
return pths
def euler_path(euler_graph, stack, path, node):
""" Find all paths in given Euler graph. """
all_pathes = set()
while True:
if not euler_graph.graph[node]:
# No more edges going from this node.
# Append the sequence with the node.
path.append(node)
if not stack:
# We went through the whole graph.
all_pathes.add(tuple(path))
break
# Take a node from the stack.
node = stack.pop()
else:
# Add node to the stack.
stack.append(node)
# Go recursively through all node's neighbours.
for nn in euler_graph.graph[node]:
tmp = copy.deepcopy(euler_graph)
tmp.graph[node].remove(nn)
set_of_pathes = euler_path(tmp, stack.copy(), path.copy(), nn)
all_pathes = all_pathes.union(set_of_pathes)
break
return all_pathes
def gap_reconstruction(prefix_string, suffix_string, k, d):
for i in range(k+d+1,len(prefix_string)):
if prefix_string[i] != suffix_string[i-k-d]:
return None
return prefix_string + suffix_string[-(k+d):] ##prefix_string concatenated with the last k+d symbols of suffix_string
def render_path_single(path):
"""
Generate a reconstructed genome based on the given Eulerian path (reversed) of (k-1)-mer nodes.
"""
#print("path: ", path[::-1])
return ("".join(map(lambda x: x[-1], path)) + path[-1][-2::-1])[::-1]
def render_path_paired(path, k, d):
"""
Generate a reconstructed genome based on the given Eulerian path (reversed) of (k, d)-mer nodes.
TODO this doesn't seem to really work, gapReconstruction above will return None
"""
path = path[::-1]
prefix = path[0][0] + "".join(map(lambda x: x[0][-1], path[1:]))
suffix = path[0][1] + "".join(map(lambda x: x[1][-1], path[1:]))
return gap_reconstruction(prefix, suffix, k, d)
def load_fasta(file_handle):
string = ""
line = file_handle.readline()
if not line or line[0] != ">": return None
while True:
line = file_handle.readline()
if not line or line[0] == ">": break
line = line.strip()
if not line or line[0] == ";": continue
string += line.strip()
return string
def test_single_graph(genome_sequence):
"""
Testing fuction for finding smallest parameter k so that genome sequence is still reconstructed correctly.
"""
k = 18
while True:
euler_graph = get_graph(genome_sequence, k)
# Find sequence (Euler path) in the graph.
sequence = find_sequence(euler_graph)
seqs = [render_path_single(se) for se in sequence]
if genome_sequence in seqs:
print("Smallest possible k for single de Brujin graph: %d, Genome size: %d" % (k ,len(genome_sequence)))
break
k +=1
def test_paired_graph(genome_sequence):
"""
Testing fuction for finding smallest parameters k and d so that genome sequence is still reconstructed correctly.
"""
for d in range(2238, 2238 + 1, 1):
k = 8
#print("d: %d k: %d" % (d, k))
while True:
#if d > 10: break
euler_graph = get_paired_graph(genome_sequence, k, d)
# Find sequence (Euler path) in the graph.
print("here I am")
sequence = find_sequence(euler_graph)
print("here I am 2")
seqs = [render_path_paired(se, k, d) for se in sequence]
if genome_sequence in seqs:
print("Smallest possible k for paired de Brujin graph: %d, d: %d, Genome size: %d" % (k, d, len(genome_sequence)))
break
#k += 1
break
if __name__ == "__main__":
# Create graph.
#euler_graph = get_graph("TAATGCCATGGGATGTT", 3)
euler_graph = get_graph("TAATGCCATGGGATGTT", 3)
#print(euler_graph)
# Find sequence (Euler path) in the graph.
ind = 1
sequence = find_sequence(euler_graph)
for q in sequence:
print("Found sequence num. %d: %s" % (ind, render_path_single(q)))
ind += 1
print("Desired sequence: TAATGCCATGGGATGTT" )
print("\n\n\nPAIRED GRAPH:")
# Create graph.
euler_graph = get_paired_graph("TAATGCCATGGGATGTT", 3, 1)
#print(euler_graph)
# Find sequence (Euler path) in the graph.
ind = 1
sequence = find_sequence(euler_graph)
for q in sequence:
print("Found sequence num. %d: %s" % (ind, render_path_paired(q, 3, 1)))
ind += 1
print("Desired sequence: TAATGCCATGGGATGTT" )
#"""
# Try processing an input file.
from sys import argv, stdin
if len(argv) < 2 or argv[1] == "-":
file_handle = stdin
else:
file_handle = open(argv[1], "r")
fasta = load_fasta(file_handle)
euler_graph = get_graph(fasta, 3)
#print("Found sequence: %s" % (render_path_single(euler_path(euler_graph))))
#print("Desired sequence: %s" % (fasta))
#3 genome files in FASTA format must be put in the argument line ---> genome_40k genome_100k genome_180k
for filename in argv[1:]:
file_handle = open(filename, "r")
genome_sequence = load_fasta(file_handle)
#test_single_graph(genome_sequence)
test_paired_graph(genome_sequence)
#""" |
381ca2ab14542e2a88fe3a9dab75f28fb4d82373 | roadfoodr/exercism | /python/submitted/difference_of_squares.py | 610 | 4.1875 | 4 | def square_of_sum(number):
# https://en.wikipedia.org/wiki/Triangular_number
return round((number * (number+1) / 2) ** 2)
def sum_of_squares(number):
# https://en.wikipedia.org/wiki/Square_pyramidal_number
return round((number**3 / 3) + (number**2 / 2) + (number / 6))
def difference_of_squares(number):
'''
Find the difference between the square of the sum and the sum of the
squares of the first N natural numbers.
'''
if number < 0:
raise ValueError(f'number {number} may not be negative.')
return square_of_sum(number) - sum_of_squares(number)
|
3af6b8da88848208cfd1b61464ec76f8fc478581 | benbendaisy/CommunicationCodes | /python_module/examples/443_String_Compression.py | 2,050 | 4.125 | 4 | from typing import List
class Solution:
"""
Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
If the group's length is 1, append the character to s.
Otherwise, append the character followed by the group's length.
The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.
After you are done modifying the input array, return the new length of the array.
You must write an algorithm that uses only constant extra space.
Example 1:
Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
Example 2:
Input: chars = ["a"]
Output: Return 1, and the first character of the input array should be: ["a"]
Explanation: The only group is "a", which remains uncompressed since it's a single character.
Example 3:
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
"""
def compress(self, chars: List[str]) -> int:
if not chars:
return 0
idx, n = 0, len(chars)
res = ""
while idx < n:
char_cnt = 1
while idx + 1 < n and chars[idx] == chars[idx + 1]:
char_cnt += 1
idx += 1
res += chars[idx] + str(char_cnt) if char_cnt > 1 else chars[idx]
idx += 1
for i in range(res):
chars[i] = res[i]
return len(res) |
907d7d476130c6340db91b8123426b92d83d47b7 | thesinbio/RepoUNLa | /Seminario de Lenguajes/Prรกctica/01.programarcadegames/Prรกctica03.py | 995 | 3.921875 | 4 | print("Tu nueva puntuaciรณn es ",1030 + 10)
print("Quiero imprimir comillas dobles \" por alguna razรณn.")
print("El archivo estรก guardado en C:\\nueva carpeta")
# Esto es un comentario que comienza con el signo # y
# y el compilador lo ignorarรก.
print("Hola") # Esto es un comentario al final de una lรญnea
'''
comentario
docstrings
'''
print("Hecho")
x = 5
print(x) # Imprime 5
x -= 1
print(x) # Imprime 6
#constante
MAX_VELOCIDAD = 100
'''
bien nombrado
'''
print(MAX_VELOCIDAD)
maxPuntos=0
'''
mal nombrado
'''
a = 10 // 3
print (a)
# Esto funciona
y=1
'''
mal tipeado, dejar espacio
'''
x = 5 * y
x = 5 * (3 / 2)
media = (90 + 86 + 71 + 100 + 98) / 5
print("media=",media)
# Importar la biblioteca math
# Esta linea se usa una sola vez y al principio del
# del programa.
from math import *
x = sin(0) + cos(0)
print(x)
'''
mejor se entiende ->
'''
millas_recorridas = 294
galones_usados = 10.5
mpg = millas_recorridas / galones_usados # Aquรญ empleamos variables
print(mpg)
|
ef40374e7f88d42eb24666b687d3dab6be4181ee | ekougs/crack-code-interview-python | /ch5/decimal_binary_representation.py | 1,750 | 3.703125 | 4 | _decimal_separator = '.'
def decimal_binary_rep(decimal_str):
if _decimal_separator in decimal_str:
point_index = decimal_str.index(_decimal_separator)
else:
point_index = len(decimal_str)
int_part = _integer_binary_str(int(decimal_str[:point_index]))
# Decimal part should have less than 32 char
binary_str = int_part
decimal_part_str = ''
if point_index < len(decimal_str):
decimal_part_str += _decimal_separator
decimal_part = float(decimal_str[point_index:])
# binary part is equal to sum for i from 0 to n of Ci * 2 ^ -i
# to find Ci, you multiply the base 10 decimal part by 2
# if the product is >= 1 then Ci = 0 and we go on with the product minus 1
# otherwise Ci = 0 and we go on with the product
# and iterate until decimal part = 0 or the floating point limit is reached
while decimal_part > 0:
if len(decimal_part_str) == 32:
raise FloatingPointError
if decimal_part == 1:
decimal_part_str += '1'
break
decimal_part_shift = decimal_part * 2
if decimal_part_shift >= 1:
decimal_part_str += '1'
decimal_part = decimal_part_shift - 1
else:
decimal_part_str += '0'
decimal_part = decimal_part_shift
return binary_str + decimal_part_str
def _integer_binary_str(decimal, limit=None):
binary_str = ''
binary_str_length = 0
while decimal != 0:
binary_str += (str(decimal % 2))
binary_str_length += 1
if limit and binary_str_length > limit:
raise FloatingPointError
decimal >>= 1
return binary_str
|
6a8712d38612c2de97484b8b0e3156341bb2a5dd | C-TAM-TC1028-003-2113/tarea-1-YalejandroFuentes | /assignments/10Videojuego/src/exercise.py | 382 | 3.65625 | 4 | def main():
# Este programa calcula el total de la compra de los videojuegos nuevos y usados.
JuegosNuevos = int(input("Dame la cantidad de juegos nuevos: "))
JuegosUsados = int(input("Dame la cantidad de juegos usados: "))
Total = (1000 * JuegosNuevos) + (350 * JuegosUsados)
print("El total de la compra es:", Total)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.